Android saves global variables

Source: Internet
Author: User

Data needs to be shared among multiple activities or services

1. Custom Application

JavaCode

 
Public class demoapplication extends application {private hashmap <string, Object> map = new hashmap <string, Object> (); Public void put (string key, object) {map. put (Key, object);} public object get (string key) {return map. get (key );}}

2. Modify the androidmanifest. xml file:

XML Code

 
<ApplicationAndroid: Name = "demoapplication"Android: icon = "@ drawable/APP" Android: Label = "@ string/app_name">

Pay attention to the content marked in bold and black, specifyProgramUse our own defined application.

3. Usage:

In one activity, save the data to the map defined in the application.

Java code

 
Demoapplication APP = (demoapplication) getapplication (); app. Put ("key", "this is a test! ");

Then retrieve data in another activity:

Java code

 
Demoapplication APP = (demoapplication) getapplication (); string value = (string) app. get ("key"); toast. maketext (this, value, toast. length_long ). show ();

Note: concurrency is not considered here. If necessary, you can add the relevant synchronization code in the Custom Application for implementation.

Related Article

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.