Watch out for using static variables in Android Development

Source: Internet
Author: User

 

As we all know, there are many advantages of static variables: they can save global data. However, this may cause hidden bugs.

Situation:


I have my personal experience when developing a project. The following BUG was found for a long time. A project developed by multiple people. A colleague used static to pre-Cache some list data for the next interface. This data saves some image references, and these images are saved separately in another list, but the images are Recycle when they exit the program.

 


Symptom:

Occasionally, the recycled images are used in the program.

Java. lang. RuntimeException: Canvas: trying to use a recycled bitmap android. graphics. Bitmap

 


Analysis:

Due to the Android architecture design, static data is not cleared immediately when the program exits. In the above case, it can be found that when loading network data in advance is slow, and then enter the next interface, it is found that the static variable has data. At this time, this data is the data when the program exits, but the image referenced by this data has been recycled. This causes the previous phenomenon.

 


Solution:

When you exit the program, the data in the static variable is cleared.

 


Suggestion:

In the development process, try to use less static data, and try to concentrate static variables in a class. (For reference only)

 


Extension:

When Android exits the program, it does not verify that static data is cleared immediately.


Public class TestStatic {
Private static int nValue = 0;
Static {
NValue ++ = 100;
}

Public TestStatic (){
NValue ++ = 300;
Log. I ("TestStatic", "nValue:" + nValue );
}

}

 


Result:

05-09 11:15:04. 589: I/TestStatic (8093): nValue: 400
05-09 11:15:08. 309: I/TestStatic (8093): nValue: 700

 


When the program is started for the first time, the static code is executed before TestStatic ();

When you enter the program for the second time, directly execute TestStatic () and skip the static code;

 

 

 

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.