How to perform an SQLite query within an Android application? - android

I am trying to use this query upon my Android database, but it does not return any data. Am I missing something?
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String select = "Select _id, title, title_raw from search Where(title_raw like " + "'%Smith%'" +
")";
Cursor cursor = db.query(TABLE_NAME, FROM,
select, null, null, null, null);
startManagingCursor(cursor);
return cursor;

This will return you the required cursor
Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"},
"title_raw like " + "'%Smith%'", null, null, null, null);

Alternatively, db.rawQuery(sql, selectionArgs) exists.
Cursor c = db.rawQuery(select, null);

This will also work if the pattern you want to match is a variable.
dbh = new DbHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Cursor c = db.query(
"TableName",
new String[]{"ColumnName"},
"ColumnName LIKE ?",
new String[]{_data+"%"},
null,
null,
null
);
while(c.moveToNext()){
// your calculation goes here
}

I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Parameters
table: the name of the table you want to query
columns: the column names that you want returned. Don't return data that you don't need.
selection: the row data that you want returned from the columns (This is the WHERE clause.)
selectionArgs: This is substituted for the ? in the selection String above.
groupBy and having: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.
orderBy: sort the data
limit: limit the number of results to return

Try this, this works for my code
name is a String:
cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
ROLEID, NATIONALID, URL, IMAGEURL },
LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);

Related

Where clause is not working for long in android SQLite

I am trying for select statement in android SQLite
i am able to select all records in a cursor if i do below
String tableName = "Test";
String[] columns = {mobile};//mobile has a datatype number in db
Cusrsor c = m_sqlLiteDatabase.query(tableName, columns, null,null, null, null, null);
c.getCount(); // 11
but does not return any value if i add a conditon as below
long mobile = 123456;
m_sqlLiteDatabase.query(tableName, columns, "mobile=" + mobile ,null, null, null, null);
c.getCount(); // 0
is anything i am doing wrong?
how to use long
try to change your query code line with this
m_sqlLiteDatabase.query(tableName, columns, " mobile = ? ", new String[]{String.valueOf(mobile)} ,null, null, null);
Reference
query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy)

How to do a rtrim() to a Android Cursor query?

I have the following query:
Cursor c = sd.query(itemsTable.Table_Name, columns, itemsTable.ItemNumber + "= ?", selectionArgs, null, null, null);
I need to be able to do this:
'SQL Query I am running on the database using for testing
select * from items where rtrim(itemnumber) = '292664'
Where itemnumber is my selectionArgs.
The SQL query returns the correct results but the cursor query returns null.
I would rather not change the way I am running queries and would like to know if there is a way to convert my existing query to work the same as the SQL query.
Try the following:
String selection = "RTRIM(" + itemsTable.ItemNumber + ") = ?";
String[] selectionArgs = new String[] {"292664"}; // or whatever
Cursor c = sd.query(itemsTable.Table_Name, columns, selection, selectionArgs, null, null, null);

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"));
}

android content provider sum query

Is it possible to use getContentResolver().query() when I want sum(column)?
OR
Do I have to make raw query to db handle?
When providing the array of columns to ContentResolver.query, wrap the column name with the sum() function
String[] columns = new String[] { "sum(" + columnName + ")" };
Cursor cursor = getContentResolver().query(
content_uri,
columns,
selection,
selectionArgs,
sort
);
cursor.moveToFirst();
int columnSum = cursor.getInt(0);
OK, it seems that its not possible using getContentResolver().query().
I had to get db connection and make rawQuery.
ContentProviderClient client = getContentResolver().acquireContentProviderClient(AUTHORITY);
SQLiteDatabase dbHandle= ((MyContentProvider)client.getLocalContentProvider()).getDbHandle();
Cursor cursor = dbHandle.rawQuery("SELECT sum("+COLUM_NNAME+") FROM "+TABLE_NAME +" WHERE "+WHERE_CLAUSE , null);
cursor.moveToFirst();
int cnt = cursor.getInt(0);
cursor.close();
cursor.deactivate();
client.release();
ACCEPTED ANSWER IS WRONG
IT IS POSSIBLE IN CONTENTPROVIDER AS
String[] columns = new String[] { "sum(" + columnName + ")" };
Cursor cursor = getContentResolver().query(
content_uri,
columns,
selection,
selectionArgs,
sort
);
int columnSum = cursor.getInt(0);
Only mistake Tom did is he forget to do :
cursor.moveToFirst();
You could use the 'simpleQueryForLong()'-Method.

data type mismatch error when using ORDER BY

I've got an android app using a local sqlite database.
private SQLiteDatabase mDb;
when I run this query I get my Cursor over rows with pid equal to id, as desired:
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, null, null);
when I run the following query, aiming to get that same result set, ordered by pid I get "android.database.sqlite.SQLiteException: datatype mismatch"
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, null, KEY_PID+" DESC");
Any ideas?
It looks like you got just a little mixed up. According to the SQLiteDatabase.query documentation, the last argument is the LIMIT clause. The second to last is the ORDER BY clause.
Cursor query (boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy, // <-- ORDER BY
String limit)
EDIT
But, there is also another SQLiteDatabase.query where ORDER BY would be last
Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy)
This worked for me
String filter = MySQLiteHelper.JOB_ID + "=" + Integer.toString(jobID);
String orderBy = MySQLiteHelper.LOG_TIME + " DESC";
Cursor cursor = database.query(MySQLiteHelper.LOG_TABLE_NAME, logTableColumns,
filter, null, null, null, orderBy);
KEY_PID + " = " + "'" + id + "'"
Since Orderby is the second last parameter in the query;
your query would be like this
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, KEY_PID+" DESC", null);
If I correctly understood your problem, try this.
String[] columns = new String[] {KEY_PID, KEY_TID};
String where = KEY_PID + " = " + Integer.toString(id);
String orderBy = KEY_PID + " DESC";
Cursor cursor = mDb.query(PT_TABLE, columns, where, null, null, null, orderBy);

Categories

Resources