0

I want to save a variable through application shutdown. I have heard about SharedPreferences, but I didn't fully understand it. Isn't there an easier way to store only one variable. Detailed explanation would be great, as I am still beginning.

  • You can store it in database.. but it is more complicated.. SharedPrefs are simple, It is literally 4 lines of code.. https://developer.android.com/training/basics/data-storage/shared-preferences.html#WriteSharedPreference and you can short it to 2 lines.. If you don't understand then say what you don't understand. – miljon Apr 14 '17 at 11:24
  • Beginners like yourself are *strongly* encouraged to search before you post. Do you think you are the first person in the history of mankind that wants to do this? – Tim Apr 14 '17 at 11:27

1 Answers1

0

Try this for saving shared Preferences:

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putString("key","value").apply();

For getting shared preferences value:

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.getString("key","");

I hope this will help.

Ashish Gupta
  • 737
  • 11
  • 18
  • I don't know who pity upvoted this but when you answer questions that are as easy as this one there is a fat chance it has been asked and answered before multiple times. Takes 2 seconds to find a duplicate and flag the question as such. By posting new answers to questions posted by lazy people who did not search, effectively providing duplicate content, you are actively working against SO's goal – Tim Apr 14 '17 at 11:33
  • @TimCastelijns rather than searching for related question, I can tell the answer within 2 minutes. Why will I waste my time? – Ashish Gupta Apr 14 '17 at 12:44
  • I already explained why not to do what you did in my first comment. The fact that you did not read it and that you are now trying to justify your wrong action tells me you do not know how this site works. Take my advice, please, so you can do the correct thing next time. – Tim Apr 14 '17 at 13:07