android - 更改 ListActivity 的托管游标的正确方法是什么

标签 android cursor listactivity

我在其顶部有一个 ListActivity,我想要一个微调器以允许用户选择 ListView 实际应该显示的内容。

在 onCreate 方法中,我实例化了我的第一个游标并调用了 startManagingCursor()。我还实例化了一个负责呈现 View 的自定义 CursorAdapter。

我想知道的是当用户在过滤器微调器中选择一个项目时更改光标的正确方法。

我正在做的是向微调器添加一个 OnItemSelectedListener 并在 onItemSelected() 方法中创建一个新的 Cursor,然后创建一个新的 CursorAdapter,然后调用

停止管理光标(当前光标); 当前光标 = 新光标; 开始管理光标(当前光标); setListAdapter(newAdapter);

这样做合适吗? 我还应该/还能怎么做? 我忘记了什么吗? 这很丑吗?

这是一些代码:

public class MyListActivity extends ListActivity {


private Spinner typeFilterSpinner;

private MyListAdapter cursorAdapter;

private Cursor currentCursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.my_layout);

    typeFilterSpinner = (Spinner) findViewById(R.id.TypeFilterSpinner);

    typeFilterSpinner.setOnItemSelectedListener(new SpinnerItemSelectedListener());

    currentCursor = MyDAO.getInstance().getMyCursor(null);
    startManagingCursor(currentCursor);

    cursorAdapter = new SelectionListAdapter(this, currentCursor);
    setListAdapter(cursorAdapter);
}

class SelectionListAdapter extends CursorAdapter {

     public FavouriteLocationSelectionListAdapter(Context context, Cursor cursor){
        super(context, cursor, true);

        [....] other initialization stuff here
    }
    [....] overriden rendering methods here
}   

public class SpinnerItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {

        Long mi = spinnerItems.get(pos);
        Cursor newCursor = MyDAO.getInstance().getMyCursor(mi);

        //TODO maybe call setCursor on the adapter here instead of instanciating a new cursor

        SelectionListAdapter newAdapter = 
            new SelectionListAdapter(MyListActivity.this, newCursor);

        stopManagingCursor(currentCursor);
        currentCursor = newCursor;
        startManagingCursor(currentCursor);
        setListAdapter(newAdapter);

    }

    public void onNothingSelected(AdapterView parent) {
      // woooork ?
    }
}   

就是这个主意。

感谢您的帮助!

最佳答案

stopManagingCursor 不会关闭 Cursor,因此您需要在切换它们时关闭它们。正如您在代码中指出的那样,最好保留相同的适配器,并为其提供新的游标。作为奖励,调用 CursorAdapter.changeCursor(Cursor) 将为您关闭旧的 Cursor

关于android - 更改 ListActivity 的托管游标的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5137537/

相关文章:

java - 安卓.content.res.Resources$NotFoundException : File from xml type layout resource ID #0x1020014

android - 如何在 ListView 中显示数据库中的数据?

android - ListActivity 上的 Listview 在 setListAdapter 上抛出 ResourceNotFound 异常

android - 如何优雅地关闭辅助 Activity ?

java - exoplayer 不玩添加并崩溃了

android - 使用选择器从外部存储加载文件

android - 在 CursorAdapter 中更改光标未正确更新列表项 View

Android:使用 Viewpager 将 Activity 置于最前面的通知

jquery - 使用 jQuery 拖动 anchor : IE not updating cursor

jquery - Safari:自定义光标在单击时更改为默认值