erroring out when executing rawquery in sqlite - android

i am trying to execute rawquery in sqlite in android but its erroring out .
My SQL code is :
String sql = "select vaccine_name,vaccine_duration from table_vaccinelists where vaccine_type=";
String[] selectionArgs = new String[10];
selectionArgs[0] = "'C'";
Cursor cur = database.rawQuery(sql, selectionArgs);
Error :
Its giving "Null pointer exception" .i am new to android and i feel there is something wrong the way i have written the where clause in the query .

Yes, there is something wrong with your query: selectionArgs are there to replace question marks in your query.
String sql = "select vaccine_name,vaccine_duration from table_vaccinelists where vaccine_type=?";
String[] selectionArgs = new String[]{"C"};
Cursor cur = database.rawQuery(sql, selectionArgs);
However, it shouldn't cause NPE, so something else might be wrong. I think your database variable is null, check the way you initialise it.

Related

syntax error in "SELECT DISTINCT _id near "SELECT"

If someone knows a better way to get a rowId from text in the row, please let me know.
I've been running around in circles with this and I know it's probably something simple, but I can't figure it out. Hoping someone can tell me what I'm doing wrong. I'm getting an error running this SQLite code:
String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol=" + name;
Cursor c = db.query(true, masterName, ALL_KEYS_MASTER, where, null, null, null, null, null);
The error points to the second line.
"name" is a string variable (in this case it's "Mary"). The exact error I'm getting is:
SQLiteLog: (1) near "SELECT": syntax error in "SELECT DISTINCT _id, masNameCol, masTotalTimeCol FROM masterRecord WHERE SELECT rowid, * FROM masterRecord WHERE masNameCol=Mary"
I've tried every syntax change I could find and think of, and it never changes the error. I'm just trying to get the rowId of the row so I can change a value in another column.
Use rawQuery(), not query().
You are trying to specify the entire SQL statement, which is what rawQuery() is for. query() assembles the SQL statement from pieces, and your one piece (where) is not just the WHERE clause.
Use placeholders for queries:
where = "masNameCol = ?";
whereArgs = new String[] { name };
columns = new String[] { "rowId" , /* all other column names you are interested in */ };
Cursor c = db.query("mytable", columns, where, whereArgs, null, null, null);

Android SQLite query cursor moveToFirst

I'm making an Android App with a sqlite db, which has a query method like this:
String[] projection = {COLUMN_NAME_ID};
String selection = COLUMN_NAME_TEAM + " = ?";
String[] selectionArgs = {teamId.toString()};
String sortOrder = COLUMN_NAME_NAME + " ASC";
Cursor c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
if (c.moveToFirst()){
//...
}
as suggested here. The point is to implement this query:
SELECT PLAYER_ID FROM PLAYERS WHERE TEAM_ID = ? ORDER BY NAME ASC;
According to the SQLiteDatabase.query documentation, this is a valid call to query(), and so far I've been doing it successfully with all my other queries in this App.
For some reason, in this query (and only in this) the App freezes in c.moveToFirst().
Some answers to similar questions suggest that it might be a performance issue. I don't think this is the case, as my table has only 6 rows and the query is quite simple.
Any ideas?
Thanks

SQLiteDatabase Cursor empty only on Android 5.0+ devices

The application has a SearchView which fetches suggestions from a specific database table. Everything worked without any errors until Android 5.0 appeared.
As of then, when the SQLiteQueryBuilder queries the database to fill the Cursor object, the return is empty cursor. Not NULL, but empty.
On other platforms, I can output the Cursor's content via DatabaseUtils.dumpCursorToString(cursorObject), but on Android 5.0+ the method reports output on null objects
Dumping cursor null
<<<<<
Even more: when I extract database file from 5.0+ devices and run the local SQL query, I can fetch all data. So the database is valid indeed. And the query is the simplest one
SELECT rowid AS _id, suggest_text_1, suggest_text_2, rowid AS suggest_intent_data_id
FROM fts
WHERE (fts MATCH '*e*') //<-- I pressed "e" on the keyboard
The logic for selecting data from the database and filling the Cursor object is really simple
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS3_TABLE);
builder.setProjectionMap(mColumnMap);
Cursor cursor = builder.query(db,columns, selection, selectionArgs,
null, null, null);
I tried looking for some deprecated methods, but was without any luck.
I have already spent 3 days debugging each step in the process and I am out of any ideas what could be causing such behaviour.
Anyone has any ideas?
EDIT
The output of the method buildQuery()
String query = builder.buildQuery(columns, selection, null, null, null, null);
RESULT:
SELECT rowid AS _id, suggest_text_1, suggest_text_2, rowid AS suggest_intent_data_id
FROM fts
WHERE (fts MATCH ?)
selection and selectionArgs parameters are created like this
String selection = FTS3_TABLE + " MATCH ?";
String[] selectionArgs = new String[]{"*" + query + "*"};
The RAW query resulted the same thing as query via builder.query()
String query = builder.buildQuery(columns, selection, null, null, null, null);
Cursor temp = db.rawQuery(query, selectionArgs);
String output = DatabaseUtils.dumpCursorToString(temp);
Output: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor#295023a7
<<<<<
Answered https://stackoverflow.com/a/30710226/437039 by laalto
MATCH '*foo*' queries never worked correctly in any version of sqlite. The fact that you got some results earlier was just a coincidence. Just the prefix form MATCH 'foo*' (and MATCH 'foo') are supported.
Lollipop ships with a newer version of sqlite. For detailed list of changes between sqlite versions, see the changelog.
Have you tried to query using the SQLiteDatabase query method like the following?
String selection = "fts" + " =? AND " +
String[] selectionArgs = new String [] {
"*e*"
};
String[] projection = new String [] { "rowId", "suggested_text"};
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor cursor = db.query("tableName",
projection,selection, selectionArgs, null, null, null);

How to use selection args to query specific rows from a contentprovider in android

i have constructed a basic content provider that stores SMS messages for learning purposes, so far i can read(without selection args), insert, update and delete.
However i have been stumped trying to figure out how to format the selection args for the WHERE clause in my provider:
Basicly my application needs to search for a specific timestamp (in long format) and return its _id
say your database has an entry like this that your trying to access:
2|1|1410293471300|test type 1||testing|0
and the entire database looks like this:
_id|CLIENTTRXID|CREATED_AT|TYPE|MESSAGEPRIO|MESSAGE|ACCEPTED
1|1|1410293471000|test type 1||testing|0
2|1|1410293471300|test type 1||testing|0
3|1|1410293471600|test type 1||testing|0
in sql the query would be
"select _id from alerts where CREATED_AT=1410293471300;"
the code i was hoping would do the equivalent:
//normally i would get the string dynamically but to make it equal to the sql
String date = "1410293471300";
String[] selectionArgs = new String[]{ date };
Cursor cursor = getContext().getContentResolver().query(AlertContract.CONTENT_URI, null, AlertContract.Column.CREATED_AT, selectionArgs, AlertContract.DEFAULT_SORT);
seems to always produce the following error no matter what i try as selectionArgs
Exception caught﹕ Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
here is the query method of my contentprovider:
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables( AlertContract.TABLE);
switch (sURIMatcher.match(uri)) {
case AlertContract.STATUS_DIR:
break;
case AlertContract.STATUS_ITEM:
qb.appendWhere(AlertContract.Column.ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException( "illegal uri: " + uri);
}
String orderBy = (TextUtils.isEmpty(sortOrder)) ? AlertContract.DEFAULT_SORT : sortOrder;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
//register for uri changes
cursor.setNotificationUri(getContext().getContentResolver(), uri);
Log.d(TAG, "queried records: "+cursor.getCount());
return cursor;
}
Presumably im missing something extremely obvious, and will feel quite silly for having posted this question.
But for the moment i would very much appreciate any help, as i am quite stumped.
It looks like your issue is with your selection, rather than with your selectionArgs per se. The selection should be the whole query after the "where". Here your selection is "CREATED_AT". You need two more items to get it to work:
an =, since you want equality (you can also do other operators, of course)
a ?. This is where your selectionArgument will be inserted (each argument needs a ? in the selection, so there should be the same number of ?s in the selection as selectionArguments.
The end result should be more like "CREATED_AT = ?"
Check out the documentation and this tutorial for more info on how to correctly construct a ContentProvider query.
When you query the content provider, try the following. The selection should be AlertContract.Column.CREATED_AT + "=?"
Cursor cursor = getContext().getContentResolver().query(AlertContract.CONTENT_URI, null, AlertContract.Column.CREATED_AT + "=?", selectionArgs, AlertContract.DEFAULT_SORT);

How can pass two parameters to rawQuery in android? [duplicate]

PREF_NAME, PREF_STATUS - text
It gives me this error:
07-02 14:08:07.457: E/AndroidRuntime(17295): android.database.sqlite.SQLiteException: near "?": syntax error: , while compiling: SELECT ? FROM ? WHERE ? = ?
The code I'm using is:
Cursor c = db.rawQuery("SELECT ? FROM ? WHERE ? = ?", new String[]{ PREF_STATUS,
PREF_TABLE, PREF_NAME, assigned_pref_name });
According with the documentation, you only can put "?" on where clause:
public Cursor rawQuery (String sql, String[] selectionArgs)
Parameters
sql the SQL query. The SQL string must not be ; terminated
selectionArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
After the SELECT keyword you have a ? instead of something like *.
I guess you wanted to pass assigned_pref_name as a string and not variable name so :
Cursor c = db.rawQuery(
"SELECT ? FROM ? WHERE ? = ?",
new String[]{
PREF_STATUS,
PREF_TABLE,
PREF_NAME,
"assigned_pref_name" //as a string
});

Categories

Resources