Hi I have a question about passing an object throughout the app. Say I want to have a big custom object throughout the app. This object will be used by multiple activities and services. What I did at first is this.
First, I created an Application class and define a singleton object.
public class FooApplication extends Application {
public static SharedObj obj;
...
}
Second, in an activity I set a value of this object
public class FooActivity extends Activity {
OnCreate() {
FooApplication.obj = SharedObj.getInstance();
}
}
Third, in another activity I access this object
public class BarActivity extends Activity {
OnCreate() {
SharedObj useThis = FooApplication.obj;
}
}
My question is, what is wrong with this? It seems to work fine but I find that sometimes the value of this singleton object is set to null for some reason. The primary reason I am sharing this object like this instead of making it parcelable is that doing so is kinda expensive for me and what I did looks much easy to do. Is there a downside?
After some research I found there is another way to share an object throughout the app.
First, define in app class
public class FooApplication extends Application {
public SharedObj obj = new SharedObj();
...
}
Second, initialize in an activity like this
public class FooActivity extends Activity {
OnCreate() {
FooApplication fooApp = (FooApplication)getApplicationContext();
fooApp.obj = new SharedObj();
}
}
Third, in another activity I access this object
public class BarActivity extends Activity {
OnCreate() {
SharedObj useThis = ((FooApplication)getApplicationContext()).obj;
}
}
How is this method (using getapplicationContext()) different from using a singleton object like I did in the first section? Is this more recommended?
Thanks in advance!