问题描述
我想对已经创建的数据库进行查询,其中案例 1 是获取所有数据,而案例 2 是给我带来两个值,其中 user_id 和 dt(时间戳格式为“yyyy-MM-dd kk:mm:ss ") 匹配通过,内容提供者。但是,当我在 Content Provider 上使用代码 2 进行查询时,uri 匹配器的方法 match 返回 -1,而如果我使用代码 1,则可以正常工作。我也尝试在 switch 中使用 default 而不是 case 2,它也工作正常。如果有人能给我提示可能是什么原因,我将不胜感激。
内容提供者类
private static UriMatcher uriMatcher;
private DbHelper dbHelper;
private static String AUTHORITY = "com.example.foo";
public static final String CONTENT_URI = "content://"+AUTHORITY;
static {
uriMatcher = new UriMatcher (UriMatcher.NO_MATCH);
uriMatcher.addURI (AUTHORITY,"/data",1);
uriMatcher.addURI (AUTHORITY,"/data/#",2);
}
@Override
public boolean onCreate() {
dbHelper = new DbHelper (getContext ());
return false;
}
.
.
.
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri,@Nullable String[] projection,@Nullable String selection,@Nullable String[] selectionArgs,@Nullable String sortOrder) {
Cursor result = null;
int bar = uriMatcher.match (uri);
switch (bar){
case 1:
result = dbHelper.selectAll ();
break;
default:
String[] data = uri.getPathSegments ().toArray (new String[0]);
result = dbHelper.selectDataByUserId (data[1],data[2]);
}
return result;
}
MainActivity 类
@Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
ContentResolver resolver = this.getContentResolver ();
String[] test = (String[]) Uri.parse (DataContentProvider.CONTENT_URI+"/data/"+user_id+"/"+dt).getPathSegments ().toArray (new String[0]);
Cursor cursor = resolver.query (Uri.parse (DataContentProvider.CONTENT_URI+"/data/"+user_id+"/"+dt),null,null);
if (cursor.movetoFirst ()) {
lon.setText (cursor.getString (1));
lat.setText (cursor.getString (2));
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exercise">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.foo">
<activity android:name=".ThirdActivity">
</activity>
<activity android:name=".SecondActivity" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="com.example.foo"
android:name=".DataContentProvider"
android:exported="true">
</provider>
</application>
</manifest>
解决方法
您需要从添加到匹配器的 URI 中删除前导正斜杠 /
。
所以替换:
uriMatcher.addURI (AUTHORITY,"/data",1);
uriMatcher.addURI (AUTHORITY,"/data/#",2);
与:
uriMatcher.addURI (AUTHORITY,"data","data/#",2);