I'm developing home screen widget, and I'm using android sqlite database. I implemented a simple class DBAdapter
with simple methods (add, remove, get records...) to handle database work. It works, but now I'm thinking about the best way how to do that.
The biggest problem for me is, how (and where) to store the instance of my DBAdapter. If I used Activity, it would be very simple - i will create instance of my DBAdapter in onCreate
method and everything is fine. But now I don't have such option, as I'm using AppWidgetProvider
and few IntentServices
. AppWidgetProvider
(BroadcastReceiver) lives only certain time - during the execution of onReceive
method. IntentService
also "ends" after finishing necessary work. So how and where to store the instance of my DBAdapter? I don't want to create every time new Instance of DBAdapter.
I was thinking about this options: make DBAdapter singleton clas or use static class & methods, another option is use Gson to store DBAdapter to sharedPreferences, or maybe use serialization. But I would rather ask. Whats the right way to do this? Thx a lot
Pro tip: do not end classes with
Adapter
when they do not inherit fromandroid.widget.Adapter
.You are welcome to make it a singleton/static data member. However, once your process terminates, it will go away, and you will need to create a new one again anyway. Hence, I recommend that you simply create the instance as needed in your
IntentService
. ADBAdapter
"with simple methods (add, remove, get records...)" should be extremely cheap to instantiate.That makes no sense. The only data of value in a
DBAdapter
should be theSQLiteOpenHelper
(orSQLiteDatabase
from some other source), which cannot itself be persisted. Moreover, this will be probably ~1000x slower than just creating a new instance ofDBAdapter
.