从 SimpleCursorAdapter 获取游标



我有一个实现 LoaderManager.LoaderCallbacks Cursor 类的活动。我有这个函数,它正在从SQlite获取数据。

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    switch (id) {
        case ITEM_LOADER_ID:
            // The uri points to Item, which is the items in the inventory
            Uri uri = InventoryContract.Item.contentUriWithAccount(mCloverAccount);
            String sortOrder = InventoryContract.Item.NAME;
            String selection = "";
            try {
                selection = InventoryContract.ItemColumns.CODE;
            catch (Exception e){
                Log.e("Error",e.toString());
            }
            return new CursorLoader(HomeActivity.this, uri, null, selection, null, sortOrder);
        default:
            // An invalid id was passed in
    }
    throw new IllegalArgumentException("Unknown Loader ID");
}

我有一个 SimpleCursorAdapter

SimpleCursorAdapter adapter = new SimpleCursorAdapter(
            this,
            android.R.layout.simple_list_item_2,
            null,
            new String[]{InventoryContract.Item.NAME, InventoryContract.Item.PRICE_TYPE},
            new int[]{android.R.id.text1, android.R.id.text2},
            0
    );

这是功能性的并获取数据,但我想获取光标,以便我可以检索所有信息并存储到 List 中以供执行后。我搜索了所有相关链接以获取光标,并找到了一个代码:

    Cursor c = adapter.getCursor();
    try {
        int i = 0;
        while (c.moveToNext()){
            Log.e("In Log Cursor",c.getString(i));
            i++;
        }
        c.close();
    }
    catch (Exception e){
        Log.e("Error",e.toString());
    }            

但它正在获得空光标。我想获取该数据并制作自定义适配器以进行进一步操作。请帮助我找到解决方案或任何其他方法,以从SQlite获取该数据并存储为列表,我可以在获取后使用它,并且可以在RecyclerView中进行设置。提前谢谢。

我认为这是一个旧帖子,但我认为它可以帮助某人。 你可以在 onloadFinshed 方法中实现他的步骤

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);
        /*
        data.moveToFirst();
    if (data.getCount() != 0) {
        for (int i = 0; i < data.getCount(); i++) {
            String s = data.getString(data.getColumnIndex(column no));
            data.moveToNext();
        }
    }

}

最新更新