我使用自定义适配器从数据库中填充自定义列表视图。当数据库中的数据发生更改时,我无法更新列表视图。我已经尝试过使用notifysetdatachanged()方法,但它没有起作用。可能是因为我放置代码的方式不正确。请帮助我解决这个问题。谢谢。
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;
}
}
[编辑]
最终我找到了解决问题的方法。我的列表视图应该首先检查列表视图的适配器是否为空。我将这段代码添加到我的onPostExecute中。感谢您的所有帮助。
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();
}