我有两个带有EditText
的alertDialog,每个都应保存一个值以存储在sharedPreferences
中。但似乎不是单独存储它们,而是用第二个输入值替换第一个输入值。这是我的代码:
public void IPconfig(){
// some AlertDialog Builder codes
sharedPreferences = getSharedPreferences("FirstText", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
editor.putString("FirstText", etIP.getText().toString());
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
public void MonitoringIPConfig(){
// some AlertDialog Builder codes
sharedPreferences = getSharedPreferences("SecondText", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
editor.putString("SecondText", etIP.getText().toString());
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
答案 0 :(得分:0)
您必须致电commit()
,让您在编辑器中执行的任何更改实际显示在SharedPreferences中,如Android开发者页面所示。 https://developer.android.com/reference/android/content/SharedPreferences.html
尝试以下方法:
editor.putString("FirstText", etIP.getText().toString()).commit();