Exchange objects between actions in Android

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!

+5
source share
1 answer

The main drawback of this approach is the fact that the Android system can kill your process at any given time . This is usually done when the memory is needed for other purposes (for example, for an incoming phone call). Then Android starts your process again and re-creates each action (when the activity becomes visible). At the same time, it will call each onCreate method, passing it a packet of parsed data stored in activity.

The application class will also be recreated. However, the object you saved will not be recreated.

Thus, no matter how painful it may be, parcelization ensures that your object can resort to the state in which it was when the activity (and the process) was killed.

Another approach would be to save the object yourself. Using SharedPreferences is one general approach.

====

So, I suggest transferring an object from activity to action through Intent. The goal that is used to launch the action is always fully restored when this activity is recreated, even in the case of the kill / restart process.

+9
source

Source: https://habr.com/ru/post/1212215/


All Articles