4

I have a DBHelper class set up as a singleton:

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);
        databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
    }
}

I have a MainActivity and a number of fragments. Many of these fragments need access to my DBHelper methods

Should I be using dbHelper = DBHelper.getInstance(getApplicationContext()) in every fragment that needs database access? Instantiation will only happen once due to the singleton pattern, so I don't need to worry about the class being instantiated in every single fragment with that code

Or is it better to instantiate the DBHelper in MainActivity only, and then in any fragment that needs database access get a reference to the mainactivity and call the object methods from there? Something like this in each fragment:

mainActivity = (MainActivity) getActivity();
mainActivity.dbHelper.insertData();
Simon
  • 9,762
  • 15
  • 62
  • 119

3 Answers3

2

Since you are sure Singleton will be instantiated in MainActivity the first approach shouldn't have any problems, you could even call getInstance(null) in your fragments

loukaspd
  • 90
  • 7
1

I think the most prodcutive decision will be create custom fragment class, extend it your fragment or v4.fragment, initialise in it dbHelper and use your custom fragment in your activity. it is my humble opinion :)

Scrobot
  • 1,911
  • 3
  • 19
  • 36
1

Codes here is one simple way to resolve concurrent problem in singleton pattern.

public DBHelper extends SQLiteOpenHelper {
    // declare private constructor
    // some public method

    public static class Wrapper {
        private static DBHelper dbHelper;
        public static void init(Context ctx, Object otherArgs) {
            // init DBHelper
            dbHelper = new DBHelper(ctx, otherArgs);
        }
        public static DBHelper get(){
            return dbHelper;
        }
    }
}

In custom Application

public MyApp extends Application{
    void onCreate(){
        DBHelper.Wrpper.init(this, otherArgs);
    }
}

Code like this where DBHelper is needed:

DBHelper.Wrapper.get().insertData();
grantonzhuang
  • 557
  • 4
  • 6