I have a question regarding the the usage of sqlite databases on Android. The main problem I have is the error 'Cannot be referenced from a static context'
Basically I have different classes which would require access to the database therefore I figured the database should be static. The question is then how do I initialise the database in MainActivity?
public class MainActivity extends BlunoLibrary {
//start db//
public static StoredValuesDBHelper StoredValuesDB = new StoredValuesDBHelper(this);
public static SQLiteDatabase db = StoredValuesDB.getWritableDatabase();
....
}
where my database class is (essentially from the google sql tutorial)
package com.example.healthcare;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class StoredValuesDBHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "StoredValues.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
public static abstract class ValueEntry implements BaseColumns {
public static final String TABLE_NAME = "storedvalue";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_CONTENT = "content";
}
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + ValueEntry.TABLE_NAME + " (" +
ValueEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
ValueEntry.COLUMN_NAME_CONTENT + TEXT_TYPE + COMMA_SEP +")";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + ValueEntry.TABLE_NAME;
public StoredValuesDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
Any help is much appreciated!
I have near zero experience in java and android programming
Aucun commentaire:
Enregistrer un commentaire