2

How do you update an ArrayAdapter without losing the scrolling position?

This is how I currently do it. I create an update method in the ArrayAdapter subclass which does the following:

public void update(List<MyEntity> entities) {
    for (MyEntity entity : entities) {
        int position = this.getPosition(entity);
        if (position >= 0) {
            final MyEntity outdateEntity = this.getItem(position);
            this.insert(entity, position);
            this.remove(outdateEntity);
        } else {
            this.insert(entity, 0);         
        }
    }
}

public int getPosition(MyEntity updatedEntity) {
    for (int i = 0; i < this.getCount(); i++) {
        if (this.getItem(i).getId() == updatedEntity.getId()) {
            return i;
        }
    }
    return -1;
}

However, this seems awfully inefficient and error-prone. Is there a better way?

1 Answer 1

2

Why do you not extend BaseAdapter in the first place? There you just have to update your list internally and then call notifyDataSetChanged()... :-)

Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't that reset the current scrolling position?
Normally not - the list should stay where it is (at least if the appropriate scrolling position is not out of range of the list).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.