Android Studio 0.4.4
Hello,
I have this onCreate in my main_activity class:
DBHelper dbHelper;
SQLiteDatabase db = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
/* Database hasn't been created yet, if already created and opened ignore */
if(db == null) {
db = dbHelper.getWritableDatabase();
Log.d(TAG, "onCreated() Create database for the first time");
}
}
I have the dbHelper class that calls onCreate, onUpdate, etc. However, as my application will use portrait and landscape, each time the user switches it will call the onCreate method. I don't want to have to keep creating the same database each time. I tried checking for a null, but this didn't work.
I cannot disable the calling onCreate in the manifest file (android:configChanges), as I have savedInstanceState that I will need in this method each time the user switches.
Many thanks for any suggestions,
public class DBHelper extends SQLiteOpenHelper {
static final String DB_NAME = "friends.db";
static final int DB_VERSION = 1;
static final String TABLE = "friends";
static final String C_ID = BaseColumns._ID;
static final String C_NAME = "name";
static final String C_PHONE = "phone";
static final String C_EMAIL = "email";
private final String TAG = "DBHELPER";
// Constructor
public DBHelper(Context _context) {
super(_context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "(" + C_ID + " int primary key, "
+ C_NAME + " text, "
+ C_PHONE + " text, "
+ C_EMAIL + " text)";
db.execSQL(sql);
Log.d(TAG, "onCreate sql: " + sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table if exists " + TABLE;
// Drop old database if it exists
db.execSQL(sql);
// Create a new database
Log.d(TAG, "onUpgrade() sql: " + sql);
onCreate(db);
}
}