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.
Related
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)
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);
I know how to query for a single selection with the following:
Cursor cursor = database.query(true, TABLE, COLUMNS, "name = ?", new String[]{"Bob"},null,null,null,null);
But suppose I want to make a function as follows:
public Cursor queryNames(String[] names)
where the function returns a cursor where the name = names[0] OR name = names[1] ... etc. So for example, if I called the function queryNames(new String[] {"Alice","Bob","Charlie"}), the function should return a cursor where the name is any of the three (Alice, Bob, or Charlie). How would I write this? Thanks!
Your method might want to look like this:
public Cursor queryNames(String[] names) {
SQLiteDatabase mDb = this.getReadableDatabase();
String whereStatement = "";
for(int i = 0; i < names.length; i++) {
if (i != (names.length - 1))
whereStatement = whereStatement + "name = ? OR "
else
whereStatement = whereStatement + "name = ?"
Cursor cursor = mDb.query(true, TABLE, COLUMNS, whereStatement, names, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
mDb.close();
return cursor;
}
Hope this helps!
try:
Cursor cursor = db.query(true, TABLE, COLUMNS, "name IN (?)", new String[]{" 'moe', 'larry', 'curly'"}, null, null, null, null);
It would probably be best to build the String[] separately than to guess at the number of names.
Enclose the whole thing in double quotes, the individual names in single quotes, comma-separated.
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);
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);