简体   繁体   中英

Search through SQLite database on Android Search

Method causing error inside my ContentProvider

public static Cursor getSuggestions(String query) {
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    db.beginTransaction();
    try {
        String selection = Formula.FORMULA_NAME + " LIKE %?%";
        String[] selectionArgs = { query + "*" };
        Cursor cursor = dbHelper.getReadableDatabase().query(
                FORMULA_TABLE_NAME,
                new String[] { BaseColumns._ID,
                        SearchManager.SUGGEST_COLUMN_TEXT_1, 
                        BaseColumns._ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID 
                        }, 
                        selection,
                selectionArgs, null, null, null);
        db.setTransactionSuccessful();
        return cursor;
    } catch (SQLiteException e) {
    } finally {
        db.endTransaction();
    }
    throw new SQLException("Failed to begin transaction");
}

Database creation:

db.execSQL("CREATE TABLE " + FORMULA_TABLE_NAME + " (" +
                BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT," +
                Formula.CATEGORY + " TEXT" +
                ");");

Constants used:

    public static final String FORMULA_NAME = SearchManager.SUGGEST_COLUMN_TEXT_1;
    public static final String CATEGORY = "category";

The problem is that in my method, the transaction is unsuccessful because it throws the error: throw new SQLException("Failed to begin transaction"); What I'm trying to do is to search through the database as part of a search. When the user activates the search box, then I have it set up so that this method should be returning a cursor with the suspected items based on their name. Through debugging, I deduced that the problem was with the method of search inside my Content Provider. Any solutions or thoughts?

I'm guessing the line throw new SQLException("Failed to begin transaction"); is meant to be inside your catch block.

What if we simplify everything to:

public static Cursor getSuggestions(String query) {
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String selection = Formula.FORMULA_NAME + " LIKE %?%";
    String[] selectionArgs = { query + "*" };
    Cursor cursor = db.query(
            FORMULA_TABLE_NAME,
            new String[] { BaseColumns._ID,
                    SearchManager.SUGGEST_COLUMN_TEXT_1, 
                    BaseColumns._ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID 
                    }, 
            selection,
            selectionArgs, null, null, null);
    return cursor;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM