问题
Good evening. I'm trying to save the choice the user makes in Spinner in SharedPreferences, when he clicks OK, but I'm not getting it, can anyone help me? Then I want to redeem the choice made when it opens the application again and puts it in a textView.
Follow my code.
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();
}
});
回答1:
check this,
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");
}
}
to save the string
PreferenceManager preferenceManager = new PreferenceManager(context);
preferenceManager.saveString("key","StringValue");
get the stored string like this
PreferenceManager preferenceManager = new PreferenceManager(context);
String savedString = preferenceManager.getString("key");
来源:https://stackoverflow.com/questions/49765921/spinner-with-sharedpreferences