首先:我已经对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
。感谢布鲁斯发现它!
答案 0 :(得分:1)
您正在使用小写提醒'当您设置匹配器时,实际的URI具有大写'提醒'。