Android - I cannot update / redraw 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 will be shown again using the onActivityResult method.

I tried for hours to update a set of books after adding a new book, but no luck.

This is the code I 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, help.
Many thanks!

+3
source share
4 answers

I do not see where you are updating the ArrayList books that are data behind the ListView. If you update this object in onActivityResult, it should work correctly.

+1
source

This is what works for me

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

notifyDataSetChanged , !

+5

I had strange problems like this, but actually it is not, you can just replace 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);     
    } 
0
source
list.setAdapter(list.getAdapter());

Faster and easier solution

0
source

Source: https://habr.com/ru/post/1777535/


All Articles