Solution to sharing data between different android activities

Source: Internet
Author: User

I recently had a local area network socket connection problem. To share a socket connection between multiple activities, I searched the internet for information. I still feel that the application method is easy to use. I will post it and share it with you!
In Android, variables are transmitted in different activities. Generally, you can use the Bundle in Intent to add variables.
When saving parameters: Copy codeThe Code is as follows: Intent intent = new Intent ();
Intent. setClass (A. this, B. class );
Bundle bundle = new Bundle ();
Bundle. putString ("name", "xiaozhu ");
Intent. putExtras (bundle );
StartActivity (intent );

Read parameters:Copy codeThe Code is as follows: Intent intent = this. getIntent ();
Bundle bundle = intent. getExtras ();
String name = bundle. getString ("name ");
[Java] view plaincopy
Intent intent = this. getIntent ();
Bundle bundle = intent. getExtras ();
String name = bundle. getString ("name ");

However, when the same variable is often used in multiple activities, it is troublesome to use Bundle. You need to set it once each time you call the Activity.
To use it in the entire Application, static variables are generally used in java, while the more elegant method in android is Application context.
Create a new class that inherits from the ApplicationCopy codeThe Code is as follows: class MyApp extends Application {
Private String myState;
Public String getState (){
Return myState;
}
Public void setState (String s ){
MyState = s;
}
}

Add the name attribute to the AndroidManifest. xml application, as shown below:Copy codeThe Code is as follows: <application android: name = ". MyApp" android: icon = "@ drawable/icon" android: label = "@ string/app_name">

Use Time:Copy codeThe Code is as follows: class Blah extends Activity {
@ Override
Public void onCreate (Bundle B ){
...
MyApp appState = (MyApp) getApplicationContext ());
String state = appState. getState ();
...
}
}

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.