我知道這已被問了很多周圍,但我似乎無法得到這個工作。 情況:我有一個對話框,其中帶有一個接受按鈕的EditText。我想在用戶觸摸接受按鈕時用SharedPreferences存儲字符串的值。這是我迄今爲止的代碼。共享首選項不保留任何東西
public void showDialog()
{
final Dialog dialog = new Dialog(VentilationActivity.this);
dialog.setContentView(R.layout.menu_options);
dialog.setTitle("Configuration de l'adresse IP");
dialog.setCancelable(true);
dialog.show();
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
SharedPreferences preferences = getSharedPreferences("Agrinuvo", 0);
String texte = preferences.getString("VentIpKey", "");
adressIp.setText(texte);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(adressIp, InputMethodManager.SHOW_IMPLICIT);
Button btnAccept = (Button) dialog.findViewById(R.id.button1);
btnAccept.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
textIp = adressIp.getText().toString();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VentIpKey", textIp);
editor.commit();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(adressIp.getWindowToken(), 0);
dialog.dismiss();
}
});
}
而且,當然這是行不通的。每次關閉對話窗口並重新打開它時,EditText文本都是空的。感謝您的任何幫助,您可以提供。
不要忘記做'喜好= getSharedPreferences( 「Agrinuvo」,0);'某處執行的onClick之前。 –