Ali*_*lin 5 sqlite android android-cursorloader android-loader android-sqlite
在活动A中,我正在加载一个包含我表中所有值的列表,并设置了一个setOnItemClickListener来启动活动B并通过发送数据发送带有所选项的id [ 1 ] 的uri
[ 1 ]
Uri currentTestUri = ContentUris.withAppendedId(TestEntry.CONTENT_URI, id);
在活动B中,我的onCreateLoader包含投影:
String[] projection = {
TestEntry._ID,
TestEntry.COLUMN_TEST_ONE,
TestEntry.COLUMN_TEST_TWO}
Run Code Online (Sandbox Code Playgroud)
...带有return语句
return new CursorLoader(this,
mCurrentTestUri, //Got this from Activity A
projection,
null,
null,
null);
Run Code Online (Sandbox Code Playgroud)
我的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);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止一切顺利,现在我希望显示下一行(右下方)的值,但是使用不同的投影(我只需要_ID和COLUMN_TEST_ONE)并且onLoadFinished显示COLUMN_TEST_ONE的值textViewThree.
[两行的值应该同时显示,而不是一个或另一个]
我可以使用[ 2 ] 从活动A获取下一行的ID,并通过putExtra将其作为字符串发送,但这是我到目前为止的所有内容.
[ 2 ]
String nextItemId = String.valueOf(listView.getItemIdAtPosition(position + 1));
if((position+1) < lListView.getCount()) {
intent.putExtra("prevID", nextItemId);
}
Run Code Online (Sandbox Code Playgroud)
..或者我可以使用下一行ID创建一个有效的URI路径,并将其作为活动A中的字符串发送,并在需要时将其转换为活动B中的URI:
ContentUris.withAppendedId(TestEntry.CONTENT_URI, nextItemId)
Run Code Online (Sandbox Code Playgroud)
我应该如何更改活动B以从下一行 和当前的onCreate 加载值?
问题出在您的查询上:
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
}
}