从偏好中获取字符串

时间:2013-03-01 16:56:20

标签: android preferences

所以我EditTextPreference中有Preferences,我想输入内容并保存,然后我想在Activity中获取该文字。我EditTextPreference的关键是B1。我试过这段代码:

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
               String samples = getPrefs.getString("B1", "");
               b1.setText(samples);

<EditTextPreference
            android:dialogTitle="Button 1"
            android:key="B1"
            android:summary="Set text on button 1"
            android:title="Set text on button 1" />

我在

之间得到java.lang.NullPointerException
String samples = getPrefs.getString("B1", "lol");
            b1.setText(samples);

3 个答案:

答案 0 :(得分:2)

宣告:

SharedPreferences pref = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

放一个值(可以是int,String等)

 String tom = "tom";
    pref.edit().putString("tom", tom).commit(); // To set a value to SharedPreferences

获取值(记住类型)

String name = pref.getString("tom", null); // To get a value from SharedPreferences

请参阅SharedPreferences

答案 1 :(得分:1)

为了写入SharedPreferences,您可以使用:

   Editor editor = getPrefs.edit();
    editor.putString("B1", "you value here");
    editor.commit();

答案 2 :(得分:1)

试试这个

Home.java

public class Home extends Activity {

public SharedPreferences prefs;

String mValues;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

     setContentView(R.layout.main);
     prefs = PreferenceManager.getDefaultSharedPreferences(this);
     mValues= prefs.getString("male", "female");
} 

}

Preferences.java

public class Preferences extends PreferenceActivity  implements OnSharedPreferenceChangeListener{


    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.setting);

    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
        Editor editor = sharedPref.edit();
        if(key.equalsIgnoreCase("B1")){
            editor.putString("male","my value"); 
        }

        editor.commit();

    }
} 

让我知道它是否适合你。