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 ?
            Asked
            
        
        
            Active
            
        
            Viewed 36 times
        
    1
            
            
         
    
    
        pheromix
        
- 18,213
- 29
- 88
- 158
- 
                    Do this from Service or Application subclass (ApplicationContext), that way, you'll have the connection and lock/synchronisation available in any Activity – Marek Sebera Apr 25 '15 at 11:30
- 
                    can you explain more clearly ? – pheromix Apr 25 '15 at 11:31
2 Answers
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.
 
    