I am trying to run a select using sqllite. Its my first time using sqllite and I am getting this error over and over.
function ="Adding Event
CODE:
public List<Example> getExampleByFunctionList(String function)
{
List<Example> examplelist = new ArrayList<Example>();
String getQuery = "SELECT * FROM " + MySQLiteHelper.TABLE_EXAMPLE+
" where "+ MySQLiteHelper.COLUMN_EXAMPLE_FUNCTION +" = "+""+function+"";
Cursor cursor = database.rawQuery(getQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Example example = cursorToExample(cursor);
examplelist.add(example);
cursor.moveToNext();
}
cursor.close();
return examplelist;
}
ERROR:
02-12 12:37:29.218: E/AndroidRuntime(3165): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tutorial/com.tutorial.ManageCalendar}: android.database.sqlite.SQLiteException: near "Events": syntax error: , while compiling: SELECT * FROM example where examplefunction = Adding Events
... +" = '"+function+"'";
^^^ ^^^
You need to quote string literals in SQL statements (regardless of whether they contain spaces or not).
Or use prepared statements and bind variables, which is much safer against SQL injection.
See: How do I use prepared statements in SQlite in Android?
Related
I am getting an error in Android Studio to do with my Cursor.
I have the following line in my code
String data = cursor.getString(cursor.getColumnIndex(columnIndex));
columnIndex is being passed into the method.
This part cursor.getColumnIndex(columnIndex) produces the following error
Value must be ≥ 0
Its happening in my DBHelper class and also my recycler adapter when it uses a cursor too.
It shows up as an error in red but the app still builds and runs without issue.
Any ideas?
Thanks for any help.
Update 22-Sep-21
I'm adding some code as requested and also how i have got around this error. Not sure if its the best way though.
So the method im using is this....
public String getTripInfo(String tableName, int tripNo, String columnIndex){
String data = "";
// Select all query
String selectQuery = "SELECT * FROM " + tableName + " WHERE " + TRIP_DETAILS_TRIP_NUMBER + "=" + tripNo;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if(cursor.moveToFirst()){
do{
data = cursor.getString(cursor.getColumnIndex(columnIndex));
} while(cursor.moveToNext());
}
// Closing connections
cursor.close();
db.close();
//Returning number plates
return data;
}
The error is in the do while loop. The part in red is "cursor.getColumnIndex(columnIndex))"
The way i have gotten around this error is using the following code instead
public String getTripInfo(String tableName, int tripNo, String columnIndex){
String data = "";
// Select all query
String selectQuery = "SELECT * FROM " + tableName + " WHERE " + TRIP_DETAILS_TRIP_NUMBER + "=" + tripNo;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if(cursor.moveToFirst()){
do{
int index = cursor.getColumnIndex(columnIndex);
data = cursor.getString(index);
} while(cursor.moveToNext());
}
// Closing connections
cursor.close();
db.close();
//Returning number plates
return data;
}
I had an error like this.
My solution : change method getColumnIndex into getColumnIndexOrThrow.
The problem is that cursor.getColumnIndex() can return -1, you're passing it as a direct parameter, and the cursor getters need a column index gte 0. The getters' parameter is annotated with #IntRange(from = 0) which is why lint marks it as an error.
So, even though you might have built your project such that it would never produce an invalid column index, the fact that such a possibly could exist is why lint is tagging it.
Your code revision only avoids the issue. It would be best to use cursor.getColumnIndexOrThrow() or test index for gte 0.
You can get away with your changes since you know more about your project than lint does, it just isn't the best practice.
Use This Method Proper Work :-
#SuppressLint("Range") Strong name = cursor.getString(cursor.getColumnIndex(indexNumber));
I am trying to fetch data which contains specific string but query is not working, following is method for fetching data.
public Cursor getSearch(String item) {
SQLiteDatabase db = this.getReadableDatabase();
String mQuery = "SELECT * FROM hadiths WHERE text LIKE %"+item.toString()+"%";
Cursor cursor = db.rawQuery(mQuery, null);
return cursor;
}
Logcat shows following error.
Caused by: android.database.sqlite.SQLiteException: near "%": syntax error (code 1): , while compiling: SELECT * FROM hadiths WHERE text LIKE %fast%
I know that the wildcard %% and string variable item is causing issue but how do I use string variable along with wildcard?
Edit:
As mentioned below by Jiří, parameters should be used to help prevent SQL injection issues.
In order to add parameters you could do something similar to this:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ?”;
String param1 = “%” + item + ”%”;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1});
In order to add another parameter:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ? AND Name = ?”;
String param1 = “%” + item + ”%”;
String param2 = name;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1, param2});
This code is a bit cumbersome, but it is to illustrate that the parameters must be added in the order in which they are should be added to the query.
see SQLite documentation:
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
Original answer here for posterity. WARNING Dangerous SQL injection issue!
You need to add single quotes to the query.
String mQuery = "SELECT * FROM hadiths WHERE text LIKE '%"+item+"%'";
Take a look at the SQLite docs:
https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
Note: There is no need to use toString() since "item" is already of type String.
im trying to get all the elements of a row in sqlite by ID using a cursor. The cursor is not null, but i can't seem to operate with the cursor, Here is my code:
public Book getBookByid (int itemId) {
String selectQuery = "SELECT * FROM " + tables[0] + " WHERE " + SQLiteHelper.ITEM_ID + " = " + itemId;
Cursor cursor = database.rawQuery(selectQuery, null);
Book bookRead = new Book();
if(cursor!=null) {
Log.i("myApp","cursor not null");
if (cursor.moveToFirst()) {
Log.i("myApp","title" + cursor.getColumnIndex(arrayFields.get(0)[1]));
bookRead.setTitle(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[1])));
bookRead.setGenre(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[2])));
bookRead.setDescription(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[3])));
bookRead.setRecommendation(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[4])));
bookRead.setPhoto(cursor.getString(cursor.getColumnIndex(arrayFields.get(0)[5])));
bookRead.setLike(cursor.getInt(cursor.getColumnIndex(arrayFields.get(0)[6])));
}
Log.i("myApp","title" + bookRead.getTitle());
}
cursor.close();
return bookRead;
}
The problem is that the code does not enter the if(cursor.moveToFirst()) so i cannot assing the values to my object, getting a null object reference.
My logs show the following:
05-13 09:37:23.720 13918-13918/com.appforbrands.meloapunto I/myApp﹕ cursor not null
05-13 09:37:23.720 13918-13918/com.appforbrands.meloapunto I/myApp﹕ titlenull
I'm also getting a blue warning or error in logcat:
05-13 10:04:14.555 3969-3969/com.appforbrands.meloapunto W/Bundle﹕ Key itemId expected Integer but value was a java.lang.Long. The default value 0 was returned.
05-13 10:04:14.559 3969-3969/com.appforbrands.meloapunto W/Bundle﹕ Attempt to cast generated internal exception:
This is steps you need to do to debug your function:
Make sure you have valid database connection.
Check and make sure your raw query are correct.
The itemID is exist in your data.
Sqlite may be confused finding your id in your Sqlite book table, so the query can't find any row. Check your table definitions or manually write the table id in your query String.
I'm trying to select a specific row from a database based on a string in a textview. The error log when I run it appears to say that it's looking for a column, but it should be looking for a row. The error log says:
--I/Database(279): sqlite returned: error code = 1, msg = no such column: Book
--D/AndroidRuntime(279): Shutting down VM
--W/dalvikvm(279): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
--E/AndroidRuntime(279): FATAL EXCEPTION: main
--E/AndroidRuntime(279): android.database.sqlite.SQLiteException: no such column: Book: , while compiling: SELECT book, background FROM bookbackgrounds WHERE book=Book
Here's the code where it gets the string from the textview, then runs a method that is supposed to return a filename in the form of a text string, then display the returned string in a second textview:
String bkString = showBooktextview.getText().toString();
bga.open();
String newBKstring = bga.getBGforBook(bkString);
bga.close();
showDBBooktextview.setText(newBKstring);
and here's the method that the error says there's no such column with the name of that book. (it's supposed to be looking for the ROW that contains that book name):
public String getBGforBook(String bkString) {
String[] thecolumns = new String[] { KEY_BOOK, KEY_BACKGROUND };
Cursor cursor = db.query(DB_TABLE, thecolumns, KEY_BOOK + "=" + bkString, null, null, null, null);
String result = "";
if (cursor != null){
cursor.moveToFirst();
result = result
+ cursor.getString(1);
}
return null;
}
so is the method written incorrectly? If so, how to write it correctly so that it looks for a row that contains the bookname string?
I think you are missing single quotes in the condition expression:
KEY_BOOK + "=" + bkString
should be
KEY_BOOK + "='" + bkString + "'"
Since the string bkString is not quoted, SQLite tries to interpret it as an identifier of a column name.
I am trying to update the database on the basis of incoming parameter but it is not updated.
i am using the following code:
public static void markFavoriteStation(String station, boolean favorite){
Log.d(AppConstants.TAG,"StationListDBIfc: +markFavoriteStation");
String Query = null;
mDb = bartDb.getWritableDatabase();
Query = "update stationlistTable set favorite ='1' where namewithabbr = '+station'";
mDb.rawQuery(Query, null);
Log.d(AppConstants.TAG,"StationListDBIfc: -markFavoriteStation");
}
I think you might have a malformed String definition. You should end the String before concatenating the "station" variable to it, like so:
Query = "update stationlistTable set favorite ='1' where namewithabbr = '" + station + "'";
I can't see any errors. I guess the SQL query has errors or the namewithabbr column doesn't contain what you expect. You should test it in the sqlite3 app.