Douglas Mesquita Douglas Mesquita - 3 months ago 22
Android Question

Error when I try get all object in database android sqlite

I trying get all object in my database when value is "completed" but I get a exception. I think my query is correct because I use the same query in another method to recover only object.

public List<DownloadProfile> getAllDownloadProfile(String state) {
List<DownloadProfile> downloadProfiles = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + DownloadEntry.TABLE_NAME
+ " WHERE " + DownloadEntry.COLUMN_NAME_DL_STATE + " = " + state + "", null);

if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
DownloadProfile downloadProfile = new DownloadProfile(-1, "", "", "");
downloadProfile.path = cursor.getString(cursor.getColumnIndex(DownloadEntry.COLUMN_NAME_DL_PATH));
downloadProfile.extension = cursor.getString(cursor.getColumnIndex(DownloadEntry.COLUMN_NAME_DL_EXTENSION));
downloadProfile.downloadId = cursor.getInt(cursor.getColumnIndex(DownloadEntry.COLUMN_NAME_DL_ID));
downloadProfiles.add(downloadProfile);

} while (cursor.moveToNext());
}
cursor.close();
return downloadProfiles;
}


My exception:

Caused By : SQL(query) error or missing database.
(no such column: completed (code 1): , while compiling: SELECT * FROM download WHERE download_state = completed)
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1454)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1393)
at com.samsung.sidia.rio360.database.DownloadDatabase.getAllDownloadProfile(DownloadDatabase.java:47)
at com.samsung.sidia.rio360.model.DownloadModel.getVideoIDsAtState(DownloadModel.java:82)
at sidia.rio360app.MainActivity.resumeDl(MainActivity.java:54)

Answer

String literals in SQL go in 'single quotes'. Unquoted strings are interpreted as identifiers such as column names.

However, it's better to use ? variables and bind the values:

Cursor cursor = db.rawQuery("SELECT * FROM " + DownloadEntry.TABLE_NAME
        + " WHERE " + DownloadEntry.COLUMN_NAME_DL_STATE + " = ?", new String[] { state });