I got a problem when trying to search in multiple columns of a SQLite db.
Here ist my current code
String whereClause;
if (!suchwort.contains("%")){ // Abfrage mit Wildcard?
whereClause = WoerterbuchContract.WoerterbuchEintraege.COLUMN_NAME_WORT_DEUTSCH
+ " = '"+suchwort+"'" ;}
else {
whereClause = WoerterbuchContract.WoerterbuchEintraege.COLUMN_NAME_WORT_DEUTSCH
+" like '"+suchwort+"'";}
Cursor ergCursor = db.query(
WoerterbuchContract.WoerterbuchEintraege.TABLE_NAME, // The table to query
projection, // The columns to return
whereClause, // WHERE clause
null, // no values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
I tried adding columns to my whereClause, but i allways get compiler errors.
Related
i want to filter multiple data such as
id = "1,3,5" from columnid which is having 1 to 10 id
and another column such as name
name = "a,e,d" from name column of 10 records
and another criteria such as age
age = "21,23,20" from age column of 10 records from same table,
one example i got is
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
which is just for one column but i want to get data from multiple column, can anyone help me?
try this working example,
Cursor cursor =
db.query(TABLE_DIARYENTRIES,
new String[] {},
STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
+ " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
null, null, null, null);
and your result string should be 'a','b','c'
I really like the way Google's example is structured. Because for noobies such as myself it makes it really clear what I am doing. And it is also more robust to SQL injections. Here is my modified version of the Google example:
//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};
//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};
Cursor cursor = db.query(
"MyTable", // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("this-is-a-test", cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
I am having trouble querying the my SQLiteDatabase using my custom ContentProvider. I am trying to query the database for one user using the 'user_id'. The following pieces of code which are associated with the problem are:
DBProvider.java
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder){
int match_code = myUriMatcher.match(uri);
Cursor c;
switch (match_code){
case USER_BY_ID: {
c = dbHelper.getReadableDatabase().query(
DBContract.User_Table.TABLE_NAME,
projection,
DBContract.User_Table.COLUMN_ID + "='" + ContentUris.parseId(uri) + "'",
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Not yet implemented");
}
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
ProfileActivity.java
// Columns to load
String[] columns = {
DBContract.User_Table.COLUMN_NAME // String "name"
};
// A cursor is your primary interface to the query results.
Cursor cursor = getActivity().getContentResolver().query(
ContentUris.withAppendedId(DBContract.User_Table.CONTENT_URI, Long.parseLong(id)), // Table to Query
columns, // Columns for the WHERE
DBContract.User_Table.COLUMN_ID, // selection
new String[]{"1"}, // Values for the WHERE
null // Sort Args
);
The error that I am getting is:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
Any help would be greatly appreciated!
Thanks
You should use:
Cursor cursor = getActivity().getContentResolver().query(
ContentUris.withAppendedId(DBContract.User_Table.CONTENT_URI, Long.parseLong(id)), // Table to Query
columns, // Columns for the WHERE
DBContract.User_Table.COLUMN_ID, // selection
null, // Values for the WHERE
null // Sort Args
);
You are using the selectionArgs parameter wrong. You don't have any ? in the selection parameter and the binding fails. More info in the documentation.
selectionArgs - You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
I have been trying to get the biggest value of a column. For this I sorted it by DESC so the biggest one comes first, but it turns out that any nulls actually come first for some reason. Therefore I tried to add a WHERE, but it still has nulls in it for some reason and I can't figure out why.
String[] projection = {
DATAbaseContract.DATAbaseEntry.COLUMN_PRICE,
};
String sortOrder =
DATAbaseContract.DATAbaseEntry.COLUMN_PRICE + " DESC";
Cursor DATAbaseCursor = DATAbaseDb.query(
DATAbaseContract.DATAbaseEntry.TABLE_NAME, // The table to query
projection, // The columns to return
ShipsContract.ShipsEntry.COLUMN_PRICE + " IS NOT NULL", // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if(!DATAbaseCursor.moveToPosition(0)) {return;}
PriceMaxVal=DATAbaseCursor.getInt(DATAbaseCursor.getColumnIndex(DATAbaseContract.DATAbaseEntry.COLUMN_PRICE));
PriceMinVal=0;
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"));
}
public static final String KEY_HIGH
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_HIGH + " INTERGE);"
);
}
public long createEntry(String high) {
ContentValues cv = new ContentValues();
cv.put(KEY_HIGH, high);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
String[] columns = new String[]{KEY_HIGH,KEY_NAME};
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null, KEY_HIGH + " DESC");
I am trying to sort by the column KEY_HIGH, however, the result came out like this:
4
3
2
10
11
1
How do I sort them as numbers from highest to lowest?
thanks.
From the Android docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Added in API level 1
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
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.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
See Also
Cursor
Note that the final is named orderBy. This is where you can specify which column (or columns) to sort on. Also note that you do not need to include the "ORDER BY" keywords that you would use in a SQL statement.
I was having the same problem.It has a very simple solution:
In your CREATE_TABLE statement do this: " INTEGER, "+KEY_HIGH+ //your remaining things.
no need for the comma after the last null
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null + " ORDER BY " + KEY_HIGH + " DESC");