Why can't I store data in an Android Application object?

Source: Internet
Author: User

In an app there's always some data that needs to be used in multiple places. The data can be a session token, a time-consuming calculation, and so on. Typically, to avoid the overhead of passing objects between the activity, the data is generally stored in persistent storage.

It is suggested that this data be saved to the Application object so that the data is available to all activities within the application. This method is simple, elegant and ... It's totally nonsense.

Assuming your data is stored in the Application object, your application will end up with a NullPointerException exception crash.

A simple test caseCode

Application object:

 for brevity class MyApplication extends Application {     String  name;      String GetName () {        return  name;    }     void SetName (String  name) {        = name;    }}

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

//access modifiers omitted  brevity  class   Whatisyournameactivity extends        Activity {void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);         Setcontentview (r.layout.writing); //Just assume that in   The real app we would        Really Ask It!        MyApplication app  = (MyApplication) getapplication (); App.setname (  developer Phil  Span style= "color: #800000;"        > " ); StartActivity ( new   Intent (this,     Greetloudlyactivity.class)); } }

second activity, We call the first activity setting and the name of the user inside the application:

 for brevity class Greetloudlyactivity extends Activity {     TextView TextView;     void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);         Setcontentview (r.layout.reading);         = (TextView) Findviewbyid (r.id.message);    }     void Onresume () {        super.onresume ();          = (MyApplication) getapplication ();        Textview.settext ("" + App.getname (). toUpperCase ());}    }
Test Scenario
  1. The user launches the app.
  2. Inside the whatisyournameactivity, users are asked to enter their names and store them in MyApplication.
  3. In Greetloudlyactivity, you get the user name from the MyApplication object and display it.
  4. The user presses the home key to leave the app.
  5. A few hours later, the Android system killed the app in order to reclaim memory. So far, everything is still fine. Next up is the crash part ...
  6. The user opens the app again.
  7. The Android system creates a new MyApplication instance and restores the greetloudlyactivity.
  8. Greetloudlyactivity gets the user's name from the new MyApplication instance, can be empty, and eventually leads to NullPointerException.
why would crash?

In the above example, the app will crash because the Application object is completely new, so the value inside the name variable is NULL, when the call to String#touppercase () Method results in NullPointerException.

The core of the whole problem is that the Application object will not stay in memory, it will be killed. What's different from the general view is that the app doesn't actually start again. The Android system creates a new Application object, and then initiates the activity from the last user's departure, causing the app to never be killed.

You think your application can save the data, but you didn't expect your users to open activity B without opening activity A, so you get a crash surprise.

What are the alternative methods?

There is no magic solution here, you can try the following methods:

    • Pass data directly to the Activity via intent.
    • Persist data to disk using several methods that are officially recommended.
    • The value of the variable is always checked for non-null when working with the data.
    • Local data protection, in-depth protection of the APK app's network cache, local storage data.
If the simulation app is killed

Update: Daniel Lew points out that the easiest way to kill an app is to use the "stop process" inside DDMS. You can use this trick when debugging your app.

To test this, you have to use an Android emulator or a root Android phone.

  1. Use the home button to exit the app.
  2. in the terminal:
    # Find the process idadbShellps# ThenFind the Line withThe package name ofyour app # Mac/unix:save some time byusinggrep:adbShellPS | grep your.app.package # The result should look like:# USER PID PPID vsize RSS Wchan PC N ame# u0_a19821997  the   827940 22064Ffffffff00000000S Your.app.package #KillThe app by PidadbShell Kill-9 21997# the App isNow killed
  3. Press and hold the home button to return to the previous app.
    You are now out of a new application instance.
Summary

Don't store data in application objects, which can be error-prone and cause your app to crash.
Either save the data you want to use behind the disk or save it to the intent extra and pass it directly to the activity.

These conclusions are not only useful for application objects, but also for the Singleton Objects (singleton) or public static variables in your app.

Why can't I store data in an Android Application object?

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.