更新ListView

时间:2015-01-10 17:29:17

标签: android listview android-listview

我从数据库接收光标并将andapter设置为ListView。然后我将新行插入数据库,但我的ListView没有更新。

Cursor c = getContentResolver().query(GEN_URI, null, null, null, null);

String[] from = { DB.column_name };
int[] to = { R.id.textViewItem };

myAdapter = new SimpleCursorAdapter(this, R.layout.shop_list_item, c, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER );
	
ShopList.setAdapter(myAdapter);

ContentValues newC = new ContentValues();
newC.put(DB.column_name, "Селёдочка");
Uri uri = getContentResolver().insert(SHOP_LIST_URI, newC);
getContentResolver().query(GEN_URI, null, null, null, null);
myAdapter.notifyDataSetChanged();

如果我设置标志SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER - ListView不更新。 如果我设置标志SimpleCursorAdapter.FLAG_AUTO_REQUERY- ListView更新。

做什么?

2 个答案:

答案 0 :(得分:2)

您可以尝试myadapter.notifyDataSetChanged();

答案 1 :(得分:0)

您必须通知适配器数据已更改并告知其刷新。

adapter.notifyDataSetChanged();

使用标志自动查询时,光标自动requeris,因此,您的列表视图会更新,但据我所知,此FLAG_AUTO_REQUEY现已弃用。

<强>更新

经过一些谷歌搜索后,我发现notifyDataSetChanged与SimpleCursorAdapters无关。

所以解决方法是requers()。但正如我所说,它已被弃用,新方法是通过更改Cursor。

adapter.changeCursor(cursor) and send it to your adapter.

以下是google关于requery()的官方文档。