2013-06-02 190 views
0

我在ContentProvider中遇到了匹配URI的問題。它將匹配具有一個或兩個「標籤」的路徑(不確定正確的術語是什麼),例如它可以識別box/#。但只要我添加第二個標籤,例如box/#/item,我就會拋出一個InvalidArgumentException,並且我的應用程序崩潰。我已經在這裏看過幾個主題,這個問題有時可以通過改變添加到UriMatcher的URI的順序來解決;我試過這個,但無濟於事。任何人都知道問題是什麼?我已經在下面摘錄了我的代碼的相關部分。UriMatcher無法識別模式

從我ContentProvider

private static final String AUTHORITY = "com.example.boxdatabase.DatabaseProvider"; 
// Type of query 
public static final int BOXES = 100; 
    ... 

public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); 
    ... 

// URI Matcher for queries 
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); 
static { 
    sURIMatcher.addURI(AUTHORITY, "box/#/item", BOX_ITEM); 
    sURIMatcher.addURI(AUTHORITY, "box/#/item/#", BOX_ITEM_ID); 
    sURIMatcher.addURI(AUTHORITY, "box", BOXES); 
    sURIMatcher.addURI(AUTHORITY, "box/#", BOXES_ID); 
    sURIMatcher.addURI(AUTHORITY, "item", ITEMS); 
    sURIMatcher.addURI(AUTHORITY, "item/#", ITEMS_ID); 
} 

的,我想訪問我的ContentProvider和失敗的例子:

return new CursorLoader(this, Uri.withAppendedPath(
       DatabaseProvider.CONTENT_URI, "box/" + boxId + "/item"), 
       DatabaseContract.BoxItemEntry.ALL_COLUMNS, null, null, null); 
+0

你能顯示堆棧跟蹤和哪行代碼會拋出異常 –

+0

我自己拋出異常。在'query()'方法中有一個switch-case,結果爲'matchUri';默認(URI匹配失敗)是一個'InvalidArgumentException'。 –

回答

3

試試這個:

sURIMatcher.addURI(AUTHORITY, "box", BOXES); 
sURIMatcher.addURI(AUTHORITY, "box/#", BOXES_ID); 
sURIMatcher.addURI(AUTHORITY, "box/#/item", BOX_ITEM); 
sURIMatcher.addURI(AUTHORITY, "box/#/item/#", BOX_ITEM_ID); 
sURIMatcher.addURI(AUTHORITY, "item", ITEMS); 
sURIMatcher.addURI(AUTHORITY, "item/#", ITEMS_ID); 

的順序很重要,在這裏閱讀我的解釋: https://stackoverflow.com/a/15015687/534471

+0

我想出了我的問題,它與'UriMatcher'無關。但是,這是非常豐富的,所以我會繼續接受它作爲我的答案。希望別人會發現這有用! –

+0

'addURI(AUTHORITY,「item」,ITEMS);'可以放在addURI(AUTHORITY,「box」,BOXES)後面嗎? –