Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android "Global Variables" Not Persisting

I have created a class that extends Application to store variables I want to access from multiple activities

public class MyApplication extends Application 
{
private String fbId, firstName;
private long expires;

@Override
public void onCreate() 
{
    super.onCreate();
}

public String getFbId() 
{
    return fbId;
}

public void setFbId(String fbId) 
{
    this.fbId = fbId;
}

public String getFirstName()
{
    return firstName;
}

public void setFirstName(String firstName) 
{
    this.firstName = firstName;
}

I am able to access these variables and set these variables the first time I am running the app. Once I quit out and restart the application it sets my values to null, any suggestions for why this may be happening?

like image 870
James Fazio Avatar asked Jan 28 '26 12:01

James Fazio


1 Answers

If you don't store your data in storage (that doesn't need to be a database, could be a flat file, SharedPreferences, or whatever) then it is not persistent.

You should be using SharedPreferences to save this kind of persistent data.

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

like image 142
Alex Lockwood Avatar answered Jan 31 '26 02:01

Alex Lockwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!