首先,我筛选了有关SO主题的许多问题,但仍未能给出正确的答案。
这是我的代码的(简化方式)版本:
private static UriMatcher
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int
HOMEWORK_TABLE_REQUEST = 1,
CLASS_TABLE_REQUEST = 2,
SETTINGS_TABLE_REQUEST = 3,
HOMEWORK_ITEM_REQUEST = 4,
CLASS_ITEM_REQUEST = 5,
SETTINGS_ITEM_REQUEST = 6;
static {
uriMatcher.addURI("org.dvc.homeworkReminder.homeworkProvider", "homework", HOMEWORK_TABLE_REQUEST);
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "homework/#", HOMEWORK_ITEM_REQUEST);
uriMatcher.addURI("org.dvc.homeworkReminder.homeworkProvider", "class", CLASS_TABLE_REQUEST);
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "class/#", CLASS_ITEM_REQUEST);
uriMatcher.addURI("org.dvc.homeworkReminder.homeworkProvider", "settings", SETTINGS_TABLE_REQUEST);
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "settings/#", SETTINGS_ITEM_REQUEST);
}
这是我的查询方法:
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor = null;
Log.i("dfg", "Query method called");
Log.i("dfg", "Uri = " + uri.toString());
Log.i("dfg", "Match: " + uriMatcher.match(uri));
switch(uriMatcher.match(uri)) {
case HOMEWORK_ITEM_REQUEST:
Log.i("dfg", "HOMEWORK_ITEM_REQUEST");
cursor = database.readCursorById(Integer.parseInt(uri.getLastPathSegment()));
break;
case HOMEWORK_TABLE_REQUEST:
Log.i("dfg", "HOMEWORK_TABLE_REQUEST");
cursor = database.readAllHomework();
break;
case CLASS_ITEM_REQUEST:
case CLASS_TABLE_REQUEST:
case SETTINGS_ITEM_REQUEST:
case SETTINGS_TABLE_REQUEST:
cursor = null;
break;
default:
cursor = null;
break;
}
return cursor;
}
我没有针对类请求或设置请求的实现,所以这就是为什么我只默认返回
null
的原因。发生的是我的switch
语句一直下降到default:
,并在以后的代码中引起了NPE的麻烦。您会发现我的代码中有5条Log
语句。将以下内容打印到LogCat。 (为什么总叫logcat?)Query method called
Uri = content://org.dvc.homeworkReminder.homeworkProvider/homework/24
Match: -1
现在正在测试的uri应该与我添加的第二个模式匹配,对吗?我还了解了
Uri.parse()
方法如何在另一个线程上与UriMatcher
的通配符混淆,因此我使用以下代码构建了上述打印的Uri
:Uri returnUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority("org.dvc.homeworkReminder.homeworkProvider").appendPath("homework").appendPath(String.valueOf(id)).build();
那里的
id
变量取决于其他与实际无关的东西。我的问题是为什么
UriMatcher
不起作用,我将如何解决它?固定:
我在以下几行有不正确的大写:
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "homework/#", HOMEWORK_ITEM_REQUEST);
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "class/#", CLASS_ITEM_REQUEST);
uriMatcher.addURI("org.dvc.homeworkreminder.homeworkProvider", "settings/#", SETTINGS_ITEM_REQUEST);
注意
r
中的小写字母homeworkreminder
。感谢布鲁斯发现它! 最佳答案
设置匹配器时,您使用的是小写的“提醒”,但是实际的URI带有大写的“提醒”。