3

我正在尝试刷新使用创建为 SimpleCursorAdapter 的 ListAdapter 的 ListView。

这是我在填充 ListView 的 onCreate 中创建 Cursor 和 ListAdapter 的代码。

tCursor = db.getAllEntries();       

ListAdapter adapter=new SimpleCursorAdapter(this,
                R.layout.row, tCursor,
                new String[] columns,
                new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter);

然后,我用另一种方法将一些数据添加到数据库中,但我不知道如何刷新 ListView。stackoverflow 和其他地方的类似问题提到了使用 notifyDataSetChanged() 和 requery(),但 ListAdapter 或 SimpleCursorAdapter 的方法都不是。

4

4 回答 4

5

我可以通过创建新适配器并再次调用 setListAdapter 来刷新 ListView。

我在另一种方法中将其命名为adapter2。

tCursor = db.updateQuery();       

ListAdapter adapter2=new SimpleCursorAdapter(this,
                R.layout.row, tCursor,
                columns,
                new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter2);

我不确定为什么这是必要的,但它现在有效。如果有人有更好的解决方案,我愿意尝试。

于 2011-02-25T05:23:55.173 回答
0

在这种情况下,我建议Adapter通过扩展BaseAdapter类来使用 custom 。

于 2011-02-25T03:54:12.323 回答
0

该方法notifyDataSetChanged来自SimpleCursorAdapter父类BaseAdapter。父实现ListAdapter,你应该能够将它传递给你的ListView.

尝试:

tCursor = db.getAllEntries();       

BaseAdapter adapter=new SimpleCursorAdapter(this,
            R.layout.row, tCursor,
            new String[] columns,
            new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter);


那么你应该可以使用notifyDataSetChanged.

于 2011-02-25T05:09:26.653 回答
0

如果需要从同一类中的其他方法访问适配器,则可以将适配器定义为类变量。然后你可以调用changeCursor()刷新ListView。

public class mainActivity extends AppCompatActivity {
    // Define the Cursor variable here so it can be accessed from the entire class.
    private SimpleCursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_coordinator_layout)

        // Get the initial cursor
        Cursor tCursor = db.getAllEntries();       

        // Setup the SimpleCursorAdapter.
        adapter = new SimpleCursorAdapter(this,
            R.layout.row,
            tCursor,
            new String[] { "column1", "column2" },
            new int[] { R.id.rowid, R.id.date },
            CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        // Populate the ListAdapter.
        setListAdapter(adapter);
    }

    protected void updateListView() {
        // Get an updated cursor with any changes to the database.
        Cursor updatedCursor = db.getAllEntries();

        // Update the ListAdapter.
        adapter.changeCursor(updatedCursor);
    }
}

public static如果需要从另一个类中的方法更新列表视图,则应声明适配器变量

public static SimpleCursorAdapter adapter;
于 2016-06-28T23:55:52.137 回答