【问题标题】:How to use Cursor Loader to access retrieved data?如何使用 Cursor Loader 访问检索到的数据?
【发布时间】:2012-01-17 23:22:55
【问题描述】:

我有点困惑如何使用光标访问我需要使用 CursorLoader 模型的数据。我能够使用 SimpleCursorAdapter 并将光标传递给 onLoadFinished 方法中适配器的 swapCursor 方法,您必须按如下方式实现。

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

    facilityAdapter.swapCursor(cursor);

}

现在我需要查询数据库并根据返回的行数显示一个整数。我如何访问这些信息?我想存储某些选定行的信息(_id),以便我可以将其捆绑并将其传递给下一个活动,因为 id 是其他数据库表中的外键,我需要查询数据库。在 android 开发者网站上,我看到游标类有一些访问方法,例如 cursor.getInt、cursor.getString 等,我应该使用它们来访问我所追求的数据吗?

【问题讨论】:

    标签: android sqlite android-cursor


    【解决方案1】:

    您似乎有两个问题......所以我会回答他们两个。如果我误解了您的问题,请纠正我...

    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 开发网站有很多不推荐使用的示例,我想确保我使用当前标准访问数据。
    • @Alex:- 先生,我有一个通过服务扩展的课程。现在,当我从移动收件箱访问消息时,它会一次又一次地发出一条消息,而无需开始管理光标 () 我无法理解这一点请告诉我该怎么办?
    • @DeepankerChaudhary 在 StackOverflow 上提问,然后复制粘贴链接,我可以尝试回答。 :)
    • 看到这个任何帮助将不胜感激...stackoverflow.com/questions/13290476/…
    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2012-09-13
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多