简体   繁体   English

使用SimpleCursorAdapter进行Android ListView更新

[英]Android ListView update with SimpleCursorAdapter

Hey i use a listview for demonstrate entries which are stored in a database. 嘿,我使用listview来显示存储在数据库中的条目。 I also have a EditText element and a button which adds the content of the EditText into the Database. 我还有一个EditText元素和一个按钮,它将EditText的内容添加到数据库中。 To bind the view to the database content i use the SimpleCursorAdapter and following populate function: 要将视图绑定到数据库内容,我使用SimpleCursorAdapter和以下populate函数:

private void populate() {
    cursor = dbAdapter.getAllItems();
    startManagingCursor(cursor);

    String[] from = new String[] { DBAdapter.KEY_TASK };
    int[] to = new int[] { android.R.id.text1 };

    // Now create an array adapter and set it to display using our row
    cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);
    list.setAdapter(cursorAdapter);
}

If i added a new entry, by clicking on the button i want to refresh the listview but this only works with the populate function and not with the common adapter function notifyDataSetChanged(); 如果我添加了一个新条目,通过单击我想刷新列表视图的按钮,但这只适用于populate函数而不适用于通用适配器函数notifyDataSetChanged(); . Do i have a bug or is this the right way to refresh a listview? 我有错误或者这是刷新列表视图的正确方法吗?

Have you seen this , tried the swap cursor method, or tried just simply calling setAdapter() again? 你有没有看过这个 ,试过交换游标方法,或者只是简单地再次调用setAdapter()

I had a similar issue where I could not get my list to update, and what I did was just create a refreshListView() method. 我有一个类似的问题,我无法让我的列表更新,我做的只是创建一个refreshListView()方法。 Now you can call this initially from your onCreate(), AND anytime a user adds something to the DB. 现在你可以从你的onCreate()开始调用它,并在用户向数据库添加内容时随时调用。 All it does is re-bind the listview to a cursor. 它只是将listview重新绑定到游标。 With all the deprecating methods (requery()), and issues with notifyDataSetChanged(), I decided this was the easiest way. 使用所有弃用方法(requery())以及notifyDataSetChanged()的问题,我认为这是最简单的方法。

Please refer this link...it works like charm 请参考此链接...它的功能就像魅力一样

Update SimpleCursorAdapter while maintaining scroll position in ListView 更新SimpleCursorAdapter,同时在ListView中保持滚动位置

for dynamic listview on scroll i added new item from database .. I did mistake here .. i was assigning new adapter for each time for same simplecursoradapter . 对于滚动的动态列表视图我从数据库添加了新项目..我在这里错了..我为同一个simplecursoradapter每次分配新的适配器。 Instead of creating new adapter. 而不是创建新的适配器。 just use 只是用

adapter.changecursor(newcursorValue);
adapter.notifydatasetChanged();
 lsMedicine1.setSelectionFromTop(lsMedicine1.getLastVisiblePosition()-20, 0);

你需要调用swapcursor()之前notifyDataSetChanged()的适配器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM