Bos*_*one 31 android group-by distinct android-contentresolver
什么是添加一种合适的方式DISTINCT
和/或GROUPBY
以ContentResolver
-基于查询.现在我必须为每个特殊情况创建自定义URI.有没有更好的办法?(我仍以1.5为最低共同标准编程)
kzo*_*tin 41
在查询contentResolver时你可以做得很好,使用:
String selection = Models.SOMETHING + "=" + something + ") GROUP BY (" + Models.TYPE;
Run Code Online (Sandbox Code Playgroud)
Bos*_*one 15
由于没有人来回答我只是想告诉我如何解决这个问题.基本上我会为每个案例创建自定义URI并传递selection
参数中的条件.然后在里面ContentProvider#query
我将识别案例并根据表名和选择参数构造原始查询.
这是一个简单的例子:
switch (URI_MATCHER.match(uri)) {
case TYPES:
table = TYPES_TABLE;
break;
case TYPES_DISTINCT:
return db.rawQuery("SELECT DISTINCT type FROM types", null);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
return db.query(table, null, selection, selectionArgs, null, null, null);
Run Code Online (Sandbox Code Playgroud)
小智 15
如果要将DISTINCT与SELECT一起使用多一列,则需要使用GROUP BY.
使用以下内容的Mini Hack over ContentResolver.query:
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri,
new String[]{"DISTINCT address","body"}, //DISTINCT
"address IS NOT NULL) GROUP BY (address", //GROUP BY
null, null);
if(c.moveToFirst()){
do{
Log.v("from", "\""+c.getString(c.getColumnIndex("address"))+"\"");
Log.v("text", "\""+c.getString(c.getColumnIndex("body"))+"\"");
} while(c.moveToNext());
}
Run Code Online (Sandbox Code Playgroud)
此代码从设备收件箱中为每个发件人选择最后一个短信.
注意:在GROUP BY之前,我们总是需要编写至少一个条件.结果ContentResolver.query方法中的SQL查询字符串将:
SELECT DISTINCT address, body FROM sms WHERE (type=1) AND (address IS NOT NULL) GROUP BY (address)
Run Code Online (Sandbox Code Playgroud)
小智 14
在重写的ContentProvider
查询方法中,有一个特定的URI映射到使用distinct.
然后使用SQLiteQueryBuilder
并调用该setDistinct(boolean)
方法.
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
boolean useDistinct = false;
switch (sUriMatcher.match(uri))
{
case YOUR_URI_DISTINCT:
useDistinct = true;
case YOUR_URI:
qb.setTables(YOUR_TABLE_NAME);
qb.setProjectionMap(sYourProjectionMap);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// If no sort order is specified use the default
String orderBy;
if (TextUtils.isEmpty(sortOrder))
{
orderBy = DEFAULT_SORT_ORDER;
}
else
{
orderBy = sortOrder;
}
// Get the database and run the query
SQLiteDatabase db = mDBHelper.getReadableDatabase();
// THIS IS THE IMPORTANT PART!
qb.setDistinct(useDistinct);
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
if (c != null)
{
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
Run Code Online (Sandbox Code Playgroud)
虽然我没有使用Group By,但我在内容解析器查询中使用了Distinct.
Cursor cursor = contentResolver
.query(YOUR_URI,
new String[] {"Distinct "+ YOUR_COLUMN_NAME},
null,
null, null);
归档时间: |
|
查看次数: |
34624 次 |
最近记录: |