Hey. I have a question about passing an object throughout the application. Let's say I want to have a large user object throughout the application. This object will be used by several actions and services. I did it first.
First, I created the Application class and defined a singleton object.
public class FooApplication extends Application { public static SharedObj obj; ... }
Secondly, in activity I set the value of this object
public class FooActivity extends Activity { OnCreate() { FooApplication.obj = SharedObj.getInstance(); } }
Thirdly, in another action I refer to this object
public class BarActivity extends Activity { OnCreate() { SharedObj useThis = FooApplication.obj; } }
My question is, what's wrong with that? It seems to be working fine, but I found that sometimes the value of this singleton is null for some reason. The main reason I am sharing this object like this, instead of making it understandable, is that it is very expensive for me and what I did looks very easy. Is there a flaw?
After some research that I found, there is another way to share an object throughout the application.
First define in the application class
public class FooApplication extends Application { public SharedObj obj = new SharedObj(); ... }
Secondly, initialize as
public class FooActivity extends Activity { OnCreate() { FooApplication fooApp = (FooApplication)getApplicationContext(); fooApp.obj = new SharedObj(); } }
Thirdly, in another action I refer to this object
public class BarActivity extends Activity { OnCreate() { SharedObj useThis = ((FooApplication)getApplicationContext()).obj; } }
How is this method (using the getapplicationContext () method) different from using a singleton object, as it was in the first section? Is this more recommended?
Thanks in advance!