SQLite query less than or greater than check - android

I want to use this:
return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_LEVEL }, KEY_LEVEL + ">= 3 AND " + KEY_LEVEL + " < 5", null, null, null, null);
But instead of 5 I want it to check the next column where it finds greater than or equal to three.
So when I give an input of say 5, I want it to check for greater than or equal to 5 in column 3 but less than the value in the next column, column 4.
Original code taken from Sqlite query check - less than and greater than.

Just do this :
String[] selectionArgs = { "5", "5" };
String[] columns = { KEY_ROWID, KEY_COLUMN3, KEY_COLUMN4 };
String selection = "KEY_COLUMN3 >= ? AND KEY_COLUMN4 < ?";
return mDb.query(DATABASE_TABLE, columns, selection, selectionArgs, null, null, null);

For me just passing numerics in String format like #buzeeg offered didn't work.
PROBLEM: My task was to perform UPDATE and in my case it should not have succeed, but as you may guess, when we use 1 as query arg, '1'>2 means true:
UPDATE table SET field = 1 WHERE ? > 2
SOLUTION: CAST helped me to solve it:
SELECT * FROM smth WHERE CAST(? as integer) > 2

Related

Get the Max _id from ContentResolver from Contacts.CONTENT_URI

I want to get the last added contact in the contacts and for getting that i want to pull the max _id of the contact. So here is my query that i want to realise:
AppMain.applicationContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
new String[]{
"MAX(" + ContactsContract.Contacts._ID + ") as max_id",
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER
},
null, null, null);
But unfortunately i am getting this error:
Invalid column MAX(contact_id) as max_id
I tried removing the 'as max_id' but no luck.
Does any one know how to get the last added contact or get the max _id of the contact.
This is not officially supported by Android's ContentProvider framework, especially if the Provider set the strictProjectionMap flag.
But this should work instead, it asks for all contacts sorted by contact-id, and limits the results to 1:
Cursor c = cr.query(Contacts.CONTENT_URI, new String[] { Contacts._ID }, null, null, Contacts._ID + "DESC LIMIT 1");
if (c != null && c.moveToNext()) {
Log.d(TAG, "id is: " + c.getLong(0));
}

Update row in SQlite database by row position in android

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.

How to use substring in Android Queries

I need to compare the last 10 digit of the phone numbers in such code:
String selectionClause = ContactsContract.CommonDataKinds.Phone.NUMBER+ " = ?";
String[] selectionClauseArgs = { callerId };
Cursor people = resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projections,
selectionClause, selectionClauseArgs, null);
So the selectionClause should be like
String selectionClauseArgs = "substr("+CommonDataKinds.Phone.NUMBER+",-1,10) = ?";
But I am not sure if I can use such SQLLite queries when querying ContentProviders.
Try this solution, I have tested it myself and should be work.
//substr(string,-10, 10) take last 10 characters.
String selectionClause = "substr(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ",-10, 10) =?";
String[] selectionClauseArgs = { callerId };
Cursor people = resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projections,
selectionClause, selectionClauseArgs, null);
and also you can use substr(COLUMN_NAME,-10) to take the last 10 characters.
note : For function substr(x,y,z), y is the beginning character, if y is negative, then it count from the right of the x. and z is the number of characters taken begin from the y position.

Android- SQLite query to Order Results by Day using the query builder

At the moment i'm currently using the query builder to pull all my records from my database and they are currently organised by day however I its sorts in althabetical order,
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,"Day");
}
I know after some googling, that I need to replace the final section with a custom search order.
something along the lines of :
select _id, busnum,
case cast (strftime('%w', servdate) as integer)
when 0 then 'Sunday'
when 1 then 'Monday'
when 2 then 'Tuesday'
when 3 then 'Wednesday'
when 4 then 'Thursday'
when 5 then 'Friday'
else 'Saturday' end as servdayofweek
from tb1
where ...
From:
http://stackoverflow.com/questions/4319302/sqlite-return-as-day-of-week
so far i have been unable to figure out how tocombine the two and anyhelp in the right direction would be much aprechiated.
Edit Soloution
thank you for the help I went with declaring the string and linking to it in the query for anyone that needs something simple this is my final code for it
public Cursor fetchAll() {
String OrderBy ="case Day"+
" when 'Monday' then 0 "+
" when 'Tuesday' then 1"+
" when 'Wednesday' then 2"+
" when 'Thursday' then 3"+
" when 'Friday' then 5"+
" end";
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,OrderBy );
}
If your Day values are the day names then you want something like this:
order by case Day
when 'Sunday' then 0
when 'Monday' then 1
when 'Tuesday' then 2
...
when 'Saturday' then 6
end
in the SQL; keep in mind that you can hand an SQL ORDER BY pretty much any expression. The orderBy argument to query can be any SQL ORDER BY clause (without the order by) so you want this big ugly string :
"case Day when 'Sunday' then 0 when 'Monday' then 1 ... when 'Saturday' then 6 end"
as the last argument to query. You'll have to properly fill in the ... of course.
If you cannot figure out how to pass a complex query through SQLiteDatabase.query(... lots of variables...) just pass your select statement as a string with SQLiteDatabase.rawQuery().
For example:
String query = "select _id, busnum, " +
" case cast cast (strftime('%w', servdate) as integer) " +
...
String[] selectionArgs = new String() { yada, yada, yada }
mDb.rawQuery(query, selectionArgs);

android sql - how do you order your sql query by multiple columns

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

Categories

Resources