所以我正在做的是: 有歌曲,按特定顺序。 我正在存储歌曲的 ID 列表,以便稍后可以按相同的顺序获取它们。
我将 ID 列表存储在变量 in
中,这就是我获取它们的方式:
StringBuilder sb = new StringBuilder( in.length * 2 - 1 );
sb.append( "?" );
for ( int i = 1; i < in.length; i ++ )
{
sb.append( ",?" );
}
String strIn = sb.toString( );
songCursor = context.getContentResolver( ).query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, TRACK_COLUMNS,
MediaStore.MediaColumns._ID + " IN (" + strIn + ")", in, null );
一切工作正常,唯一的问题是,列表的顺序与存储的顺序不同。在这里我不能使用排序顺序,因为显然没有指定我想要的顺序。我希望它按照存储的顺序排列,但我不知道该怎么做。
这也是将鼠标悬停在查询上时给出的信息,因此可以解释原因,但我没有解决方案。
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection.
例如:
在上图中,我按顺序存储了所有歌曲的 id。
但是当我检索它们时,顺序发生了变化。
最佳答案
按照 this post 中的示例,下面的代码为 query()
调用中的 sortOrder
参数构建一个 CASE
表达式,以及 selection
论证。
StringBuilder inStr = new StringBuilder(MediaStore.MediaColumns._ID)
.append(" IN (?");
StringBuilder orderStr = new StringBuilder("CASE ")
.append(MediaStore.MediaColumns._ID)
.append(" WHEN ")
.append(in[0])
.append(" THEN 0");
for (int i = 1; i < in.length; i++) {
inStr.append(",?");
orderStr.append(" WHEN ")
.append(in[i])
.append(" THEN ")
.append(i);
}
inStr.append(")");
orderStr.append(" END, ")
.append(MediaStore.MediaColumns._ID)
.append(" ASC");
Cursor songCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
TRACK_COLUMNS,
inStr.toString(),
in,
orderStr.toString());
CASE
表达式本质上是为每个 ID 分配一个别名值以进行排序,而不是按实际 ID 值排序。无论选择中的第一个 ID 是什么,其别名值为 0
,第二个为 1
,第三个为 2
,依此类推. 按这些值升序排序,生成的 Cursor
将按照选择中传递的 ID 的顺序排列。
关于android - 在 SQLite 中按选择参数的顺序对查询结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859304/