Loader <cursor>仅加载选定的行+下一行

时间:2018-04-03 07:54:14

标签: android sqlite android-sqlite android-cursorloader android-loader

活动A 我正在加载一个包含我的表中所有值的列表,并设置了一个setOnItemClickListener来启动活动B 并发送 uri 使用所选项目的ID [ 1 ]通过发送数据

[ 1 ] Uri currentTestUri = ContentUris.withAppendedId(TestEntry.CONTENT_URI, id);

活动B 中,我的 onCreateLoader 带有投影:

String[] projection = {
       TestEntry._ID,
       TestEntry.COLUMN_TEST_ONE,
       TestEntry.COLUMN_TEST_TWO}

...使用return语句

return new CursorLoader(this,  
    mCurrentTestUri, //Got this from Activity A         
    projection,             
    null,                   
    null,                   
    null);  

我的 onLoadFinished 看起来像这样:

if (cursor.moveToFirst()) {
      int oneColumnIndex = cursor.getColumnIndex(TestEntry.COLUMN_TEST_ONE);
      int twoColumnIndex = cursor.getColumnIndex(TestEntry.COLUMN_TEST_TWO);

      String currentOne = cursor.getString(oneColumnIndex);
      String currentTwo = cursor.getString(twoColumnIndex);

      textViewOne.setText(currentOne);
      textViewTwo.setText(currentTwo);
}

到目前为止一切顺利,现在我希望显示下一行(右下方)的值,但使用不同的投影(我只需要_IDCOLUMN_TEST_ONE)并拥有 onLoadFinished textViewThree中显示COLUMN_TEST_ONE的值。

  

[两行的值应同时显示,而不是一个或   另一个]

我可以通过[ 2 ]从活动A 获取下一行的ID,然后通过putExtra将其作为字符串发送,但这是关于我的全部内容到目前为止。

[ 2

String nextItemId = String.valueOf(listView.getItemIdAtPosition(position + 1));
if((position+1) < lListView.getCount()) {
    intent.putExtra("prevID", nextItemId);
}

..或者我可以使用下一行ID创建有效的URI路径,并将其作为活动A中的字符串发送,并在需要时将其转换为活动B中的URI:

ContentUris.withAppendedId(TestEntry.CONTENT_URI, nextItemId)
  

如何更改活动B 以从下一行加载值   和当前的onCreate?

1 个答案:

答案 0 :(得分:2)

问题在于您的查询:


    Uri currentTestUri = ContentUris.withAppendedId(TestEntry.CONTENT_URI, id);

您要指定的是,您要查询具有特定id行。任何行id都不会在Cursor中返回。

相反,使用适当的选择参数查询表:


    // Load all rows that have id `firstId` or `secondId`
    return new CursorLoader(this,  
        TestEntry.CONTENT_URI,
        projection,             
        TestEntry._ID + "=? OR " + TestEntry._ID + "=?",                   
        new String[] {firstId, secondId},                   
        null);

然后您可以按照以下方式获取secondId行的值:


    if (cursor.moveToFirst()) {
          ...

          textViewOne.setText(currentOne);
          textViewTwo.setText(currentTwo);

          if (cursor.moveToNext()) {
              int index = cursor.getColumnIndex(TestEntry.COLUMN_TEST_ONE);
              String next = cursor.getString(index);
              // Use `next` as needed, may be passed to next activity via extras
          }
    }

相关问题