Jamie
Jamie

Reputation: 115

Search SQLite database in Android

I'm having some trouble searching a SQLite database in my Android app. I use the Search interface to pass the search variable (searchActivity.query) to this:

   //searchActivity.query obtained from: 
   //String query = searchActivity.getStringExtra(SearchManager.QUERY);

   String searchString = "'" + searchActivity.query + "%'";

   //sqlitedb is called via: private SQLiteDatabase sqlitedb;

   Cursor cursor = sqlitedb.query(DATABASE_TABLE, new String[] 
    {"id", "FirstName","LastName"}, 
    "FirstName LIKE " + searchString, null, null, null, null);

    int index_CONTENT = cursor.getColumnIndex(FirstName);

    for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
        result = result + cursor.getString(index_CONTENT) + "\n";
    }

The problem is that using the "LIKE" statement outputs everything in the database - defeating the purpose of using the Search interface. I'm not too sure where I'm going wrong.

I tried replacing LIKE with "=" except that displayed nothing, even when I was 100% sure the record existed.

Any help would be greatly appreciated!

Thanks in advance,

Joe

UPDATE: Sorry about the misleading title. I wasn't passing the search query properly.

Upvotes: 1

Views: 9443

Answers (4)

bab
bab

Reputation: 21

Cursor c = sqLiteDatabase.query(SQLiteHelper.MYDATABASE_TABLE, null, null, null, null, null, SQLiteHelper.KEY_CONTENT1 +" ASC");

Upvotes: 2

Mustafa Güven
Mustafa Güven

Reputation: 15744

String sql = " SELECT * FROM Table WHERE xColumn LIKE '%"+textView1.getText().toString()+"%'";
cursor = db.rawQuery(sql, null); 

you can use as above

Upvotes: 2

Anirudh
Anirudh

Reputation: 2524

You should bind the parameter.

query = "UPPER(" + COLUMNNAME + ") like ?";
String searchString = searchActivity.query + "%"; 

and then,

sqlitedb.query(DATABASE_TABLE, new String[] 
{"id", "FirstName","LastName"}, 
query , new String[] {searchString},....);

Upvotes: 0

user370305
user370305

Reputation: 109237

Try this,

Cursor cursor = sqlitedb.query(DATABASE_TABLE, new String[] 
    {"id", "FirstName","LastName"}, 
    "FirstName LIKE '"+searchActivity.query+"%'", null, null, null, null);

and let me know what happen..

Upvotes: 0

Related Questions