gpt4 book ai didi

mysql - 使用 ContentProviderClient 从外部应用程序 rawQuery 一个 ContentProvider

转载 作者:行者123 更新时间:2023-11-30 23:06:16 25 4
gpt4 key购买 nike

这几天我一直在为一个问题苦苦挣扎。我正在与两个不同的应用程序(应用程序 A 和应用程序 B)共享一个内容提供者。所有关于数据库创建和内容提供者管理的事情都由应用程序 A 完成。应用程序 B 只需使用相应的权限和内容提供者客户端访问它。

ContentProviderClient myCPClient = this.miContext.getContentResolver().acquireContentProviderClient(this.miUri);

当尝试以更复杂的方式查询数据库时出现问题,即使用一些关键字,如 GROUP BY、HAVING 等。我需要根据一个特定的列获取唯一引用(我想使用 GROUP BY ),而且我发现 ContentProviderClient 没有 rawQuery() 方法,而是一个简化的 query() 方法(与SQLiteDatabase 类中可用的一个,它允许制定适当的 MySQL 命令)。

我检查过这个answer ,但是由于我的 ContentProvider 是从不同的应用程序访问的,所以我没有像 MyContentProvider 这样的类。

总而言之,有什么方法可以对由不同应用程序生成的 ContentProvider 进行正确的查询(如 rawQuery())?

最佳答案

我终于找到了一个相当简单和明智的解决方案。我得到了关于内容提供者和内容解析器的很好的解释。后者用于访问前者,这意味着他们无法控制提供程序中的内容,但可以从中获取数据。这意味着如果未在相应 query() 方法中实现(覆盖),则您无法让 Content Provider Client 使用 rawQuery() >内容提供者

为了解决我的问题,我在我的提供商客户端中使用了一个标志,并修改了我的内容提供商以读取它,以便我可以使用 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;
}

问候,

关于mysql - 使用 ContentProviderClient 从外部应用程序 rawQuery 一个 ContentProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com