简体   繁体   中英

Android simple method to create and use global variables?

I'm coming up short when trying to locate a simple method to implement a global variable into my app (an array of Java classes that I plan to use in a couple of activities). I saw one method that looked as though it made sense and was easy to implement. It involved creating a new Java Class; fill it with whatever; and insert it into the manifest <application android:name="app.com.new.GlobalVariables"... . But it says that the class is not assignable to application.

I've attempted some other methods, but to no avail. Similar to C++, isn't there a way to "include" a class(or global variables) into the entire Android app?

Create a class which is extended Application

public class GlobalClass extends Application{

private String name;
public String getName() {
return name;
}

public void setName(String Name) {

   name = Name;

}}

Later register it in manifest file

<application
    android:name="com.example.globalvariable.GlobalClass"

How to use it

 GlobalClass globalVariable = (GlobalClass) getApplicationContext();
    globalVariable.setName("Name here");
    String name  = globalVariable.getName();

Thats it.

You can use the singleton design pattern to make a new class that stores all the data you wish to keep across all your activities.

http://en.wikipedia.org/wiki/Singleton_pattern

Essentially you create a class that only contains a get method. The method creates an instance of an object if there is none or just returns the object if it has been previously instantiated. you can just call the method in each activity to get the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM