There is android sqlite database with one table, im using this query for getting values :
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=? AND problemtype=?",
new String[] { roosazi,type,problem }, null, null,KEY_Items_ID+" "+date , null);
everything is working fine.
question is:
how can i get all from specific column? let me give an example:
all values with type="A" and operationtype="XYZ" are needed , no matter what problemtype is! of course i can use something like this :
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=?",
new String[] { roosazi,type }, null, null,KEY_Items_ID+" "+date , null);
but problem is sometimes problemtype is X and sometimes its like ALL!
how can i achieve this? can i put something like * instead of problem?
thank u so much
I understand that you want to use the same query to get sometimes with a particular problem type like X,Y or Z, and sometimes with any problem type,
If that is the case you could use the statement 'like' in your query instead of '=' in the problemtype field
Cursor cursor = db.query(Table_Items, null, "type=? AND operationtype=? AND problemtype like '?'",
When you want to return all values just past
problem = "%"
% simbol means any characters,
When you want to return values with a particular problem use
problem = "X"
in the values array
new String[] { roosazi,type,problem }
Related
I'm writing a method to update default settings in a table. The table is very simple: two columns, the first containing labels to indicate the type of setting, the second to store the value of the setting.
At this point in the execution, the table is empty. I'm just setting up the initial value. So, I expect that this cursor will come back empty. But instead, I'm getting an error (shown below). The setting that I am working with is called "lastPlayer" and is supposed to get stored in the "SETTING_COLUMN" in the "SETTINGS_TABLE". Here's the code:
public static void updateSetting(String setting, String newVal) {
String table = "SETTINGS_TABLE";
String[] resultColumn = new String[] {VALUE_COLUMN};
String where = SETTING_COLUMN + "=" + setting;
System.err.println(where);
SQLiteDatabase db = godSimDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(table, resultColumn, where, null, null, null, null);
System.err.println("cursor returned"); //I never see this ouput
\\more
}
sqlite returned: error code = 1, msg = no such column: lastPlayer
Why is it saying that there is no such column lastPlayer? I thought that I was telling the query to look at the column "SETTING_COLUMN" and return the record where that column has a value "lastPlayer". I'm confused. Can somebody straighten me out? I've been looking a this for an hour and I just don't see what I am doing wrong.
Thanks!
You're not properly building/escaping your query. Since the value lastPlayer is not in quotes, your statement is checking for equality of two columns, which is what that error message is saying.
To properly build your query, it's best to not do this manually with String concatenation. Instead, the parameter selectionArgs of SQLiteDatabase.query() is meant to do this.
The parameters in your query should be defined as ? and then filled in based on the selectionArgs. From the docs:
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.
So, your code would look like this:
String where = SETTING_COLUMN + " = ?";
Cursor cursor = db.query(table, resultColumn, where, new String[] { setting }, null, null, null);
I'm working on Android contact. I want to query phone numbers (not contact name) from a specific group name. What query should i perform in order to do this?
Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI
, null, ContactsContract.Data.MIMETYPE+"=?"
, new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE}
, null);
Then loop through cursor and get data u want. This will return data blocks showing the contactID and the groupID and other info. With this then query ContactsContract.Groups and get data about the group to compare.
If you are looking for specific data about a group first query for group row ID than you can add that to the following cursor like so...
Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI
, null, ContactsContract.Data.MIMETYPE+"=? AND "+ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID+"=?"
, new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, rowID }
, null);
wrote code here so sorry for silly mistakes
You can find group id like so...
Cursor c = context.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, new String[]{ContactsContract.Groups._ID}, ContactsContract.Groups.TITLE+"=?","myGroup", null);
I query and get a result set back, but I need to do some calculations that are impossible in the SQLite WHERE clause in order to determine what shows up in the ListView. How can I remove certain rows from the cursor? I know it is the same question as this Filter rows from Cursor so they don't show up in ListView but that answer does not help. Can an example be provided if there isn't a simpler way to do this?
It might work to simply retain all the rows in the Cursor, but then use a custom adapter to hide the unwanted rows at display time. For example, if you extend CursorAdapter, then you might have something like this in your bindView implementation:
View v = view.findViewById(R.id.my_list_entry);
boolean keepThisRow = .......; // do my calculations
v.setVisibility(keepThisRow ? View.VISIBLE : View.GONE);
There should be a better way to do this, but what I ended up doing is storing the ID of each row I wanted in a string ArrayList, and then requerying where _id IN arraListOfIds.toString(), replacing the square brackets with parentheses to fit SQL syntax.
// Get all of the rows from the database
mTasksCursor = mDbHelper.fetchAllTasks();
ArrayList<String> activeTaskIDs = new ArrayList<String>();
// calculate which ones belong
// .....
if (!hasCompleted)
activeTaskIDs.add(mTasksCursor.getString(TaskerDBadapter.INDEX_ID));
// requery on my list of IDs
mTasksCursor = mDbHelper.fetchActiveTasks(activeTaskIDs);
public Cursor fetchActiveTasks(ArrayList<String> activeTaskIDs)
{
String inClause = activeTaskIDs.toString();
inClause = inClause.replace('[', '(');
inClause = inClause.replace(']', ')');
Cursor mCursor = mDb.query(true, DATABASE_TABLE, columnStringArray(),
KEY_ROWID + " IN " + inClause,
null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
The "What Columns" piece above is where you can tell the cursor which rows to return. Using "null" returns them all.
I need to do some calculations that
are impossible in the SQLite WHERE
clause
I find this very hard to believe; my experience has been that SQL will let you query for just about anything you'd ever need (with the exception of heirarchical or recursive queries in SQLite's case). If there's some function you need that isn't supported, you can add it easily with sqlite_create_function() and use it in your app. Or perhaps a creative use of the SELECT clause can do what you are looking for.
Can you explain what these impossible calculations are?
EDIT: Nevermind, checking out this webpage reveals that the sqlite_create_function() adapter is all closed up by the Android SQLite wrapper. That's annoying.
Hello i've spent almost 2 hours trying to figure out why the LIKE statement doesn't work and i only get this error: 03-03 11:31:01.770: ERROR/AndroidRuntime(11767): Caused by: android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x89d9f8
In SQLiteManager it works perfectly like this: SELECT Word FROM Sign WHERE Word LIKE 'he%';
But when i try to do it from java it won't work.
Here's is my query, i've tried in a lot of ways with no luck:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+" ?"+"%'", new String[]{name}, null, null, null);
Any ideas? i'm i doing it wrong or is there a bug?
Thanks for your time.
The solution is actually very easy. Just include the % inside your selectionArgs.
String []selectionArgs = {name + "%"});
I think you shouldn't use selArgs for LIKE such a way. You may try this:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+name+"%'", null, null, null, null);
EDIT:
OK, if you want be safe from SQL injections, don't use above solution, use this:
Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word LIKE '?'", new String[]{name+"%"}, null, null, null);
This is how I did:
String []columns = {"_id", "name"};
String []selectionArgs = {name+"%"};
db.query(true,"mydb",columns,"name LIKE ?",selectionArgs,null,null,null);
Another -- perhaps cleaner -- solution is to use the || operator as described here: Sqlite binding within string literal
I'm getting an annoying error when trying to query some data in SQLite.
Here is my code:
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = "+compareToThis, null, null, null, null);
I'm just returning the cursor as a string.
The error is saying:
no such column: compareToThis: while compiling.....the statement
My question is: why is SQLite setting the compareToThis attribute as a column when it's just a value?
How can I fix this?
Thanks in advance.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = ?", new String[]{compareToThis}, null, null, null);
The selection must include placeholder for parameter, and the next argument should be the array of parameters.
The solution by Vladimir works, however if you are like me and wonder why your approach did not work initially when it should have, here is why:
It is because it expects an integer unless you used (single or double) quotation marks to indicate that it is a string.
For example, in MySql this would return no results:
SELECT * FROM clients WHERE firstName = Bob; -- This will not work.
However when you surround it with quotations, it will return a result because it identifies Bob as a String literal.
Select * FROM clients WHERE firstName = 'Bob'; -- Single quotes work.
Select * FROM clients WHERE firstName = "Bob"; -- Double quotes as well.
Therefore for it to work, you would have to surround your compareToString with single quotes, as Muhhammad mentioned within the comments.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +'" = "+compareToThis+"'", null, null, null, null);