1

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 ?

pheromix
  • 18,213
  • 29
  • 88
  • 158

2 Answers2

3

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);
  }

}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
3

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.

Community
  • 1
  • 1
Vaiden
  • 15,728
  • 7
  • 61
  • 91