Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 692
Dan Avatar asked Apr 07 '26 09:04

Dan


2 Answers

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!

like image 86
Alex Avatar answered Apr 09 '26 23:04

Alex


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.

like image 37
Robby Pond Avatar answered Apr 09 '26 22:04

Robby Pond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!