2

所以我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);
4

3 回答 3

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

请参阅共享首选项

于 2013-03-01T18:02:34.530 回答
1

Try this

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();

    }
} 

Let me know if it works for you.

于 2013-03-01T17:35:01.067 回答
1

为了写入 SharedPreferences 您可以使用:

   Editor editor = getPrefs.edit();
    editor.putString("B1", "you value here");
    editor.commit();
于 2013-03-01T17:11:40.890 回答