user3352488
user3352488

Reputation: 281

Android Global SQLite Database Access

I am trying to make my SQLite database globally accessible throughout my Android application using a singleton pattern:

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "foo";
    private static final int DATABASE_VERSION = 1;
    private static MySQLiteOpenHelper instance;

    private MySQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static MySQLiteOpenHelper getInstance(Context context) {
        if (instance == null) {
            instance = new MySQLiteOpenHelper(context);
        }
        return instance;
    }

    public static MySQLiteOpenHelper getInstance() throws UnsupportedOperationException {
        if (instance == null) {
            throw new UnsupportedOperationException();
        }
        return instance;
    }

...

The idea here is that the first call is to getInstance(Context context) passing in the Application object. Thereafter I can just use getInstance() where I can't get a handle on a Context object.

However, I come unstuck when I make the initial MySQLiteOpenHelper.getInstance(getApplication()) call:

java.lang.IllegalStateException: getDatabase called recursively
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:204)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)

Can anyone shed any light on what is happening here or suggest a better technique for achieving my goal?

Cheers!

Upvotes: 1

Views: 1471

Answers (2)

laalto
laalto

Reputation: 152817

The code you posted is just fine.

java.lang.IllegalStateException: getDatabase called recursively

This is caused when you call e.g. getWritableDatabase() recursively.

One common cause for it is to call getWritableDatabase() in database helper onCreate(). The onCreate() gets invoked when getWritableDatabase() is called and the database does not exist. Calling getWritableDatabase() again is an error. You should use the writable SQLiteDatabase passed to onCreate() as an argument instead.

Upvotes: 2

juanhl
juanhl

Reputation: 1170

Your MySQLiteOpenHelper should works fine.

That class is not the problem.

Upvotes: 0

Related Questions