嘿伙计们我使用简单的适配器从我的数据库制作了数据列表视图,但我不知道每次数据库更改时如何更新它。任何帮助?notifyDataSetChanged();方法不起作用,我不知道该怎么做。
MainActivity
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_general_discussion); db = new SQLiteHandler(this); ArrayList<HashMap<String, String>> emaillist = db.getMessage(); if (emaillist.size() != 0) { ListAdapter adapter = new SimpleAdapter(MainActivity.this, emaillist, R.layout.raw_layout, new String[]{"user_posted", "post", "posted_at", "post_id"}, new int[]{ R.id.text_user_name, R.id.text_user_post, R.id.text_user_date, R.id.text_user_number}); setListAdapter(adapter); }
助手类
public ArrayList<HashMap<String, String>> getMessage(){ ArrayList<HashMap<String, String>> message = new ArrayList<HashMap<String, String>>(); String selectQuery = "SELECT * FROM " + TABLE_POSTING; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if ( cursor.moveToFirst()) { do { HashMap<String, String> map = new HashMap<String, String>(); map.put("post_id", cursor.getString(0)); map.put("user_posted", cursor.getString(1)); map.put("post", cursor.getString(2)); map.put("posted_at", cursor.getString(3)); message.add(map); } while (cursor.moveToNext()); } return message; }
答案 0 :(得分:0)
声明您的适配器&amp;列出全球水平
class example{
ListAdapter adapter;
ArrayList<HashMap<String, String>> emaillist;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_discussion);
db = new SQLiteHandler(this);
emaillist = db.getMessage();
if (emaillist.size() != 0) {
adapter = new SimpleAdapter(MainActivity.this, emaillist,
R.layout.raw_layout,
new String[]{"user_posted", "post", "posted_at", "post_id"}, new int[]{
R.id.text_user_name, R.id.text_user_post, R.id.text_user_date, R.id.text_user_number});
setListAdapter(adapter);
}
如果您只想更新
adapter.notifyDataSetChanged();
答案 1 :(得分:0)
将您的适配器声明为Public,然后调用
的 adapter.notifyDatasetChange();
强>
何时何地你想要。这会更新。
希望这有帮助。
答案 2 :(得分:0)
我认为没有直接的方法来检查数据库中是否有变化 但你可以像刷新一样做。
使您的适配器成为全局,当触发操作时再次填充适配器并写入adapter.notifyDatasetChange();
另一种方法是使用Thread
,将其放入类型AsyncTask
的内部类中
然后每分钟重新填充阵列
然后在每次检查之后写下adapter.notifyDatasetChange();
doInBackground(){
while(true){
checkDataBase();
refillAdapter();
adapter.notifyDatasetChange();
Thread.sleep(1000*60);// sec * 60 sec =1min
}
}
查看此链接如何使用AsyncTask类http://developer.android.com/reference/android/os/AsyncTask.html