urimatcher 不适用于预填充的数据库

urimatcher not working with prepopulated database

我正在尝试使用 SQLiteAssetHelper 将预填充的 SQLITE 表添加到我的内容提供商,但 uri 匹配器不匹配。我可以通过标准 SQL access/modify 表,但使用游标加载程序会引发异常。这里是内容provider/cursor loader.

中的相关代码

//内容提供者代码

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");
}

我知道游标加载器可以工作,因为我对另一个 activity 和 pantry uri 使用了完全相同的代码,并且它工作得很好。当我尝试使用信息 uri 加载它时,我得到了这个异常。

java.lang.IllegalArgumentException: 不支持的 URI 内容://com.battlestarmathematica.stayfresh.pantryprovider/info

如有任何帮助,我们将不胜感激。

您只是在代码中缺少 break 语句。

UriMatcher 匹配并且 switch 语句跳转到 case INFO:,但是由于没有 break; 所以 default: case 也被执行。

尝试替换这个

        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);