Search code examples
androidglobal-variables

Android - My Global Variable values return null after switching Application


I am Using GlobalVariable file to hold data during my entire application, but what happens is it returns null value if i switch to another application and returns back.

below is my code :

In Manifest :

 <application
    ..
    android:name=".MyApplication" >

For Class of global variables :

public class MyApplication extends Application {
public int rowId = 0;
}

inside the activities

int mRowId = ((MyApplication) getApplicationContext()).rowId;

Solution

  • you need to make it static and final but use it with getters and setters only.

    Something like the following

     public class MyApplication extends Application {
    
    
     public final static int rowId = 0;
    

    dont forget your initializing and setters and getters please :

     int rowId;
    
    public int getRowId() {
        return rowId;
    }
    
    public void setRowId(int rowId) {
        this.rowId = rowId;
    }
    

    to set the values from outside the class, something like:

      MyApplication.rowId =  //whatever returns int
    

    to get the values from outside/inside the class, something like:

      int TempInt = MyApplication.rowId; // TempInt will have the value of rowId
    

    check What are setters and getters : https://dzone.com/articles/why-should-i-write-getters-and-setters