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);
Related
I am using the following to fetch a string from my table. The cursor is always returning empty even when I have data in database. Is the query wrong?
public void find(String myNumber){
String[] thecolumns = new String[]{
ID,
FLAG};
cursor = sqlDb.query(MY_TABLE,
thecolumns, NUMBER + "='"
+ myNumber+ "'", null, null, null, null);
if (cursorToFetchAssets != null ) {
cursorToFetchAssets.moveToFirst();{
try{
//code to fetch
}catch{
//return when there are no rows found.
}
}
EDIT: NUMBER is of type string "...+ NUMBER + " TEXT,.. " and myNumber is also a string
FIXED: Issue was on the server side of my code. Not over here..
try this:
cursor = sqlDb.query(
MY_TABLE,
thecolumns,
NUMBER + "=?",
new String[]{String.valueOf(number)},
null, null, null);
I am trying to build a method to determine if a user exists in an Android sqlite database before inserting, I have tried to build this method to return the number of rows, however If I try a search for like matches like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " LIKE '" + screenName + "%'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get the number of rows returned no problem however the minute I look for an exact match like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " = '" + screenName + "'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get 0 rows every time no matter if it matches or not, Im not sure if theres something wrong with my SQL or maybe im using the wrong arguments to make the statement, any help would go a long way thanks
Try this code it might work
Using Raw Query
Cursor mCount= db.rawQuery("select count(*) from "+ DATABASE_TABLE +" where "+SCREEN_NAME+"='" + SCREEN_NAME + "'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
Or using the same code but differently
db.query(DATABASE_TABLE , columns, SCREEN_NAME=?, new String[] { SCREEN_NAME}, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
I have database which contains "date" column and "item" column.
I want that user could update specific row in the database.
I trying to do it with update method in SQLiteDatabase class.
My problem is that i dont know how to make update method find exactly the row i want.
I saw some example that use it with parameters from one word.
like this:
ourDatabase.update(tableName, cvUpdate, rowId + "=" + item , null);
My problem is that i want to update the row that have specific item and date. so the name of the item alone is not enough.
I tried this code below but its didnt work, hope youll can help me.
public void updateEntry(String item, String date) throws SQLException{
String[] columns = new String[]{myItem, myDate};
Cursor c = ourDatabase.query(tableName, columns, null, null, null, null, null);
long position;
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(date, myDate);
cvUpdate.put(item, myExercise);
int itemAll = c.getColumnIndex(myItem);
int dateAll = c.getColumnIndex(myDate);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if (c.getString(itemAll).equals(myItem) && c.getString(dateAll).equals(myDate))
{
position = c.getPosition();
break;
}
}
ourDatabase.update(tableName, cvUpdate, rowId + "=" + position , null);
}
First, the columns String[] is supposed to contain column names, such as "_ID", or whatever are the column names you have used. Given that you compare the content of the column myItem with the object myItem, I assume there is a confusion somewhere here.
Secondly, rowId and position are different things in SQL, especially if you delete rows, as the row id usually is autoincrement, and especially since your query is not explicitely sorted. Replacing c.getPosition() by c.getLong(c.getColumnIndex(ID_COLUMN)) would make more sense.
Thirdly, sql is nice because you can query it. For example, rather than get all items and loop to find the matching date and item, you can :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
Cursor c = ourDatabase.query(tableName, columns, whereClause, whereArgs, null, null, null);
instead of your for loop.
Forthly, you can even make the query in the update :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
ourDatabase.update(tableName, cvUpdate, whereClause, whereArgs);
Extra tip: use full caps variable names for contants such as column names, it help with readability.
I am currently working on an Android project in Eclipse and i am having problems with my SQL query.
I am trying to order the query by more than two columns, currently i am doing it by KEY_DAY_ID but i want to also do it by KEY_START_TIME, but i can't get it to work
my query currently looks like this:
Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE,
KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
null, null, null, null, KEY_DAY_ID + " ASC");
Please let me know your thoughts. Thank you in advance!
The last parameter in db.query() method is the order by clause (without the "order by"). All you need to do is separate both columns by a ",". So it would look like:
Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE,
KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
null, null, null, null, KEY_DAY_ID + " ASC, " + KEY_START_TIME + " ASC");
This works for me
SQLiteCursor cursor = (SQLiteCursor) db.query(DbHelper.TIMES, colmn, null, null, null, null, DbHelper.TABLE_DAY + " ASC, " + DbHelper.TABLE_LECTURE_NO + " ASC",null);
Also you can do it in select line like this:
Cursor data = ddbb.rawQuery("SELECT * FROM vacations ORDER BY NAME ,MONTH , date ",null);
in previous code the first probability for the first column "NAME" then will start arrange by the Second probability "MONTH" then the third "date".....
which mean working in series
Or:
Cursor data = ddbb.rawQuery("select * from vacations where NAME = ? ORDER BY MONTH AND date ",new String[]{ns});
in previous code by using "AND" the two conditions are working together in parallel
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