Dan
Dan

Reputation: 16236

Android - I can't refresh / redraw a ListView

I have a ListView that lists a set of books.
The user can add a new book and, after that, the set of books is shown again using the onActivityResult method.

I have been trying for hours to get the set of books to refresh after adding a new book but with no luck, at all.

This is the code I have tried:

public class BookActivity extends Activity {

    private ArrayList<Book> books = null;   
    private BookItemAdapter bookItemAdapter;
    ListView booksSetView = null;    

    @Override
    public void onCreate(Bundle savedInstanceState) {   
        books = new ArrayList<Book>();        
        booksSetView = (ListView)findViewById(R.id.booksSet);   

        Cursor booksCursor = null;

        booksCursor = getBooksCursor();                      
        if (booksCursor.moveToFirst())
        {
            do
            {   
                books.add(getBookFromCursor(booksCursor));                  
            } while(booksCursor.moveToNext());
        }

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter        
        booksSetView.setAdapter(bookItemAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter.notifyDataSetChanged();
        booksSetView.invalidate();
        booksSetView.invalidateViews();     
    }
}

Please some help.
Thanks a lot!

Upvotes: 3

Views: 3903

Answers (4)

Jack
Jack

Reputation: 1

list.setAdapter(list.getAdapter());

Faster and easiest solution

Upvotes: 0

Alex
Alex

Reputation: 654

This is what works for me

Adapter adapter = list.getAdapter();
list.setAdapter(null);
list.setAdapter(adapter);

it forces notifyDataSetChanged to get fired and it works like a charm!

Upvotes: 5

blindstuff
blindstuff

Reputation: 18348

I've had wierd issues like this, while it really isnt pretty, you can just substitute notifyDataSetChanged for the adapter constructor.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
            Log.e("BOOKS MANAGER", "trying to refresh");

        bookItemAdapter = new BookItemAdapter(this, R.layout.book_item, books, 0); // BookItemAdapter is a ArrayAdapter        
        booksSetView.setAdapter(bookItemAdapter);     
    } 

Upvotes: 0

Robby Pond
Robby Pond

Reputation: 73484

I don't see where you are updating the books ArrayList which is the data behind the ListView. If you update that object in onActivityResult then it should work correctly.

Upvotes: 1

Related Questions