Android Shared preferences with multiple activities

前端 未结 3 971
星月不相逢
星月不相逢 2020-12-30 04:36
  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?
相关标签:
3条回答
  • 2020-12-30 04:38

    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.

    0 讨论(0)
  • 2020-12-30 04:49

    You don't need to do anything special, other than make sure both activities are writing to/reading from the same file. Under the hood, preferences are just stored as an XML file.

    So, your choices are:

    1) Use PreferenceManager.getDefaultSharedPreferences() from both activities to write to the default file.

    2) Use Context.getSharedPreferences() specifying a custom file name, and use the same name from both activities.

    0 讨论(0)
  • 2020-12-30 04:52

    Shared Preferences are just that, shared. As long as you properly save the preferences after editting them by calling Editor.commit(), they will be available in the future.

    0 讨论(0)
提交回复
热议问题