How and where store persistent objects (like db adapters) in AppWidgetProvider?

634 views Asked by At

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

1

There are 1 answers

1
CommonsWare On BEST ANSWER

The biggest problem for me is, how (and where) to store the instance of my DBAdapter.

Pro tip: do not end classes with Adapter when they do not inherit from android.widget.Adapter.

I don't want to create every time new Instance of DBAdapter.

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. A DBAdapter "with simple methods (add, remove, get records...)" should be extremely cheap to instantiate.

another option is use Gson to store DBAdapter to sharedPreferences, or maybe use serialization

That makes no sense. The only data of value in a DBAdapter should be the SQLiteOpenHelper (or SQLiteDatabase from some other source), which cannot itself be persisted. Moreover, this will be probably ~1000x slower than just creating a new instance of DBAdapter.