I tried an tutorial but I cannot save the state of my spinner.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_main);
//language selection list
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.language_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// storing string resources into Array
lang_list = getResources().getStringArray(R.array.language_list);
Toast.makeText(getBaseContext(), "You have selected : " + lang_list[index],
Toast.LENGTH_SHORT).show();
choice = spinner.getSelectedItem().toString();
spinnerPos = arg2;
final ImageView country_flag = (ImageView)findViewById(R.id.country);
String s=((TextView)arg1).getText().toString();
if(s.equals("English"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.eng_spinner));
if(s.equals("German"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.german_spinner));
if(s.equals("French"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.french_spinner));
if(s.equals("Spanish"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.spanish_spinner));
}
/*private int getPersistedItem() {
String keyName = makePersistedItemKeyName();
return PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getInt(keyName, 0);
}
protected void setPersistedItem(int position) {
String keyName = makePersistedItemKeyName();
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().putInt(keyName, position).commit();
}
private String makePersistedItemKeyName() {
return currentUserName + "_your_key";
}*/
public void onNothingSelected(AdapterView<?> arg0) {
// do nothing
}
});
}
}
To saved the states (these are after oncreate):
protected void onResume(){
super.onResume();
spinner.setSelection(spinnerPos);
}
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("spinnerIndex", spinnerPos);
Log.d("SpinnerState", "Spinner at position " + spinnerPos + " was saved");
}
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getInt("spinnerIndex");
Log.d("SpinnerState", "Spinner at position " + spinnerPos + " was restored");
}
I am trying to save the spinner state even if the app is closed or the activity stopped. Can someone explain why it's not working.