Android - notifyDataSetChanged () not working

I created a custom ArrayAdapter that displays a list of questions. I request db, convert this data, pass the data to an array and pass the array to the ArrayAdapter to display the list.

dbData = getDbData(); List<Question> questions = getQuestions(1L); dbData.closeDb(); setContentView(R.layout.activity_questions); adapter = new QuestionsAdapter(this, getCurrentContext(), questions, 1L, dbData); 

In my application, you can click on another question, manipulate some things and return to the main list. The underlying array has not changed yet since the changes were saved in db. I request db again, run my transforms, and then my array is updated. I do this in my onResume() method, but the adapter will not recognize any changes using the notifyDataSetChanged() method. My onResume() looks like this:

 @Override protected void onResume() { super.onResume(); dbData = getDbData(); questions = getQuestions(1L); adapter = new QuestionsAdapter(this, getCurrentContext(), questions, 1L, dbData); items.setAdapter(adapter); } 

I need to query db, do the transforms, create my array, and then create a new adapter so that my changes appear in the main list. Why can't I just do:

 @Override protected void onResume() { super.onResume(); dbData = getDbData(); questions = getQuestions(1L); adapter.notifyDataSetChanges(); } 

What do I need to do to make this work? Thanks for the help.

+4
source share
1 answer

The adapter stores a copy of all elements, so when you call notifyDataSetChanged, it checks its own copy of the elements

try the following:

 @Override protected void onResume() { super.onResume(); dbData = getDbData(); questions = getQuestions(1L); adapter.clear(); adapter.addAll(questions); // API level [1..10] use for(..){ adapter.add(question.get(index)) } or simply implement addAll method in you custom adapter for your own convenience (thanks to @Mena) adapter.notifyDataSetChanged(); } 
+15
source

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


All Articles