简体   繁体   English

使用 SharedPreferences 保存和检索值

[英]Saving and retrieving values with SharedPreferences

I want to save two values using shared preferences and get those values in other classes.我想使用共享首选项保存两个值并在其他类中获取这些值。 Can any one please give me information about how to set shared preferences and getting value from shared preferences.谁能给我有关如何设置共享偏好和从共享偏好中获取价值的信息。

I am using following code:我正在使用以下代码:

SharedPreferences settings =  
        getSharedPreferences("MyGamePreferences", MODE_WORLD_READABLE); 

    SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_WORLD_READABLE);  
    SharedPreferences.Editor prefEditor = gameSettings.edit();  
    prefEditor.putString("KEY", "e6c77c29021c9b3bd55aa0e9b7687ad9");  
    prefEditor.putString("SECRET", "ca85fa3fe86edaf2");
    prefEditor.commit();

Try this,尝试这个,

SharedPreferences button1; 
String name1="",name2="";
button1=this.getSharedPreferences("MyGamePreferences",MODE_WORLD_WRITEABLE);
        name1=button1.getString("KEY", "");
        name2=button1.getString("SECRET", "");



 SharedPreferences.Editor prefEditor = button1.edit();  
     prefEditor.putString("KEY","e6c77c29021c9b3bd55aa0e9b7687ad9");  
     prefEditor.putString("SECRET", "ca85fa3fe86edaf2");
     prefEditor.commit();

now stored two values.现在存储了两个值。

SharedPreferences myPrefs = this.getSharedPreferences("prefEditor ", MODE_WORLD_READABLE); SharedPreferences myPrefs = this.getSharedPreferences("prefEditor ", MODE_WORLD_READABLE); String key = myPrefs.getString(KEY, "nothing");字符串键 = myPrefs.getString(KEY, "nothing"); String secret = myPrefs.getString(SECRET, "nothing"); String secret = myPrefs.getString(SECRET, "nothing");

you can retrieve the values, using the getString method by passing the Key and a default value.您可以使用 getString 方法通过传递 Key 和默认值来检索值。 http://developer.android.com/reference/android/content/SharedPreferences.html http://developer.android.com/reference/android/content/SharedPreferences.html

my problem was how to retrieve these stored values in another file.我的问题是如何在另一个文件中检索这些存储的值。 it was cleared my code is我的代码被清除了

      SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);


      String key = sharedPreferences.getString("key", "");
      String secret = sharedPreferences.getString("secret", "");

Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM