0

I have a class where it contains a variable

 public class MyClass
{
    public static string testenome;
    public string Testenome
    {
        get { return testenome; }
        set { testenome = value; }
    }
}

When I leave the application in the background I lose the value of the variable as soon as I return.

To some way for me to make that variable stay fixed, only if I close the app so I lose it ?

JOSE
  • 45
  • 6
  • shouldn't `testnome` have a private access modifier? also can you provide code of how you're instantiating the class and assigning the value, it's likely this is scope related – Jpsh Apr 03 '17 at 13:25
  • if there is an exception occurred in your code static value may gone in this case. – Chetan Joshi Apr 03 '17 at 13:28
  • 1
    You need to provide more details. This behavoiur seems normal, considering how Android apps work. I recommend reading about the lifecycle of an activity: https://developer.android.com/guide/components/activities/activity-lifecycle.html – pablochan Apr 03 '17 at 13:30
  • http://stackoverflow.com/a/18050592/436938 – Sergey Glotov Apr 03 '17 at 13:31
  • Does MyClass extends Application ? Also you might need to store and recover the variable value in the activity life cycle onCreate(), onResume() and onPause(). – Daniel Apr 03 '17 at 13:35

1 Answers1

0

Yes you can do save that variable in SharedPreferences so as it stays in app memory even if its closed.

First set value in SharedPreferences

//MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "TestName");
 editor.commit();

Now whenever you get back to app after closing it, just get the value of name from SharedPreferences

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.

This is the best way to retain any such vairable until app is uninstalled.

Wilson Christian
  • 650
  • 1
  • 6
  • 17