我正在尝试使用SQLiteAssetHelper将预填充的SQLITE表添加到我的内容提供程序,但uri匹配器不匹配。我可以通过标准SQL访问/修改表,但使用游标加载器会抛出异常。这是内容提供者/游标加载器中的相关代码。
//内容提供商代码
private PantryDbHelper dbHelper;
private static final int PANTRY = 1;
private static final int INFO = 5;
public static final String AUTHORITY =“com.battlestarmathematica.stayfresh.pantryprovider”;
//path to db
public static final String URL = "content://" + AUTHORITY;
public static final Uri CONTENT_URI = Uri.parse(URL);
public static final Uri CONTENT_URI_PANTRY = Uri.withAppendedPath(CONTENT_URI,"pantry");
public static final Uri CONTENT_URI_INFO = Uri.withAppendedPath(CONTENT_URI,"info");
static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY,"info",INFO);
uriMatcher.addURI(AUTHORITY, "pantry", PANTRY);
}
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder){
SQLiteDatabase db = dbHelper.getReadableDatabase();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri)) {
case PANTRY:
builder.setTables(PantryContract.PANTRY_TABLE_NAME);
break;
case INFO:
builder.setTables("info");
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
}
//光标加载程序代码
public Loader<Cursor> onCreateLoader(int id, Bundle args){
return new CursorLoader(
//context
this,
//content URI
PantryContentProvider.CONTENT_URI_INFO,
//columns to return
new String[] {"_id","itemname"},
//selection
null,
//selection args
null,
//sort order
"itemname");
}
我知道游标加载器有效,因为我使用与pantry uri的另一个活动完全相同的代码,它完美地工作。当我尝试使用信息uri加载它时虽然我得到了这个例外。
java.lang.IllegalArgumentException:不支持的URI内容://com.battlestarmathematica.stayfresh.pantryprovider/info
非常感谢任何帮助。
答案 0 :(得分:2)
您在代码中缺少break
语句。
UriMatcher
匹配,并且switch语句跳转到case INFO:
,但由于没有break;
,因此也会执行default:
个案。
尝试替换此
case INFO:
builder.setTables("info");
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
由此:
case INFO:
builder.setTables("info");
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri);