How To Maintain Spinner State In Android
Solution 1:
You can use
spinner.getSelectedItemPosition();
that will return to you an int that you can save with
prefEdit.putInt();
then when you want to re-load everything that has been saved you would just call
spinner.setSelection(prefs.getInt("key", default));
OR TRY LIKE THIS
to Save:
int selectedPosition = yourSpinner.getSelectedItemPosition()
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();
to Load:
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
if you are array used it should changed like this
String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.commit();
checking array[i] against the value stored in prefs.if you use an ArrayList instead this part could be done without the loop by calling
ArrayList.indexOf(prefs.getString("spinnerSelection", "");
when you commit show all above array item gone. show no one into array.
Solution 2:
You can follow the below procedure:
You need to save state of your spinner so this would be helpful to you.
1.) Apply this after creating spinner object
sectionNameSpinner.setSelection(getPersistedItem());
2.) Create these methods according to you to save the state of your spinner selected item
private int getPersistedItem() {
String keyName = makePersistedItemKeyName();
return PreferenceManager.getDefaultSharedPreferences(this).getInt(keyName, 0);
}
protected void setPersistedItem(int position) {
String keyName = makePersistedItemKeyName();
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(keyName, position).commit();
}
private String makePersistedItemKeyName() {
return currentUserName + "_your_key";
}
3.) Set its state as the spinner selection changed:
sectionNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View view, int position, long itemId) {
setPersistedItem(position);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Solution 3:
When you "go to some other screen" you should do so via a new activity. Then, after you finish that new activity, the spinner selection activity will resume and the selection state will be as it was prior to starting the second activity.
Solution 4:
- Make sure you are not hitting the webservice in OnResume() of your activity.
- Make sure you are not finishing the current activity by calling finish() before proceeding to the next activity.
- And check whether data available or not before web hit (here you can avoid unnecessary web hits)
Post a Comment for "How To Maintain Spinner State In Android"