我终于找到了一个相当简单和明智的解决方案。我对 Content Providers 和 Content Resolvers 有很好的解释。后者用于访问前者,这意味着他们无法控制提供者中的内容,而是从它们那里获取数据。这意味着如果在对应的ContentProvider 的query() 方法中没有实现(覆盖)rawQuery(),则您不能让 Content Provider Client 使用它。
为了解决我的问题,我在提供程序客户端中使用了一个标志,并修改了我的内容提供程序以读取它,以便我可以使用 GROUP BY。我只是想根据特定列从数据库中获取唯一引用。
这就是解决方案,虽然不是很干净,但效果很好。
对于ContentProviderClient,
ContentProviderClient myCPClient = this.miContext.getContentResolver().acquireContentProviderClient(this.miUri);
//I declare some variables for the query
//'selection' will get all the rows whose "_id" is greater than 0, i.e. all the rows
String selection = BaseDatosParam.Tabla._ID + ">?";
String[] selectionArgs = {"0"};
//'groupBy' is not formatted in any particular way. I just need it to contain the pattern "GROUP BY"
String groupBy = "GROUP BY" + BaseDatosParam.Tabla.REF;
//the last field of the query corresponds to 'sortOrder', but I
Cursor c = myCPClient.query(Uri.parse(miUri.toString()),
projection, selection, selectionArgs, groupBy);
在ContentProvider,
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
String where = selection;
String groupBy = null;
SQLiteDatabase db = this.miBDManager.getWritableDatabase();
//We just check out whether 'sortOrder' includes the pattern "GROUP BY", otherwise that field will remain null
Pattern myPat = Pattern.compile("GROUP BY");
Matcher myMat = myPat.matcher(sortOrder);
if (myMat.find())
groupBy = myMat.replaceFirst("");
Cursor c = db.query(BaseDatosParam.Tabla.NOMBRE_TABLA, projection, where, selectionArgs, groupBy, null, null);
c.setNotificationUri(this.getContext().getContentResolver(), uri);
return c;
}
问候,