Android SQLite distinct select? - android

I have created a Sqlite database in my android app, it looks like this:
create table msgs ( id integer primary key autoincrement, msg text not null, session text not null, sender text not null);
I can get all the entry's like this, but I don't fly understand what is happening.
String[] allColumns = {"msg","session","sender"};
Cursor cursor = database.query(msgs, allColumns, id = insertId, null, null, null, null);
What i could like to do, is to only get the latest entry with a distinct session how can i do this in android?
Edit: If this was mysql i whould do "SELECT MAX(id) AS id2,msg, session FROM msgs GROUP BY session"
But cant seam to get it to work in SQLite :/

To execute a complete SQL query, you could use rawQuery:
cursor = database.rawQuery("SELECT MAX(id) AS id2,msg, session FROM msgs GROUP BY session", null);
With query, you would have to set the parameters like this:
cursor = database.query("msgs",
new String[] { "MAX(id) AS id2", "msg", "session" },
null, null,
"session",
null, null);
Please note that using an unaggregated colum (msg) in an aggregated query does not work before SQLite version 3.7.11 (Android API version 16, Jelly Bean).

Always check documentation and be careful with types!
Your using following method:
query(
msgs, //String table: OK
allColumns, //String[] columns: OK
id = insertId, //String selection: NOT OK
// ^--- this is a boolean which will render SQL something like
// "SELECT ... WHERE TRUE ..." or "SELECT ... WHERE FALSE ..."
// causing all rows or none to be displayed
null, //String[] selectionArgs: OK
null, //String groupBy: OK
null, //String having: OK
null); //String orderBy: OK
Correction:
query(
msgs, //table
allColumns, //columns
"id = ?", //selection
new String[] {String.valueOf(insertId)}, //selectionArgs
null, //groupBy
null, //having
null); //orderBy

Related

SimpleAdapter needs an _id field

I got this :
Cursor c = db.query("Org", null, null, null, null, null, null);
which means I choose a table "Org", but together with this I need to make this :
Cursor c = db.rawQuery(" SELECT "+ id + " AS _id")
because SimpleAdapter need to have an _id field necessarily for some reason or it will crash with an error. How do I combine this 2 into one query?
The second parameter of the query function is the list of columns.
If you want to rename a column, you cannot just blindy return all columns but have to list the desired columns:
String[] columns = new String[] { id+" AS _id", "Name", "Color", "whatever..." };
Cursor c = db.query("Org", columns, null, null, null, null, null);
For your statement : Cursor c = db.query("Org", null, null, null, null, null, null); the second parameter is wrong, you shoukd mention the column names in it.
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Whereas for,
Cursor c = db.rawQuery(" SELECT "+ id + " AS _id from Org");
means that you Select id and create an alias of it using AS into _id, and you are selecting this id from Org table.
so now you will be able to access the result from this query from the column name _id, and in order to access the result use:
c.moveToFirst();
while (c.moveToNext())
{
System.out.println(c.getString(c.getColumnIndex("_id"));
}

query method in SQLiteDatabase

I want to know how to use query method that have where clause with like property.
basically what i want is to select all the columns WHERE C_NAME column is LIKE keyWord.
I've tried this, but it doesn't work:
cursor = db.query(TABLE, null, C_NAME, new String[] {"like '"+keyWord+"'"}, null, null, null);
Look at the docs. They say:
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
so try this:
cursor = db.query(TABLE, C_NAME, new String[] {C_NAME + " like '" + keyWord + "'"}, null, null, null);
Also see this answer as well to see some examples on how to use the selectionArgs (4th argument above). That is where keyWord would have to go.
this query work perfect for me
Cursor cursor = db.query(true, TABLE_NAME, new String[]{ COLUMNS }, ROW + " LIKE ?", new > String[] { "%" + name + "%" }, null, null, null, null);

Cursor returns empty when querying for particular column values, even though rows exist

I have implemented a custom SQLite database helper. I have a table containing sms messages. I query this table for entries from a particular phone number like so:
public Cursor getSmsForContact(String phoneNumber) throws SQLException {
phoneNumber = PhoneNumberUtils.stripSeparators(phoneNumber);
Cursor cursor =
db.query(DATABASE_TABLE, new String[] {
KEY_DATE,
KEY_BODY,
KEY_CONTACT,
KEY_TYPE,
KEY_ROWID,
KEY_MESSAGE_STATE
}, KEY_CONTACT + "=" + phoneNumber, null, null, null, null);
return cursor;
}
This method works fine for numbers that do not have a "+" in the front (indicating a country code). However, it always returns an empty cursor when phoneNumber has a "+" in the front. I've verified that the PhoneNumberUtils.stripSeparators() method does not remove the "+" sign. I've also verified that rows exist in the table which match the phone number which is being queried.
Thanks!
Try
}, KEY_CONTACT + "= ?" , new String[] {phoneNumber}, null, null, null);
Phone number is being interpreted as a number; you want it to be interpreted as a string

Android sql query using WHERE clause for greater than

I have a question regarding how to use a WHERE clause when querying a sql database in Android. I need to return specific records from my database where the value of DURATION is greater than 3.
It works fine when I have the WHERE clause for checking equals.
Example
Cursor resultOfFilterQuery = db.query(myTable, new String[] {call_cost, call_type,
date,DURATION , phone_number }, phone_number= , new String[]{"9456788909"}, null, null, null);
Please let me know how to check for greater than
How should the query statement look?
Cursor resultOfFilterQuery = db.query(myTable, new String[] {call_cost, call_type,
date,DURATION , phone_number }, DURATION> , new String[]{3}, null, null, null);
Don't know how your first code snippet work with syntax errors, but this can helps:
Cursor resultOfFilterQuery = db.query(myTable,
new String[] {call_cost, call_type, date, DURATION, phone_number },
DURATION + "> ?", new String[]{"3"}, null, null, null);

Query only the first data from a table

I'm trying to query only the first data from the table.
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null",
null, null, null, null);
Could somebody tell me how to implement a query where only the first data is retrieved from a table?
Solution
I think I solved the answer:
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null",
null, null, null, null , "1");
I used limit 1 first, but the application crashed. Only if I pass the number as a String will it work. The query has 8 parameters while we're using the limit parameter.
limit 1
From Documentation:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
so, put your last argument to be "limit 1".
Cursor img_cursor = db.query(
IMAGE_URL_TABLE_NAME,
new String[]{"small_img_url" , "large_img_url"},
null,
null, null, null, "limit 1");

Categories

Resources