Save global variables in Android
Sometimes our app needs to save some variable values for programs to call anywhere, so we will use the Save method of global variables. Here we will introduce two methods for your reference.
1: use application to save global variables
1.1 define an AppContext class to inherit from Application
Package com. example. demo_001.app; import java. util. hashMap; import java. util. map; import com. example. demo_001.User; import android. app. application;/*** Creation Time: 3:09:27 * Project name: Demo_001 * @ author Xu zhuyun * @ version 1.0 * @ since JDK 1.6.0 _ 21 * file name: AppContext. java * class description: */public class AppContext extends Application {private String B; // Save the String private User user; // Save the User object private Map innerMap = new HashMap (); // save Map-type data public void onCreate () {// initialize String B = Arthur inking;} public String getB () {return B;} public void setB (String B) {this. B = B;} public User getUser () {return user;} public void setUser (User user) {this. user = user;} public Map getInnerMap () {return innerMap;} public void setInnerMap (Map innerMap) {this. innerMap = innerMap ;}}
1.2 declare application in manifest. xml
android:name=com.example.demo_001.app.AppContext android:theme=@style/AppTheme >
1.3 assign values to global variables and their values in the program
@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // value final AppContext app = (AppContext) getApplication (); // value the app to the string. setB (hello, world); // assign User user = new User (); user to the User object. setAge (25); user. setName (Arthur inking); app. setUser (user); // assign an app to the Map object. addParam (company, alibaba); // value: String str = app. getB (); User user2 = app. getUser (); String company = (String) app. getParam (company );}
2. Use a common class to save global variables
2.1 define a class
public class Data{private static String a =feiyangxiaomi;public static String getA() {return a;}public static void setA(String a) {Data.a = a;}}
2.2 values and values
Call the corresponding set and get methods.
Both methods pass the test. We recommend that you use the first method.