This is a problem that is puzzling me and I wanted to get answers.
We have extended the Application and the class has variables that are to be accessed from different areas of the app. I think this was done to get a singleton implementation. The application has member objects of different classes.
public class DataApplication extends Application{
public InfoHelper mInfoHelper;
public void setHelper (InfoHelper infoHelper) {
mInfoHelper = infoHelper;
}
public InfoHelper getInfoHelper() {
if (mInfoHelper == null){
mInfoHelper = new InfoHelper();
}
return mInfoHelper;
}
// the InfoHelper class
public class InfoHelper{
public int trial = 10;
}
Now in an AsyncTask (which is started from an Activity A) updates the value of trial
variable like this,
mDataApplication = (DataApplication) ((FragmentActivity)context).getApplication();
InfoHelper infoHelper = mDataApplication.getInfoHelper();
infoHelper.trial = 200;
when the AsyncTask is done, inside the Activity-A, I check the value of the trial
variable using and InfoHelper variable that was created before calling the AsycTask,
// The below is created in onCreate() of Activiy-A, before the AsyncTask is started.
mInfoHelper = mScanApplication.getInfoHelper();
// After the Asyctask is done I would check the value of trial.
Log.d(TAG, "Test Value 1 --- "+ mInfoHelper.trial);
Log.d(TAG, "Test Value 2--- "+ mDataApplication.getInfoHelper().trial);
the result is, Test Value 1 --- 10 Test Value 2--- 200
I was expecting the first result from the first Log statement but I did not expect the second log statement to get me the updated result. How did that happen? When updating in the AsyncTask, I created an object of InfoHelper and updated that object. How come it reflected everywhere. My friends said that it was because it was the same reference of the object and it does not matter if we create an object of the InfoHelper as it is the same memory location, if that is true then the question would be why the first Log statement showed me the old value?
My fundamentals are weak in this area and I appreciate may help in my quest to become better.
Note: If I create the mInfoHelper object again right before printing it I have the updated value which I was expecting to happen.
mInfoHelper = mScanApplication.getInfoHelper();
Log.d(TAG, "Test Value 1 --- "+ mInfoHelper.trial);
the result is, Test Value 1 --- 200