jeudi 16 avril 2015

openDatabase() returns null

I have setup a SQlite manager as outlined here.

When calling openDatabase(), it does not create the database, i.e. getting an NPE. This happens on both an emulator and a device.

What am I doing wrong?


MainActivity



MySQLiteHelper permitsSQLiteHelper = new MySQLiteHelper(mainActivity);
MySQLLiteManager.initializeInstance(permitsSQLiteHelper);
MySQLLiteManager.getInstance().openDatabase();


Classes



public class MySQLLiteManager {

private int mOpenCount;

private static MySQLLiteManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;

// hide constructor here
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new MySQLLiteManager();
mDatabaseHelper = helper;
}
}

public static synchronized MySQLLiteManager getInstance() {
if (instance == null) {
Log.e("MySQLLiteManager", "getInstance : null");
throw new IllegalStateException(MySQLLiteManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}

return instance;
}

public synchronized SQLiteDatabase openDatabase() {
mOpenCount++;
if(mOpenCount == 1) {
// Create and/or open a database that will be used for reading and writing.
try {
mDatabase = mDatabaseHelper.getWritableDatabase(); // mDatabaseHelper.database is null
}
catch (Exception e) {
Log.e("MySQLLiteManager", "openDatabase:exception : " + e.getMessage()); // NPE
e.printStackTrace();
}
}
return mDatabase;
}

public synchronized void closeDatabase() {
mOpenCount--;
if(mOpenCount == 0) {
mDatabase.close();
}
}

public synchronized void deleteTable(String tableName) {
if(mOpenCount == 1) {
mDatabase.delete(tableName, null, null);
}
}

}

public class MySQLiteHelper extends SQLiteOpenHelper {

private static final String DB_CONTROLLER = "MySQLiteHelper";

public static String DB_NAME = "MyAndroid.db";
private static int DB_VERSION = 1;

private SQLiteDatabase database;

// constructor
public MySQLiteHelper(Context applicationcontext) {
super(applicationcontext, DB_NAME, null, DB_VERSION);

Log.d(DB_CONTROLLER,"Database Created");
}

@Override
// This method is called only if the database does not exist
// Creating the table here can cause problems if the table is deleted and the database remains
public void onCreate(SQLiteDatabase database) {

MySQLLiteManager.getInstance().createTable(MinesAndMyDataEntry.TABLE_NAME);

Log.d(DB_CONTROLLER, MinesAndMyDataEntry.TABLE_NAME + " Created");
}

@Override
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
String query;
query = "DROP TABLE IF EXISTS " + MinesAndMyDataEntry.TABLE_NAME;
database.execSQL(query);
onCreate(database);
}
}

Aucun commentaire:

Enregistrer un commentaire