hamid reza gholami hamid reza gholami - 27 days ago 7
Android Question

adapter.notifyDataSetChanged do not work after search with search view

I have a search view that filter recycler view items; it properly filter items but when I close search view my adapter

notifyDataSetChanged
wont work for example if I add new item to recycler view until I close the app and open it again. This is my code for filtering items.

public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)){
adapter.resetList(userData.GetAllWords(user.getId()));
} else {
final ArrayList<Word> filteredModelList = filter(wordlist, newText);
adapter.setfilter(filteredModelList);
}
return false;
}

private ArrayList<Word> filter(ArrayList<Word> wordlistt, String query) {
query = query.toLowerCase();
final ArrayList<Word> filteredModelList = new ArrayList<>();
for (Word myword : wordlistt) {
if (myword.getWord().contains(query) || myword.getTranslation().contains(query)) {
filteredModelList.add(myword);
}
}
return filteredModelList;
}


And this is my code in adapter

public void setfilter(ArrayList<Word> filteredwordlist) {
wordlist = new ArrayList<>();
wordlist.addAll(filteredwordlist);
notifyDataSetChanged();
}

public void resetList(ArrayList<Word> newWordlist){
wordlist=new ArrayList<>();
wordlist.addAll(newWordlist);
notifyDataSetChanged();
}


I even reset my adapter when search view is closed like this

@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
adapter=new WordAdapter(MainActivity.this,userData.GetAllWords(user.getId()));
recyclerView.setAdapter(adapter);
return true;
}


but still nothing change in my recycler view

Answer

You are creating object of array everytime which means Adapter does not have same data instance to notify do this, just create wordlist object once in constructor rest clear it and add item in it.

 public void setfilter(ArrayList<Word> filteredwordlist) {
    //wordlist = new ArrayList<>();
    wordlist.clear();
    wordlist.addAll(filteredwordlist);
    notifyDataSetChanged();
}

Do same when reseting,