android - 如何使用 Cursor Loader 访问检索到的数据?

标签 android sqlite android-cursor

我对如何使用游标访问我需要使用 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 等,我应该使用它们来访问我想要的数据吗。

最佳答案

看来您在这里有两个问题...所以我会一一回答。如果我误解了你的问题,请纠正我......

  1. 要获取表中的行数,请执行如下简单查询:

    Cursor cur = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
    int numColumns = cur.getCount();
    cur.close();
    
  2. 多亏了 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/

相关文章:

android - 制作动态壁纸

java - 多次执行 Runnable post 到 Looper 的 Activity

php - 使用移动网页检测 Android 应用程序是否已安装在设备上 - PHP 和 JS

ruby-on-rails - 数据库适配器的 Rails aws elastic beanstalk 部署错误

android - 这些代码如何从 Android Gallery 加载图像

android - LiveData Observer停止进行配置更改

ruby-on-rails - 错误 "no such file to load"-- sqlite3/sqlite3_native (LoadError)

android - 如何(正确)从 startManagingCursor 过渡到 CursorLoader?

java - 移动 Cursor 时出现 android.database.CursorWindowAllocationException

java - JDBCPreparedStatement 似乎忽略占位符