Do not save data in application

Source: Internet
Author: User

Introduction:

There is always a need for some information in many places in your application. It can be a session, the result of an expensive calculation, etc., it is usually tempting to let you avoid the overhead of passing objects between activity or keeping those in persistent storage.

Sometimes it is recommended that this mode, which will be available in all activity of the Application object. This solution is simple and elegant ... Then this pattern is completely wrong.

If you think your data will be put there, then your application will eventually crash with a NullPointerException exception

A simple case:

The Application object:

Class MyApplication extends Application {    String name;    String GetName () {        return name;    }    void SetName (String name) {        this.name = name;    }}

The first activity, where we store the user's name in the Application object:

Class Whatisyournameactivity extends Activity {    void onCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);        Setcontentview (r.layout.writing);        MyApplication app = (myapplication) getapplication ();        App.setname ("Developer Phil");        StartActivity (New Intent (this, greetloudlyactivity.class));}    }

The second activity, we read the user's name

Class Greetloudlyactivity extends Activity {    TextView TextView;    void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.reading);        TextView = (TextView) Findviewbyid (r.id.message);    }    void Onresume () {        super.onresume ();        MyApplication app = (myapplication) getapplication ();        Textview.settext ("HELLO" + app.getname (). toUpperCase ());}    }
Operation Flow:

1. Turn on the Application object

2. In whatisyournameactivity you save a user name and save it to the Application object

3. In greetloudlyactivity you read the user name and show it

4. Use the home key to leave the program

5. After a while, Android will quietly kill the program to reclaim memory

So far, everything is fine!

There's going to be an accident.

6. The user re-opens the application

7.Android creates a new instance of MyApplication and restores the greetloudlyactivity

8.GreetLoudlyActivity Gets the user name, but is now NULL, the program crashes and runs out of a NullPointerException exception

Why did you have this accident?

In this case. The program crashes unexpectedly because application is a completely new object, so we get the name variable is null, so when we call String#touppercase () it causes the program to throw the NullPointerException exception

This brings us to the core of the problem: application will not stay forever, it will be killed. This program will not revert to its original state. Android will recreate a application object for the program and activate the activity to give the user a application that has never been killed.

This means that. If only your users do not want to open an activity B in activity A, save some data to application. Then you will get such an unexpected surprise (NPE)

So what's the solution?

There is no magic solution here, you can do one of the following:

1. Clear data transfer through intent to activity

2. Persisting data to disk

3. Always do non-empty checks and make corresponding processing

How to simulate application being killed?

An easy way to kill your application in Ddms, using the "Stop Process" feature (Red Stop icon)

In order to simulate this phenomenon. You have to use the simulator or use a root phone

1. Use the home button to exit your program

2. In the terminal:

# Find your process idadb Shell ps# Find your application's package name # Mac/unix:save some time by using GREP:ADB Shell PS | grep your.app.package# Find results as follows # USER      PID   PPID  vsize  RSS     wchan    PC         name# u0_a198   21997   827940 22064 ffffffff 00000000 S your.app.package# by PID kill the application you want to kill adb shell kill-9 21997# This program was killed

3. Now use the task to switch back to the application. So now is a new application example.

Summarize:

Saving data in your Application object is error-prone. And it will crash your program. Best of all, you should save your global data to disk or explicitly pass intent extras to the activity

 

  

Do not save data in application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.