Never store data in application objects

Source: Internet
Author: User
Tags modifiers

Translation: http://www.developerphil.com/dont-store-data-in-the-application-object/

Never store data in application objects May 5, 2013

In our applicationsProgramSome data needs to be used in multiple places. It may be a session token. It takes a lot of money to get the result, and so on. In addition, we always want to avoid passing data between two activities or not storing the data in persistent storage.
A solution is to store the data in the Application Object of the application, so that the stored data can be shared among all the activities. This solution looks simple and elegant, but it is actually wrong!
If you always believe that the data will remain in the Application object, your application will end with an nullpointerexception.
A simple test case

The application object:

 

 
// Access modifiers omitted for brevityclassmyapplication extends application {string name; string getname () {returnname;} voidsetname (string name) {This. Name = Name ;}}

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

 

 

// Access modifiers omitted for brevityclasswhatisyournameactivity extends activity {voidoncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. writing); // just assume that in the real app we wocould really ask it! Myapplication APP = (myapplication) getapplication (); app. setname ("Developer Phil"); startactivity (newintent (this, greetloudlyactivity. Class ));}}

 

The second activity, where we shout the name of the user:

 

 
// Access modifiers omitted for brevityclassgreetloudlyactivity extends activity {textview; voidoncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. reading); textview = (textview) findviewbyid (R. id. message);} voidonresume () {super. onresume (); myapplication APP = (myapplication) getapplication (); textview. settext ("hello" + app. getname (). touppercase ());}}

 

Possible scenarios for users to use your application

 

1. the user opens your application 2. In whatisyournameactivity, you store the user name in the myapplication object. 3. In greetloudlyactivity, you extract the user name from the myapplication object and display it to the user. 4. the user presses the Home Key to exit your application. 5. In a few hours, Android may silently kill your application in the background and release the memory for other applications. So far, no problems have occurred, and no exceptions have occurred to your application. 6. the user re-opened your application 7. Android will recreate a myapplication object and restore greeloudlyactivity. 8. greetloudlyactivity obtains the user's name, but the username is already null. Your application throws nullpointerexception and ends abnormally.

 

Why does it end abnormally?

 

In the example program, because the application object is newly created, the name attribute is null and calls
String # touppercase ()
Cause nullpointerexception

 

Core of the problem: the application object will not always exist in the memory and may be recycled and killed. The general idea is that applications will not be restarted from scratch. Android will create a new application object and restore the previous activity. It gives the user the illusion that the application will never be killed and remains in the original state.

 

This means that if you expect that the user will not open Activity B before opening activity A, the data will always be in the Application object. Then you will be pleasantly surprised by the exceptional termination!

 

 

Solution

 

There is no good solution here, but you can follow the following guidelines:
1. Use intent to clearly transfer data between activities
2. Use
One of gateways is used to store data on disks.
3. always perform null-check manually

How to simulate application killing
Edit:Daniel LewIt is pointed out that the simplest method is to use the "Stop process" function in ddms to kill an application (the device is in debug mode)

 

To test this, you must have a simulator or a root-user mobile phone.
1. Use the Home Key to exit your application.
2. input the following command in the command line:

 

# Find the process idadb shell PS # Then find the line with the package name of your app # MAC/Unix: save some time by using grep: ADB shell PS | grep your. app. package # The result shocould look like: # user PID ppid vsize RSS wchan PC name # u0_a198 21997 160 827940 22064 ffffffff 00000000 s your. app. package # Kill the app by pidadb Shell kill-9 21997 # the app is now killed

 

 

3. Use the task switching function to return to your application. Now, your application creates a new application object.

Summary

 

 

Data stored in the Application object is prone to errors, causing your application to terminate abnormally. If the data will be used later, you can store the data on the disk or through
Intent's extras is passed to the desired activity In addition, it should be noted that this is the case for the Application object, so it is true for any singleton object or static attribute.

 

Note: The test result is as described by the author.

 

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.