[英]simple adapter cant update database
大家好,我已经使用简单的适配器对数据库中的数据进行了列表视图,但是我不知道每次数据库更改时都如何更新。有什么帮助吗?notifyDataSetChanged(); 方法不起作用,我找不到解决方法。
主要活动
@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; }
声明您的适配器并列出全局级别
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();
将适配器声明为“公共”,然后致电
adapter.notifyDatasetChange();
无论何时何地。 这将更新。
希望这可以帮助。
我认为没有直接的方法可以检查数据库中是否有更改,但是您可以执行“刷新”之类的操作。
将您的适配器设置为全局适配器,并在触发操作时再次填充适配器并写入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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.