【问题标题】:content provider unknown uri内容提供者未知 uri
【发布时间】:2013-04-27 16:13:04
【问题描述】:

我正在尝试访问 sqlite 内容以在 searchview 中获取建议。我无法在提供程序和 sqlite 数据库之间建立连接。我采取 illegalArgumentException, uknown uri。 我的代码的内容 uri 的确切语法是什么。

这是 logCat 输出:

04-27 22:52:33.122: E/AndroidRuntime(1062): FATAL EXCEPTION: main
04-27 22:52:33.122: E/AndroidRuntime(1062): android.database.sqlite.SQLiteException:     near "er": syntax error: , while     compiling:     SELECT _id AS _id, titleid, titlename FROM titles WHERE (titlename LIKE ?     er%) ORDER BY DESC
04-27 22:52:33.122: E/AndroidRuntime(1062):     at     android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at     android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at     android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:354)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:291)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at com.example.search_deneme.SuggestionProvider.query(SuggestionProvider.java:77)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.content.ContentProvider$Transport.query(ContentProvider.java:178)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.content.ContentResolver.query(ContentResolver.java:310)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at com.example.search_deneme.SearchableActivity.handleIntent(SearchableActivity.java:106)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at com.example.search_deneme.SearchableActivity.onNewIntent(SearchableActivity.java:88)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1123)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2041)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread.performNewIntents(ActivityThread.java:2054)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2063)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread.access$1400(ActivityThread.java:122)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1193)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.os.Looper.loop(Looper.java:137)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at android.app.ActivityThread.main(ActivityThread.java:4340)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at java.lang.reflect.Method.invokeNative(Native Method)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at java.lang.reflect.Method.invoke(Method.java:511)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-27 22:52:33.122: E/AndroidRuntime(1062):     at dalvik.system.NativeStart.main(Native Method)

这是我的活动代码。谢谢。

public class SearchableActivity extends Activity implements OnQueryTextListener {

DatabaseHandler db;
String query2;
Uri mNewUri;
ContentValues mNewValues = new ContentValues();



public static final String tablePath = "titles";
public static final String AUTHORITY = "com.example.search_deneme.SuggestionProvider";

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



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searchlist);
    db = new DatabaseHandler(this, "dbS");
    db.addContact(new Titles(1,1,"erdinc"));
    db.addContact(new Titles(2,1,"erf"));
    db.addContact(new Titles(3,1,"erg"));
    db.addContact(new Titles(4,1,"erh"));

    // Get the intent, verify the action and get the query
    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        query2 = intent.getStringExtra(SearchManager.QUERY);
        handleIntent(getIntent());
        System.out.println(query2);
        // doMySearch(query);
    }




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
            .getActionView();
    // Assumes current activity is the searchable activity
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(true); // Do not iconify the widget;
                                            // expand it by default
    searchView.setQueryRefinementEnabled(true);

    return true;

}

public boolean onSearchRequested() {
    Toast.makeText(SearchableActivity.this, "deneme", Toast.LENGTH_LONG)
            .show();
    return super.onSearchRequested();
}

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        query2 = intent.getStringExtra(SearchManager.QUERY);

        String[] mProjection = { 
                //CONTENT_URI.getQueryParameter("_ID"),
                //CONTENT_URI.getQueryParameter("_TITLEID"),
                //CONTENT_URI.getQueryParameter("_TITLENAME")
                DatabaseHandler._ID + "AS _id",DatabaseHandler._TITLEID,DatabaseHandler._TITLENAME
        };

        String mSelectionClause = DatabaseHandler._TITLENAME  +  " LIKE ? " + query2 + "%";



        Cursor a = getContentResolver().query(SuggestionProvider.CONTENT_URI, mProjection, mSelectionClause, null , "DESC");
        //Cursor c = db.getWordMatches(query, null);
        int b = a.getColumnCount();
        System.out.println(a.toString() + "      " + b);
        //doMySearch(query);
    }
}

@Override
public boolean onQueryTextSubmit(String query) {
    // TODO Auto-generated method stub
    System.out.println("123");
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
    return false;
}

}

这是我的建议提供者类。

public class SuggestionProvider extends ContentProvider {

DatabaseHandler mOpenHelper;
private SQLiteDatabase db;
private String dbName = "dbS";

public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final String tablePath = "titles";

private static final String BASE_PATH = "titles";
public static final String AUTHORITY = "com.example.search_deneme.SuggestionProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
        + "/" + BASE_PATH);
// public static final int MODE = DATABASE_MODE_QUERIES;

private static final String[] COLUMNS = {
        "_id", // must include this column
        SearchManager.SUGGEST_COLUMN_TEXT_1,
        SearchManager.SUGGEST_COLUMN_TEXT_2, };

@Override
public boolean onCreate() {
    // TODO Auto-generated method stub
    mOpenHelper = new DatabaseHandler(getContext(), dbName);

    return true;

}

private static final UriMatcher sURIMatcher = new UriMatcher(
        UriMatcher.NO_MATCH);
static {
    sURIMatcher.addURI(AUTHORITY, BASE_PATH, A);
    sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", B);
    sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/", C);
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(tablePath);
    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
    case B:
        queryBuilder.appendWhere(mOpenHelper._ID + "="
                + uri.getLastPathSegment());
        break;
    case A:// no filter
        break;
    case C:
        queryBuilder.appendWhere(mOpenHelper._TITLENAME+ "="
                + uri.getLastPathSegment());
//          break;
    default:
        throw new IllegalArgumentException("Unknown URI" + uri);

    }
    Cursor cursor = queryBuilder.query(mOpenHelper.getReadableDatabase(),
            projection, selection, selectionArgs, null, null, sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;

    // TODO Auto-generated method stub

}

@Override
public String getType(Uri uri) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub

    db = mOpenHelper.getWritableDatabase();
    return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
    // TODO Auto-generated method stub
    return 0;
}

}

这里是我如何创建我的数据库表。

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
public static final int DATABASE_VERSION = 1;

// Database Name
public static final String DATABASE_NAME = "suggestionManager";

// Contacts table name
public static final String TABLE_SUGGESTIONS = "titles";

public static final String _ID = "_id";
public static final String _TITLEID = "titleid";
public static final String _TITLENAME = "titlename";

public DatabaseHandler(Context context, String db) {
    super(context, db, null, DATABASE_VERSION);
}

// Creating TablesS
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_SUGGESTIONS + "("
            + _ID + " INTEGER PRIMARY KEY," + _TITLEID + " INTEGER,"
            + _TITLENAME + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUGGESTIONS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Titles title) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(_ID, title.getID()); // Contact Name
    values.put(_TITLENAME, title.getTitleName()); // Contact Name
    values.put(_TITLEID, title.getTitleID()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_SUGGESTIONS, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
Titles getTitle(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_SUGGESTIONS, new String[] { _ID,
            _TITLEID, _TITLENAME }, _ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Titles title = new Titles(cursor.getInt(0),
            cursor.getInt(1), cursor.getString(2));
    // return contact
    return title;
}

// Getting All Contacts
public List<Titles> getAllContacts() {
    List<Titles> contactList = new ArrayList<Titles>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_SUGGESTIONS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Titles contact = new Titles();
            contact.setID(cursor.getInt(0));
            contact.setTitleID(cursor.getInt(1));
            contact.setTitleName(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

// Updating single contact
public int updateContact(Titles title) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(_TITLEID, title.getTitleID());
    values.put(_TITLENAME, title.getTitleName());

    // updating row
    return db.update(TABLE_SUGGESTIONS, values, _ID + " = ?",
            new String[] { String.valueOf(title.getID()) });
}

// Deleting single contact
public void deleteContact(Titles contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_SUGGESTIONS, _ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_SUGGESTIONS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

}

【问题讨论】:

    标签: android uri android-contentprovider search-suggestion


    【解决方案1】:

    您是否将提供程序放在清单中?

    <provider
    
       android:authorities="com.yourpackagename.SuggestionsProvider"
    
       android:name=".SuggestionsProvider" >
    
    </provider>
    

    你可以试试这个:

    在您的数据库类中重命名: public static final String _ID = "id"; to public static final String _ID = "_id"; 我相信 _id 是 Android 中的一个自定义项。

    你能像这样写你的投影,看看它是否也有什么不同(其中 MYDATABASECLASS 是你的数据库 JAVA 类的名称:

    String[] mProjection = { MYDATABASECLASS._ID,MYDATABASECLASS._TITLEID,MYDATABASECLASS._TITLENAME };
    
    String mSelectionClause = MYDATABASAECLASS._TITLENAME  +  "LIKE ?";
    

    并在您的数据库类中重命名:

    public static final String _ID = "id"; to public static final String _ID = "_id"; 我相信 _id 是 Android 中的自定义。

    你能检查以下是否正确吗? queryBuilder.setTables(mOpenHelper.getDatabaseName());

    这里不是你的表名吗? 所以试试 queryBuilder.setTables(tablePath);

    【讨论】:

    • 我和你一样。然后我意识到我没有从数据库中获取 id、titleid 和 titlename 列。从数据库类中取出它们后,我在日志屏幕上看到了它们。但是现在 sql 命令无法正常工作。这是日志结果。 ““?”附近的 sql 异常,从 dbs WHERE (1=titles) A​​ND (titlenameLIKE) ORDER BY DESC 编译选择 _id、_titleid、_titlename 时出现语法错误...它采用数据库名称而不是表名称。而且我不确定它是否可以使用数据库类而不是内容提供者来工作。再次感谢。
    • 你是对的。我已经更改了 setTables 方法并且它有效。在此过程中,我对代码进行了许多更改。我已经更新了这个问题。如果你看最后一个,我将不胜感激。
    • 我仍在服用 IllegalArgumentException.Unknown URI content://com.example.search_deneme.SuggestionProvider.titles
    • 这里是...
    • 你愿意把它整理成一个清晰的答案吗?我不清楚是什么解决了上述问题。
    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2016-11-29
    相关资源
    最近更新 更多