Reputation: 5792
I wanted to know what is the best approach for sharing singleton in my android app. I have a few activities that does not rely on each other, but I want them to have a singleton that they can all read/write.
Where should I place it?
Thanks
Upvotes: 2
Views: 2330
Reputation: 38168
Your application should be a singleton. It avoids many other problem related to sharing datas or models.
In your manifest.xml :
<application android:icon="@drawable/icon"
android:label="@string/app_name" android:debuggable="false"
android:name="<class of your application see below>"
android:launchMode="singleTop">
..... all activities/services/receivers/etc... as usual
</application>
And your android:name refers to this class :
public class MyApp extends Application {
//singleton, but use onCreate more than constructor to build shared resources.
....
}//class
And then, from within any activity, you can retrieve your singleton to get shared resources by doing this :
((MyApp)getApplicationContext()).getSharedResources()....
or
MyApp.getInstance().getSharedResources()....
Having a singleton as a app is a usual design pattern in android, it is especially useful to handle device rotation (as it tends to destroy activities and recreate them) as it provides a stable entity to persist during app lifecycle.
Upvotes: 8