Reputation: 1
I have a spinner view called Spinner_Gender
, I made array, array adapter and made onItemSelectedListener
. I want to save the selected item position which is integer to shared preference, I tried using a string with Editor and putInt, it saved well. But when reloading the saved data to the spinner using .setSelection
it gives an error because it wants an integer not string. Also while trying Integer in sharedpreference I can't save the selected item position to it because the putInt needs only a string to put int in.
Sorry for long question but I searched a lot and can't find answer. Two more questions please:
what is the integer name for spinner selectedItemPosition
? How can I store it to sharedpreference
?
Code:
final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View itemSelected,
final int selectedItemPosition, long selectedId)
{
int selectedPosition = spinner.getSelectedItemPosition();
Editor editor = mGameSettings.edit();
editor.putInt(myNum,selectedPosition);
editor.commit();
}
}
Upvotes: 0
Views: 1180
Reputation: 24235
You should do something like this
spinner.setSelection(dataAdapter.getPosition(genderstring));
final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter);
spinner.setSelection(mGameSettings.getInt("gender", 0));
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View itemSelected,
final int selectedItemPosition, long selectedId)
{
Editor editor = mGameSettings.edit();
editor.putInt("gender", selectedItemPosition);
editor.commit();
}
}
Upvotes: 0
Reputation: 1325
I don't quite understand what's your issue with SharedPreferences. When you want to save the value you do something like this :
SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
Editor editTest = test.edit();
editTest.putInt("key", id_from_spinner);
editTest.commit();
When you want to get the value you do something like this :
SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
int id = test.getInt("key", -1);
if(id != -1) {
//use it in your spinner
} else {
//abort because value was not set
}
Upvotes: 1
Reputation: 2538
To convert an int to a String you can use Integer.toString(theInteger)
and to convert a String to an int you can use Integer.parseInt(theString)
.
Upvotes: 0