Using selectionArgs doesn't work in a query - android

I'm trying to use the following:
String dbquery = "Select * From stops where stopname LIKE '%?%' LIMIT 100";
String[] uinputarray = {uinput};
Cursor c = sDB.rawQuery(dbquery, uinputarray);
This consistently crashes.
Curiously, if I use the old test code of:
Cursor c = sDB.rawQuery("Select * From stops where stopname LIKE '%" + uinput + "%' LIMIT 100", null);
It works flawlessly.
I've been reading up on selectionArgs and I honestly can't see anything wrong with what I've done.
What am I doing wrong?
Thanks guys

You have to append the % to the selectionArgs itself:
selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
Note: Accordingly % and _ in the searchString string still work as wildcards!

Related

select multiple song id from MediaStore.Audio.Media

I have created a getContentResolver().query using the follwing
uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String projection[] = { android.provider.MediaStore.Audio.Media.DATA,
android.provider.MediaStore.Audio.Media.TITLE,
android.provider.MediaStore.Audio.Media.ARTIST,
android.provider.MediaStore.Audio.Media.ALBUM,
android.provider.MediaStore.Audio.Media.COMPOSER,
android.provider.MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media._ID,
android.provider.MediaStore.Audio.Media.ALBUM_ID };
String selection1 = MediaStore.Audio.Media._ID + "=?" ;
String[] selectionArgs = new String[] {"" + 19};
cursor = this.getContentResolver().query(uri, projection,
selection1, selectionArgs, null);
songs = new ArrayList<String>();
while (cursor.moveToNext()) {
songs.add(cursor.getString(1));
This works perfectly fine for selecting single song , however when I try to select multiple songs using
String selection1 = MediaStore.Audio.Media._ID + "IN(?,?)";
String[] selectionArgs = new String[] {"" + 12,"" + 19};
This query fails .
Is there a proper way to select multiple songs , what is wrong with the above query.
please explain the changes needed to be made.
I don't see anything wrong with your query using the IN operator. I suspect the query with IN has quirks and limitations. I did not use it however. Try just using the OR operator instead.
Example:
String selection1 = MediaStore.Audio.Media._ID + "=12" + " OR " + MediaStore.Audio.Media._ID + "=19";
And of course not use selectionArgs as the parameter.
Another good try is using raw query instead, documentation # SQL rawQuery. With a raw query, you can use the IN operator, and I think it's a good idea for simplifying queries. I should use it next time.
Thanks for this question!

sqlite - how does contains work

I am not overly experienced in SQL and now get a syntax error trying to invoke SQL from android:
select _id from inAd where Name contains ?
says there is a Syntax error near contains.
However, it works fine if I use "=" instead of "contains".
Does anyone know what the issue is?w
Now following your advice, I tried:
cursor = helper.getReadableDatabase().rawQuery(
"select _id from inAd where Name like ?",
new String[] { str2 });
but to no avail.
Now also tried:
cursor = helper.getReadableDatabase().rawQuery(
"select _id from inAd where Name like ?",
new String[] { "%<str2>%" });
Same Problem.
cursor = helper.getReadableDatabase().rawQuery(
"select _id from '"+inAd+" where Name like '%"+str2+"%'",
null);
This time there is a syntax error near %.
When using LIKE, you must use wildcards at the beginning and end of the pattern:
cursor = helper.getReadableDatabase().rawQuery(
"select _id from inAd where Name like '%' || ? || '%'",
new String[] { str2 });
or:
cursor = helper.getReadableDatabase().rawQuery(
"select _id from inAd where Name like ?",
new String[] { "%" + str2 + "%" });
Try
select _id from inAd where Name like '%<Your String>%'
'contains' is not a part of the SQL syntax. As #Kristy specified, you can use the LIKE operator or '='.
See if this works:
selectionArgs = new String[] { "%" + str2 + "%" };
Cursor c = db.rawQuery("select _id from inAd where Name LIKE ?, selectionArgs);

SQL using with clause not working

My question is why this query does not work?
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor = '%" + spin.getSelectedItem().toString() + "%'", null);
Cursor c: it is a cursor for handling my query
tbl_staff: my table that consist of PName, PMajor, PCert
spin: is spinner that has values which I need for my database query.
When I use:
if (c.moveToNext())
else (log.d("error query","couldn't do the query!");)
It goes to else statement and moveToNext() doesn't work.
Instead of using =, which checks for equality, use keyword LIKE, which matches a pattern.
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor LIKE '%" + spin.getSelectedItem().toString() + "%'", null);

cant use like clause in android app

I am working on a database with sqllite in an android app
I want to retrieve sm data using a like clause
ex:
Cursor c = myDB.query(MY_DATABASE_TABLE, null, " SongName LIKE '%"+"=?"+"%'" ,
new String[]{match_str}, null, null,"SongHit DESC");
It should give all SongName starting with match_str but its not working.Why?
This:
" SongName LIKE '%"+"=?"+"%'"
Will end up looking like this when the SQL interpreter sees it:
" SongName LIKE '%=?%'"
And that will match any SongName that contains a literal "=?" and I don't think that's anything like what you want.
A % matches any sequence of characters in an SQL LIKE, it is essentially the same as .* in a regular expression; so, if you want to match at the beginning then you don't want a leading %. Also, your ? placeholder needs to be outside the single quotes or it will be interpreted as a literal question mark rather than a placeholder.
You want something more like this:
String[] a = new String[1];
a[0] = match_str + '%';
Cursor c = myDB.rawQuery("SELECT * FROM songs WHERE SongName LIKE ?", a);
If you wanted to be really strict you'd also have to escape % and _ symbols inside match_str as well but that's left as an exercise for the reader.
Try this:
String[] args = new String[1];
args[0] = "%"+song+"%";
Cursor friendLike = db.rawQuery("SELECT * FROM songs WHERE SongName like ?", args);
No need for the equal sign and you should be able to include the ? right in the string without the need for the + operator. The where clause should just be:
"SongName LIKE '%?%'"
and if mu is too short is correct and you only want starting with...
"SongName LIKE '?%'"
hi Are you getting any exception while executing the above query. Try by removing the "=" symbol infront of the question mark in the like condition. Else try using
db.rawQuery(sql, selectionArgs)
This works perfectly for me...
"Songname LIKE ? "...
cursor = database.rawQuery(query, new String[]{"%" + searchTerm + "%"});
If you wish to use query() instead of rawQuery(), you can do it like so:
// searchString is the string to search for
final String whereClause = "MyColumnName" + " like ?";
String[] whereArgs = new String[]{"%" + searchString + "%"};
Cursor cursor = sqLiteDatabase.query("MyTableName",
null, // columns
whereClause, // selection
whereArgs, // selectionArgs
null, // groupBy
null, // having
null, // orderBy
null); // limit
a simple way is to use the concatenate operator ||
"SongName LIKE '%'||?||'%'"
so there is no need to edit the match_str.
Cursor c = myDB.query(MY_DATABASE_TABLE, null, " SongName LIKE '%'||?||'%'" ,
new String[]{match_str}, null, null,"SongHit DESC");
from https://stackoverflow.com/a/46420813/908821

SQLite Query in Android to count rows

I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

Categories

Resources