Reputation: 1108
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?
Upvotes: 0
Views: 1224
Reputation: 3502
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.
Upvotes: 2
Reputation: 328
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.
Upvotes: 1