【发布时间】:2016-01-28 12:14:07
【问题描述】:
大家好,我已经使用简单的适配器从我的数据库中创建了一个数据列表视图,但我不知道如何在每次数据库更改时更新它。有什么帮助吗?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); }
HelperClass
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; }
【问题讨论】:
-
能否请您添加更新功能以检查错误
-
你在哪里调用
notifyDataSetChanged,你是在主线程(也就是ui线程)上调用它吗? -
嘿,我将它添加到发布按钮点击事件中,所以每次我按下按钮时,列表都会更新
-
btnposting.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String post = inputPost.getText().toString().trim(); String user_posted = txtName.getText ().toString().trim(); if (!post.isEmpty()) { postThreads(post, user_posted); } else { Toast.makeText(getApplicationContext(), "请输入您的详细信息!", Toast.LENGTH_LONG ) .show(); } } });
标签: java android database android-sqlite simpleadapter