0

I am trying to implement a static database as I was having a lot of issues with reopening closed resources. When calling getWritableDatabase(), I expect the onCreate for the DatabaseHelper to be called and start setting up my tables. However, it does not get called.

From MainActivtity.java:

    public class MainActivity extends Activity {

    DatabaseHelper db;
    String buttonClicked;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        db = DatabaseHelper.getInstance(this);
    }

From DatabaseHelper.java:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String LOG = "";
    private static DatabaseHelper sInstance;
    private static SQLiteDatabase db = null;
    private static Context context;

    // Database name
    private static final String DATABASE_NAME = "workout.db";

    // Database version number
    private static final int DATABASE_VERSION = 1;

    // Table names
    public static final String TABLE_DAY_OF_WEEK = "table_day_of_week";
    public static final String TABLE_DAY_HAS_EX = "table_day_exercise";
    public static final String TABLE_EXERCISE = "table_exercise";
    public static final String TABLE_EX_HAS_HIS = "table_exercise_history";
    public static final String TABLE_HISTORY = "table_history";

    // Common column names
    public static final String KEY_ID = "_id";
    public static final String COLUMN_EXERCISE_ID = "exercise_id";
    public static final String COLUMN_EXERCISE = "exerciseName";
    public static final String COLUMN_REPETITIONS = "numReps";
    public static final String COLUMN_NOTES = "notes";

    // Dayofweek table columns
    public static final String COLUMN_WEEKDAY = "dayName";
    public static final String COLUMN_SUMMARY = "summary";

    // Day Has Exercises table columns
    public static final String COLUMN_DAY_ID = "day_id";

    // Exercise Has History table columns
    public static final String COLUMN_HISTORY_ID = "history_id";

    // History table columns
    public static final String COLUMN_DATE = "date";
    public static final String COLUMN_COMPLETED_TIME = "time";


    // Dayofweek table creation statement
    private static final String CREATE_DAYOFWEEK_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_DAY_OF_WEEK + "( " + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_WEEKDAY + " TEXT, " + COLUMN_SUMMARY + " TEXT )";

    // Day Has Exercises  table creation statement
    private static final String CREATE_DAY_HAS_EX_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_DAY_HAS_EX + "( " + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DAY_ID + " INTEGER, " + COLUMN_EXERCISE_ID  + " INTEGER )";

    // Exercise table creation statement
    private static final String CREATE_EXERCISE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_EXERCISE + "( " + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_EXERCISE + " TEXT, " + COLUMN_REPETITIONS + " INTEGER, " + COLUMN_NOTES + " TEXT )";

    // Exercise Has History table creation statement
    private static final String CREATE_EX_HAS_HISTORY_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_EX_HAS_HIS + "( " + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_EXERCISE_ID + " INTEGER, " + COLUMN_HISTORY_ID + " INTEGER )";

    // History table creation statement
    private static final String CREATE_HISTORY_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_HISTORY + "( " + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_EXERCISE + " TEXT, " + COLUMN_WEEKDAY + " TEXT, " + COLUMN_REPETITIONS +
            " INTEGER, " + COLUMN_NOTES + " TEXT, " + COLUMN_DATE + " TEXT, " + COLUMN_COMPLETED_TIME + " TEXT )";

    private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
        DatabaseHelper.context = context;
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            db = sInstance.getWritableDatabase();
        }
        return sInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    // create required tables
    db.execSQL(CREATE_DAYOFWEEK_TABLE);
    db.execSQL(CREATE_EXERCISE_TABLE);

    // enter days of the week default entries
    insertWeekday("Monday", db);
    insertWeekday("Tuesday", db);
    insertWeekday("Wednesday", db);
    insertWeekday("Thursday", db);
    insertWeekday("Friday", db);
    insertWeekday("Saturday", db);
    insertWeekday("Sunday", db);
    }
    public boolean insertWeekday(String dayName, SQLiteDatabase db) {

    boolean createSuccessful = false;
    ContentValues values = new ContentValues();
    values.put(COLUMN_WEEKDAY, dayName);
    values.put(COLUMN_SUMMARY, "");

    createSuccessful = db.insertWithOnConflict(TABLE_DAY_OF_WEEK, null, values,
            SQLiteDatabase.CONFLICT_IGNORE) > 0;
    return createSuccessful;
    }

public ObjectDay readSummary(String dName/*, SQLiteDatabase db*/) {
    getReadableDatabase();

    ObjectDay objectDay = new ObjectDay();
    objectDay.setDayName(dName);

    String sql = "SELECT * FROM " + TABLE_DAY_OF_WEEK + " WHERE " + COLUMN_WEEKDAY + " = " + dName;

    Cursor cursor = db.rawQuery(sql, null);

    if (cursor.moveToFirst()) {

        int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID)));
        String summary = cursor.getString(cursor.getColumnIndex(COLUMN_SUMMARY));

        objectDay.setId(id);
        objectDay.setSummary(summary);
    }

    cursor.close();
    return objectDay;
}

I've tried resetting the AVD phone and wiping user data but it didn't help. The example code I've been referring to is at

http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html

and

https://gist.github.com/jcxavier/1486739. Any insight would be much appreciated.

Edit: Ok, apparently onCreate is being called. The issue is happens later. I create column names for the days of the week. But when I go to query the database, it says that the column is not found. I've stepped through it and it appears that the columns are added so I'm at a loss.

Johnny
  • 675
  • 3
  • 15
  • 25

1 Answers1

0

You need to quote your string literals in SQL:

String sql = "SELECT * FROM " + TABLE_DAY_OF_WEEK + " WHERE " + COLUMN_WEEKDAY + " = " + dName;

Cursor cursor = db.rawQuery(sql, null);

Change to:

String sql = "SELECT * FROM " + TABLE_DAY_OF_WEEK + " WHERE " + COLUMN_WEEKDAY + " = '" + dName + "'";

Cursor cursor = db.rawQuery(sql, null);

Note the single quotes around dName.

Or even better, use parameters:

String sql = "SELECT * FROM " + TABLE_DAY_OF_WEEK + " WHERE " + COLUMN_WEEKDAY + " = ?";

Cursor cursor = db.rawQuery(sql, new String[] { dName });

Without the quotes or ? parameter placeholder it is interpreted as an identifier (column name) and not a literal value.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • I will try this! Should there be another quote after the question mark? – Johnny Aug 05 '14 at 10:02
  • Yes, of course you need to terminate the Java string literal with `"` and the statement with `;`. Edited. – laalto Aug 05 '14 at 10:03
  • I got this error when trying the second version. android.database.sqlite.SQLiteException: no such column: dayName (code 1): , while compiling: SELECT * FROM table_exercise WHERE dayName = Monday ORDER BY _id DESC – Johnny Aug 05 '14 at 10:10
  • Well, your `table_exercise` doesn't have such column. The code you posted was querying from `table_day_of_week` and it seems to have such column. – laalto Aug 05 '14 at 10:13
  • Ok, I see that now. That is strange though because I entered in the code from your second example exactly. So I'm not sure why it would be querying from table_exercise. – Johnny Aug 05 '14 at 10:19