Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Shared preferences with multiple activities

  1. How do I retrieve shared preferences that have been saved from a previous activity?
  2. Do I need to enable file writing or some other manifest modifications?
like image 393
kabuto178 Avatar asked Sep 14 '12 22:09

kabuto178


People also ask

Can an app have multiple shared pref files?

Yes you can maintain as many shared preference files for an app as you can.

What is the maximum number of shared preferences you can create in Android?

there is no limit in Shared Preference.

What is the difference between commit () and apply () in androids shared preference?

Unlike commit() , which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.


1 Answers

You don't need any special manifest modificaiton to achieve that.

Assuming you have already saved preferences you can read those preferences at anytime doing something like I show bellow.

  1. Write on Shared Preferences file:

      SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
      SharedPreferences.Editor editor = prefs.edit();
      editor.putString("yourStringName", "this_is_the_saved_value");
      editor.commit(); // This line is IMPORTANT. If you miss this one its not gonna work!
    
  2. Read from Shared Preferences file:

      SharedPreferences prefs = getSharedPreferences("your_file_name",
      MODE_PRIVATE); String string = prefs.getString("yourStringName",
      "default_value_here_if_string_is_missing");
    

You can use a default file to save/ read your preferences. Just replace the first line of the two code snippets above by something like: SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());

Thats it! Check the Android Developers dedicated page to this matter, here.

Hope it was usefull. Let me know about it.

like image 175
yugidroid Avatar answered Sep 23 '22 13:09

yugidroid