I'm creating an Android project and I have a "DBFunc" class that has multiple methods to handles queries called by the activities.
DBFunc.java
public int getTotalNumberOfQuestions (String table, String category) {
String selectQuery = "SELECT COUNT(*) FROM " + table + " WHERE category='" + category + "'";
// example
// SELECT COUNT(*) FROM questions WHERE category='History';
SQLiteDatabase database = this.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
int ans = -1; // returns -1 if query unsuccessful
if (c.moveToFirst()) {
ans = c.getInt(0);
}
database.close();
c.close();
return ans;
}
I'm getting an error on the cursor, saying
android.database.sqlite.SQLiteException: no such column: category (code 1): , while compiling: SELECT COUNT(*) FROM questions WHERE category='Physics'
but I do have a category column in my questions table
When running this query through sqlite3 on the command prompt, it works and returns a number (e.g 1)
Here's what the schema looks like in "DB Browser for SQLite"
I really hope there's an easy solution, because I don't understand why it wouldn't work,
Thanks
EDIT 1:
@CL asked for the code that creates the database. The database is created in sqlite3 command line and passed into the program. But the query I used was
CREATE TABLE questions (questionId INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT, option1 TEXT, option2 TEXT, option3 TEXT, option4 TEXT, category TEXT);
EDIT 2:
I did what @Uwe Partzsch sugested and used LIKE
instead of ' '
String selectQuery = "SELECT * FROM " + table + " WHERE category LIKE '" + category + "'";
But now I'm getting a different error
no such table: questions
EDIT 3:
public class DBFunc extends SQLiteOpenHelper {
public static String DB_PATH ="/data/data/com.example.healyj36.quizapp/databases/";
public static String DB_NAME = "questions.db";
public static final int DB_VERSION = 1;
public static final String TB_NAME1 = "questions";
public static final String TB_NAME2 = "answers";
private SQLiteDatabase myDB;
private Context context;
public DBFunc(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
//Copy database from source code assets to device
public void copyDataBase() throws IOException {
try {
InputStream myInput = context.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("tle99 - copyDatabase", e.getMessage());
}
}
public void createDatabase() throws IOException {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e("tle99 - create", e.getMessage());
}
}
...
String selectQuery = "SELECT COUNT(*) FROM " + table + " WHERE category like '" + category + "'";