Shadab Khan Shadab Khan - 1 year ago 146
Android Question

How to set values globally in android

How to set values globally so that i can access from any activity or fragment.

For eg : > user_id need to store globally so every time any section which depends on user_id, checking and pulling data from backend will be easy instead of passing through activity (intent)

Edit :
i do need setter and getter from fragment or activtiy.

Answer Source

you can extend the base class and add member variables like so:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;

In your android manifest you must declare the class implementing (add the android:name=".MyApplication" attribute to the existing application tag):


Then in your activities you can get and set the variable like so:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download