Irma Elita Irma Elita - 6 months ago 245
Android Question

How to refresh listview in a custom adapter?

I made a custom listview with a custom adapter that populated from database. I can't update my listview whenever the data from database has changed. I have already tried using notifysetdatachanged() but it didn't work. Maybe it's because I putted the code in a wrong way. Please help me to solve this problem. Thanks.

ContactActivity.java



public void getImages2(){
class GetImages2 extends AsyncTask<Void,Void,Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected void onPostExecute(Void v) {
super.onPostExecute(v);
loading.dismiss();
customList = new CustomList(ContactActivity.this,GetAlImages2.imageURLs,GetAlImages2.bitmaps,GetAlImages2.code,GetAlImages2.name,GetAlImages2.phone,GetAlImages2.email);
listView.setAdapter(customList);
customList.notifyDataSetChanged();

}
@Override
protected Void doInBackground(Void... voids) {
try {
getAlImages2.getAllImages2();

} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
GetImages2 getImages = new GetImages2();
getImages.execute();
}





CustomList.java



public class CustomList extends ArrayAdapter<String> {
private Bitmap[] bitmaps;
private String[] urls;
private String[] code;
private String[] name;
private String[] email;
private String[] phone;

private Activity context;

public CustomList(Activity context, String[] urls, Bitmap[] bitmaps, String[] code, String[] name, String[] phone, String[] email) {
super(context, R.layout.activity_contact_item, urls);
this.context = context;
this.urls= urls;
this.bitmaps= bitmaps;
this.code= code;
this.name= name;
this.phone= phone;
this.email = email;
}

}





[EDIT]

Finally I have found the solution of my problem. My listview should have checked first whether the listview's adapter is empty or not. I added this code to my onPostExecute. Thanks for all your help.



customList = new CustomList(ContactActivity.this,GetAlImages2.imageURLs,GetAlImages2.bitmaps,GetAlImages2.code,GetAlImages2.name,GetAlImages2.phone,GetAlImages2.email);
if(listView.getAdapter() == null){ //Adapter not set yet.
listView.setAdapter(customList);
}
else{ //Already has an adapter
listView.setAdapter(customList);
customList.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}




Answer

Try this

Inside your onResume() add this

if (listvew!= null) {
  listvew.invalidateViews();
}
adapter.notifyDataSetChanged();
Comments