2

I am looking for a way to openOrCreateDatabase from another non-activity class and all tutorials and SO questions I found so far, are against that.

Why?

Method openOrCreateDatabase can be called only from Service or Activity or I can call it as a static method SQLiteDatabase.openOrCreateDatabase.

However, this method's second parameter, requires CursorFactory, which in most tutorials is: MODE_PRIVATE. I can't use MODE_PRIVATE from a non-activity class. Some suggest to use context.MODE_PRIVATE, but I wanted to avoid such dependency of passing a context from every activity that I want to use the DB.

What is the best way to have only one DB connection and DB handling in one class across all activities?

Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103

1 Answers1

2

Do you access your SQLiteDatabase through a singleton?

private static DatabaseHelper sInstance = null;

public static synchronized DatabaseHelper getInstance(Context context) {

    if (sInstance == null) {
        sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
 }

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

If so, then the above still requires a Context argument, but if you're averse to passing one around then you can use this technique:

public class App extends Application {

    private static App instance;

    public static App get() { 
        return instance; 
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

So you could access your database with DatabaseHelper.getInstance(App.get());

Community
  • 1
  • 1
PPartisan
  • 8,173
  • 4
  • 29
  • 48