0

I am new to Android Mono programming, but I have what is probably a simple question. Basically what I am doing is storing a String value whenever my app is exited via home or back button action. I want to restore this String value to the proper TextView field when the app is reopened. This seems simple enough, but I have yet to discover the means to do so. So far I have the string as a global variable to my Activity class, and I set it anytime an action is taken in my app where this value is changed. I have handled OnResume and OnRestart to try and repopulate the TextView but seems the life cycle of the activity causes the value of this String to be lost when the app is exited. Where or how can I store this value upon change or exit of the app, so when its resumed, the value can be restored?

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
Wanabrutbeer
  • 676
  • 6
  • 11
  • 5
    Shared preferences is the best solution – Adam Nov 17 '12 at 07:18
  • 1
    I agree with @Adam. Shared preferences *is* the best solution. Check the [docs](http://developer.android.com/reference/android/content/SharedPreferences.html) or [this question](http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) for reference. – Lokesh Mehra Nov 17 '12 at 07:35

2 Answers2

1

use this to store the string...

        final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref1.edit();
        editor.putString("Stringval", "xxxxxxx");
        editor.commit();

to get the value from SharedPreference use below code:-

    final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
    String str1= pref2.getString("Stringval", null);
Mehul Ranpara
  • 4,245
  • 2
  • 26
  • 39
  • This worked great. For C# its ISharedPreferences and ISharedPreferencesEditor, but the rest is the same. Also, to recall the values make an ISharedPreferences the same way, and call GetString("key", "defaultValue") – Wanabrutbeer Nov 17 '12 at 19:44
0

You can also use database except shared preferance.

sumit acharya
  • 619
  • 1
  • 6
  • 18