晚上好。 我试图保存用户在SharedPreferences中在Spinner中做出的选择,当他点击OK,但我没有得到它,有人可以帮助我吗? 然后我想要重新打开再次打开应用程序时所做的选择并将其放在textView中。
关注我的代码。
mShowDialog = (Button) findViewById(R.id.btnEscolhaCidade);
mShowDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_spinner, null);
mBuilder.setTitle("Em qual Cidade Você está?");
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.cidades));
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter3);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Escolha uma Cidade")) {
cidade_Escolhida.setText(mSpinner.getSelectedItem().toString());
SharedPreferences.Editor editor = preferences2.edit();
editor.putString(getString(R.string.cidade_escolhida_salvo), mSpinner.getSelectedItem().toString());
editor.apply();
Toast.makeText(MainActivity.this,
mSpinner.getSelectedItem().toString(),
Toast.LENGTH_LONG)
.show();
dialogInterface.dismiss();
}
}
});
mBuilder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
答案 0 :(得分:0)
检查一下,
public class PreferenceManager {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public PreferenceManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences("General", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.apply();
}
public void saveString(String key, String value) {
editor.putString(key, value);
editor.commit();
}
public String getString(String key) {
return sharedPreferences.getString(key, "NA");
}
}
保存字符串
PreferenceManager preferenceManager = new PreferenceManager(context);
preferenceManager.saveString("key","StringValue");
获取存储的字符串
PreferenceManager preferenceManager = new PreferenceManager(context);
String savedString = preferenceManager.getString("key");