我对如何使用游标访问我需要使用 CursorLoader 模型的数据感到有点困惑。我能够使用 SimpleCursorAdapter 并将光标传递到 onLoadFinished 方法中适配器的 swapCursor 方法,您必须按如下方式实现。
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
facilityAdapter.swapCursor(cursor);
}
现在我需要查询数据库并根据返回的行数显示一个整数。我如何访问这些信息?我想存储某些选定行的信息(_id),以便我可以将其 bundle 起来并将其传递给下一个 Activity ,因为 id 是其他数据库表中的外键,我需要查询数据库。在 android 开发者网站上,我看到有游标类的访问器方法,例如 cursor.getInt、cursor.getString 等,我应该使用它们来访问我想要的数据吗。
最佳答案
看来您在这里有两个问题...所以我会一一回答。如果我误解了你的问题,请纠正我......
要获取表中的行数,请执行如下简单查询:
Cursor cur = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); int numColumns = cur.getCount(); cur.close();
多亏了 Android 适配器,检索所选项目的 ID 实际上非常简单。下面的示例概述了如何将 id 传递给另一个 Activity(例如,当单击 ListView 项目时)。
public class SampleActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { // pass this String to the Intent in onListItemClicked() public static final String ID_TAG = "id_tag"; private SimpleCursorAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* setup layout, initialize the Loader and the adapter, etc. */ setListAdapter(mAdapter); } @Override public void onListItemClick(ListView l, View v, int position, long id) { final Intent i = new Intent(getApplicationContext(), NewActivity.class); i.putExtra(ID_TAG, id); // pass the id to NewActivity. You can retrieve this information in // the Activity's onCreate() method with something like: // long id = getIntent().getLongExtra(SampleActivity.ID_TAG, -1); startActivity(i); } }
您必须自己创建一个 URI 来查询外部数据库。这可以通过类似的方式完成:
Uri uri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(id));
其中
CONTENT_URI
是适合您的ContentProvider
的 CONTENT_URI。
如果有帮助,请告诉我!
关于android - 如何使用 Cursor Loader 访问检索到的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8903104/