首页 文章

urimatcher不使用预先填充的数据库

提问于
浏览
0

我正在尝试使用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

任何帮助将不胜感激 .

1 回答

  • 2

    您只是在代码中缺少 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);
    

相关问题