Android Shared preferences with multiple activities

三世轮回 提交于 2019-12-18 11:50:20

问题


  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?

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/12432585/android-shared-preferences-with-multiple-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!