Android / Java: accessing a single DBite SQLite object from multiple actions

I have a central database in my application that needs to be accessed by several different activities.

Should I share this object by making it static? As, for example, in the activity that initializes the database, I do this:

protected static appDatabase db; 

Then others can access it through FirstActivity.db .

Another option is to create private appDatabase db objects in every action that he needs, but I suspect that opening multiple db objects to access the same stored data can be wasteful.

However, I am not too keen on java, so I ask - what is the preferred way to do this and why?

thanks

+7
source share
2 answers

You can use singleton as follows:

  private static DataHelper singleton; public static DataHelper getDataHelper(Context context) { if (singleton == null) { singleton = new DataHelper(context); OpenHelper openHelper = new OpenHelper(singleton.context); singleton.db = openHelper.getWritableDatabase(); } if(!singleton.db.isOpen()){ OpenHelper openHelper = new OpenHelper(singleton.context); singleton.db = openHelper.getWritableDatabase(); } singleton.context = context; return singleton; } private DataHelper(Context context) { this.context = context; } 

And name your singleton class as follows:

 public DataHelper dh; this.dh = DataHelper.getDataHelper(this); 
+4
source

I handle this situation using the Application class and synchronized management of database objects. Here is an example. The [synchronized] qualifier is the key in a multi-threaded application.

By definition, an Application object is a Singleton in Android.

 public class App extends Application { private static App _instance; private AppLocalStorage _localStorage; @Override public void onCreate() { super.onCreate(); _instance = this; } public static App getInstance() { //Exposes a mechanism to get an instance of the //custom application object. return _instance; } public synchronized AppLocalStorage getDatabase() { if (_localStorage == null) { _localStorage = new AppLocalStorage(this); } return _localStorage; } 

}

+1
source

All Articles