pheromix
pheromix

Reputation: 19327

Should the context of SQLiteOpenHelper always be the running activity?

I want to open the database once only from the main screen of my app , and I want to use this instance anywhere in any activity. Is that possible or should I make the context to be each actual opened activity so that I must create an instance of the database ( open ) in every activity ?

Upvotes: 1

Views: 39

Answers (2)

Blackbelt
Blackbelt

Reputation: 157457

Is that possible or should I make the context to be each actual opened activity so that I must create an instance of the database ( open ) in every activity ?

it is possible, and you could use the application context. Your DBHelper could be a singleton. E.g

public class DBHelper extends SQLiteOpenHelper { 

  private static DBHelper sInstance;
  public static synchronized DBHelper getInstance(Context context) {    
    if (sInstance == null) {
       sInstance = new DBHelper(context.getApplicationContext());
    }
    return sInstance;
  }

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

}

Upvotes: 3

Vaiden
Vaiden

Reputation: 16122

You do not need to close and re-open the SQL connection per each individual Activity.

Having said that - it is best to open the connection using an app context, to avoid Activity leaks.

You can get an app context refrence quite easily.

Upvotes: 3

Related Questions