cant use like clause in android app - android

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

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!

Getting completion suggestions from a database

I am trying to retrieve first 5 words from database and set those as text of button for that here is my code
String [] deal;
String text,s1,s2,s3,s4,s5;
text=edt.getText().toString();
deal=db.getAllItemFilter(text);
s1=deal[0];
s2=deal[0];
s3=deal[0];
s4=deal[0];
s5=deal[0];
sug1.setText(s1);
sug2.setText(s2);
sug3.setText(s3);
sug4.setText(s4);
sug5.setText(s5);
for database query i am using this code but it is not working
public String[] getAllItemFilter(String text)
{
String [] columns= new String[]{word};
Cursor cursor = this.ourdatabase.query(database_table, columns, " word like 'text%' ", null, null, null, null);
String [] deal = new String[cursor.getCount()];
int iword = cursor.getColumnIndex(word);
int i=0;
for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext())
{
deal[i]=cursor.getString(iword);
i++;
if(i==5)
break;
}
return deal;
}
can anybody help me to get first 5 suggestions from database .Thanks in advance
you should first set a "LIMIT=5" at your SQL query end rather than a loop limit, it will save resources. Then you can replace word% by %word% to also match word beginning.
Your query is incorrect. As you have it set up, it is looking for "text*" every time (you forgot to format the query so the variable is used as a variable).
Change your cursor to what I show below if you want words beginnning with the supplied text:
Cursor cursor = this.ourdatabase.query(database_table, columns, " word like '" + text + "%' ", null, null, null, null);
If you just want words containing the supplied text, change it to:
Cursor cursor = this.ourdatabase.query(database_table, columns, " word like '%" + text + "%' ", null, null, null, null);

Using selectionArgs doesn't work in a query

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!

how to use db.query() when i have many conditions in where clause?? #android

i have a table with columns ID,SUBJECT,BRANCH
i have select the rows which satisfies the follwing conditions
id=rollno
branch=cse
subject=any subject
db.query(DATABASE_TABLE, new String[] {
ID,SUBJECT,BRANCH},
where clause,
null,
null,
null,
null);
how to write where clause here to satisfy my conditions?
You can use db.rawQuery methos also
Cursor cursor= db.rawQuery("select * from <table_name> where id='1' and
branch='" + branchName + "' and subject='" + subjectName+ "'");
add Where clauses with " AND ".. Pretty simple.. Each condition is seperated by the same..
here is an example
String addrWhere = ContactsContract.Data.CONTACT_ID+" = ? AND "+ContactsContract.Data.MIMETYPE+" = ?"; //this is where clause and below is corresponding selection args..
String[] addrWhereParams = new String[]{data.getContac_ID(),
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};

How to filter the results of content resolver in android?

I would like to get user contacts and then append some kind of regular expression and append them to a list view. I am currently able to get all the contacts via
getContentResolver().query(People.CONTENT_URI, null, null, null, null);
and then pass them to a custom class that extends SimpleCursorAdapter.
So I would like to know how to get only the contacts that match a regular expression and not all of users contacts.
Instead of
getContentResolver().query(People.CONTENT_URI, null, null, null, null);
you should use something like
final ContentResolver resolver = getContentResolver();
final String[] projection = { People._ID, People.NAME, People.NUMBER };
final String sa1 = "%A%"; // contains an "A"
cursor = resolver.query(People.CONTENT_URI, projection, People.NAME + " LIKE ?",
new String[] { sa1 }, null);
this uses a parameterized request (using ?) and provides the actual values as a different argument, this avoids concatenation and prevents SQL injection mainly if you are requesting the filter from the user. For example if you are using
cursor = resolver.query(People.CONTENT_URI, projection,
People.NAME + " = '" + name + "'",
new String[] { sa1 }, null);
imagine if
name = "Donald Duck' OR name = 'Mickey Mouse") // notice the " and '
and you are concatenating the strings.
You can query the content provider with sql type input, the Query method is just a wrapper for an sql command.
Here is an example where I query for a Contacts name given a particular number
String [] requestedColumns = {
Contacts.Phones.NAME,
Contacts.Phones.TYPE
};
Cursor contacts = context.getContentResolver().query(
Contacts.Phones.CONTENT_URI,
requestedColumns,
Contacts.Phones.NUMBER + "='" + phoneNumber + "'",
null, null);
Note that instead of null I have parameters that build up the sql statement.
The requestColumns are the data I want to get back and Contacts.Phones.NUMBER + "='" + phoneNumber + "'" is the Where clause, so I retrieve the Name and Type where the Phone Number matches
You should be able to put a legal SQLite WHERE clause as the third argument to the query() method, including a LIKE, but there's no native REGEXP function in SQLite and Android doesn't seem to let you define your own. So depending how complex your needs are, a set of other SQLite conditions and LIKE expressions might do the trick.
See the documentation on the query method under ContentResolver and SQLite expressions.
Actually REGEXP with Calllog Content Provider works (means that regexp() function is defined for that content provider's Database https://sqlite.org/lang_expr.html#regexp)! But it is very slow: ~15 sec across ~1750 records.
String regexp = "([\\s\\S]{0,}" +
TextUtils.join("||[\\s\\S]{0,}", numbers) +
")";
cursor = context.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
null,
CallLog.Calls.NUMBER + " REGEXP ?",
new String[]{regexp},
CallLog.Calls.DATE + " DESC"
);

Categories

Resources