Problem:
I'm saving some data in a singleton class... Sometimes it happens, that this singleton returns null data, from which I derive, that it was destroyed...
My idea/thoughts:
Actually, I thought, the singleton will live as long as the application lives and as long as the application remembers anything else like fragments state for example, my singleton will exist with it's last data too. Isn't this correct?
concrete problem:
My case is following: I go from my main fragment to a sub fragment and save an selected object in my singleton... I stop using my app and come back after some time. My app remembers it's state and recreates the fragments, my fragment want to get the selected object from my singleton and get's null.
I thought, a singleton should exist as long as the application exists and therefore needs no saving... Whenever the application is ended, nothing will be restored anyway and my app won't remember anything, so that's ok anyway. Is that a wrong assumption?
I need an answer to this question, because if I'm sure, that above thoughts are correct, I at least know, that I have to search for the problem somewhere else...
Here is a short summury of what I've found out (or have had forgotten)
Activitys can be recreated, although the application was destroyed
Singletons can be garbage collected if not referenzed from somewhere
So you HAVE TO SAVE your singletons! Otherwise, whenever your phone is on low memory, it may kill the application and create a NEW application, but RECREATE the activities...
For me, as I'm actually always use a single activity with fragments, it is easy to solve the problem:
when I create an activity, I call a static restore function (BEFORE calling get!!!)
in the onSaveInstanceState of the activity a always save the singleton to the bundle
=> so my singleton looks like following (base structure)
public class DataCache implements Parcelable
{
private static final String TAG = DataCache.class.getName();
private static DataCache mCache = null;
public static synchronized final DataCache get()
{
if (mCache == null)
mCache = new DataCache();
return mCache;
}
private DataCache()
{
// init...
}
public void save(Bundle outState)
{
outState.putParcelable(TAG, this);
}
public static void restore(Bundle savedInstanceState)
{
if (savedInstanceState != null && savedInstanceState.containsKey(TAG))
{
// only restore, if necessary, i.e. if application was destroyed but activity saved our last cache
if (mCache == null)
mCache = savedInstanceState.getParcelable(TAG);
}
}
}
Related
I am building a menu from which the user can select items. They can edit their selections whenever necessary. The singleton would be a class containing the list of all selectable items. Whenever new activities are opened, the singleton would have the correct state of all items.
The reason I am asking this is because implementing Serializable creates a new instance (albeit almost identical) of the item.
Yes you could use a singleton for this. It would be something like:
public class MenuData {
private static MenuData instance;
private boolean isItemASelected;
public static MenuData getInstance() {
if (instance == null) {
instance = new MenuData();
}
return instance;
}
public boolean isItemASelected() {
return isItemASelected;
}
public void setItemASelected(boolean itemASelected) {
isItemASelected = itemASelected;
}
}
However I wouldn't recommend this. This data will only be around for as long as your Application is in memory. As soon as your app gets killed by Android all the variables will be cleared and the state will have been lost.
If your menu items are constant then I'd recommend using SharedPreferences to store the state. If they are dynamic then use the SQL database. This way the options are persisted even if your app gets killed.
I'm a beginner to android development, and I'm trying to write my code in an MVC pattern, but I'm having trouble understanding how a model would work. As far as I can tell every time you start a new activity with an intent you are not able to pass a model along with it. As far as i can tell you'd have to reinitialize it each time you start a new activity. Am I missing something? I looked into Parcelable, but it seems that you loose your methods if you make your model Parcelable. right now I'm building a log in system, which checks my local sqllite db on start up if the user has already logged in, and if so it passes to another activity, otherwise it passes to the log in activity, but I wan't to keep that user model alive through all the activities. Is thee a way to do that?
You might want to also consider keeping a static reference around to the model data that you want to share across activities so that you don't have to keep serializing/deserializing the model when switching between activities. You can get away with using Parcelable if your models are small, but at some point, performance may become an issue.
I'm working on a project where we keep the models in a Singleton that we can access throughout the app, and although I generally hate Singleton's for how they can make unit testing more difficult, I have found this approach to perform better with larger models than trying to rely on Android's serialization mechanism.
Here's is a very rough example of what I mean (disclaimer: I have not actually run tested this code, but I hope this illustrates the concept):
You might have a singleton class that I terribly called Models
public class Models {
private static Models instance;
private boolean isInitialized = false;
private User user;
private OtherInterestingModel otherInterestingModel;
private Models() {
}
public static synchronized Models getInstance() {
if (instance == null) {
instance = new Models();
}
return instance;
}
public void loadModels() {
if (!isInitialized) {
/*
* One-time model initialization here.
*/
isInitialized = true;
}
}
public User getUser() {
return user;
}
public OtherInterestingModel getOtherInterestingModel() {
return otherInterestingModel;
}
}
In your LoginActivity, you can initialize the Models class, say, in your onCreate():
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Models.getInstance().loadModels();
User user = Models.getInstance().getUser();
OtherInterestingModelData otherData = Models.getInstance().getOtherInterestingModel();
// Do something with the model data...
}
/*
* This might be called after the user enters data and clicks a login button...
*/
private void login() {
startActivity(new Intent(this, AwesomeLoggedInActivity.class));
}
}
Once the user successfully logs into your app, you could have basically the same code in your main activity:
public class AwesomeLoggedInActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Models.getInstance().loadModels();
User user = Models.getInstance().getUser();
OtherInterestingModelData otherData = Models.getInstance().getOtherInterestingModel();
// Do something with the model data...
}
}
Notice that by having a Singleton, you avoided having to serialize the model data by passing it through the intent that started the main activity.
Yes, you can do that with the Parcelable interface.
You do not lose your class's methods when you implement the Parcelable interface. The interface simply defines a method for writing your member variables to a Parcel object when you need to pass the object around.
Once you retrieve the data from your Intent via getParcelableExtra(), the object is recreated from the Parcel and you can once again treat it as an instance of whatever class it is.
For example, if you have a User class that extends Parcelable, you can bundle it with an Intent by calling putExtra("user", myUser). myUser is then (behind the scenes) packed into a Parcel and attached to the Intent. In your next Activity, you can retrieve that User object with User myUser = (User) getParcelableExtra("user");, and the Parcel will be unpacked and returned to you. You wil once again have a fully functioning User object.
I am trying to use a Singleton to share a large data object between Activities. But when I open the new Activity, the singleton comes up as empty. It seems to me that the Singleton should be the same no matter where in the Application I call if from.
It seems like the Scope of the Singleton is being limited to the individual Activity. Working around this is making my App very complicated. I must be doing something wrong. I even tried instantiating them in an extended Application class... Google says I should not have to use that though...
Can someone please point out where I am going wrong? i.e. Why does this singletom not contain the same data in each Activity?
I call it from an Activity with...
DataLog dataLog = DataLog.getInstance(this);
I have...
public class DataLog extends ArrayList<String> implements Serializable {
private static final long serialVersionUID = 0L;
private static DataLog sInstance;
private static Context mContext;
public static DataLog getInstance(Context context) {
mContext = context.getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
if (sInstance == null) {
sInstance = new DataLog();
}
return sInstance;
}
private DataLog() {
}
public boolean add(String entry) {
super.add(entry);
return true;
}
public void add(int index, String entry) {
if (index > 0)
super.add(index, entry);
else
super.add(entry);
}
public void clear() {
super.clear();
}
...
}
Its highly advisable to avoid singleton for sharing large data sets in android.
Singletons are used for short life-cycle objects.
Switch to SharedPrefferences, SQLite DB's or file storing. You are not the only to have experienced this behavior, and the reason lies in the nature of android Activities and the system itself(managing activities and its data).
Here is an example why singleton is bad for your case:
You stored important data in it. The user knows that he can close the app on home button to call someone or whatever)maybe someone called him when he was in your app), and that when he opens your app he will come back at the same place with everything in order. (this is expected behavior from users and android apps). The system can easily kill your process and all static variables in it for memory maintenance, app inactivity etc...result=data lost. Thus its not safe to use it.
I thought a singleton instance should not be garbage collected, however I maintained a singleton object, and mark it when it was initialized, like this:
private static LocalCache instance;
public LocalCache() {
// initialize objects......
}
public static LocalCache getInstance() {
if (instance == null) {
instance = new LocalCache();
Log.e("instance", "new");
}
return instance;
}
I found that this log appear more than once in my application.
More precisely, I have 5 fragments in a FragmentActivity. When I press home button to do some task and switch back to the activity, the singleton class seems to be reallocated. Is there thing wrong in my code? Or can I prevent the fragment being recreated?
I'm sure I didn't assign null to the instance.
#Override
protected void finalize() throws Throwable {
Log.e("finalize", "finalize");
}
I also override finalize() to observe when it was destroyed, but the log didn't appear before the second "new instance" log.
Is there thing wrong in my code?
Usually, for a singleton, you use synchronized and volatile for locking, to make sure that you do not allocate multiple instances due to parallel calls on multiple threads. Or, in your case, just use a static initializer, since your getInstance() does not take any parameters needed to instantiate your LocalCache.
However, more likely, the issue here is that your process was terminated. Once you are no longer in the foreground, your process can be terminated at any point. When your app runs again, a new process is created, and all static data members will initially be null.
I have a doubt about destruction of activities and objects.
While I attach & detach the activity from the AsyncTask I do not change the ArrayAdapter from the asynctask (see code). So, what I get is multiple activities being attached & detached (ought to orientation changes) and just one task running and modifying ONE adapter, which in turn is the one from the first activity that created the task. So, when I attach the task in the onCreate() I just set the adapter with the one which holds the task, which in turn has all the values processed (in the example just a dummie list of numbers).
How can this be possible? I thought that onDestroy() would erase the activity itself and its attributes, and therefore I would get a null pointer exception or something like that while trying to access the ArrayAdapter of the original activity from the AsynkTask, but the code below works!
private static class TestingTask extends AsyncTask<Void, Integer, Void> {
private TestingActivity mActivity; // extends ListActivity
private ArrayAdapter<String> mAdapter;
private boolean mIsFinished;
private TestingTask(Context activity) {
attach(activity);
mAdapter = (ArrayAdapter<String>)mActivity.getListAdapter();
mIsFinished = false;
}
private void attach(Context activity) {
mActivity = (TestingActivity)activity;
}
private void detach() {
mActivity = null;
}
protected Void doInBackground(Void... params) {
for (int i = 0; i < 100000; i++) {
publishProgress(i);
}
return null;
}
protected void onProgressUpdate(Integer... values) {
if (!isCancelled()) {
mAdapter.add(values[0].toString());
}
}
// ...
}
Is this because the task keeps an active reference to the ArrayAdapter object, and therefore it is not deleted? Or is it something else?
I also experienced another "similar case" in which I returned an Activity's attribute from onRetainNonConfigurationInstance() let's say A a, that had visibility over B b (which is another attribute of the Activity). Then, when trying to access b instance through a, there is no problem and I thought I would need a wrapper to hold the two instances (a and b), or else I would get an exception when trying to access b (which I do not actually save). I do not know if it is related width the previous case in which the objects that I supposed not to be available actually are there, maybe because of the active reference to them that causes no deletion?
Thank you!
I think I have found the answer to these questions and as I was wondering... it is related to the Garbage Collector and the use of strong references.
In Understanding weak references article it is said that:
if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don't want the garbage collector destroying objects you're working on, this is normally exactly what you want
In another article How Gargabe Collection works it is explained that:
if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
So, my conclusion is that:
In the first case: As I am setting activity to null in detach() there is no memory leak and all objects can be garbage collected unless the adapter, which has a strong reference. So, I understand that the activity and all other objects contained by it are deleted unless the adapter, this is what I actually want.
In the second case: As I am returning the container object (A a) in onRetainNonConfigurationInstance() and it has a strong reference to (B b), b instance is accessible too, because it can be reachable via a chain of strong references.
Hope this will be helpful. If anyone else wants to give his/her opinion it will be welcome!