nkpatel nkpatel - 2 months ago 11
Android Question

Android Spinner: Set selected item as default

I am making an android app that asks for the users to select a country via spinner.

When the user opens the app first time, user selects a country from list.

Then when app opens second time, I want the same country to be selected. I don't want user to select the country every time the app is opened.
How to do that?

Answer

You can use SharedPreferences to store the selection the first time that the user selects a country, and then use SharedPreferences again for the app to remember the selection, when the user returns a second time.

To store the selection in a SharedPrefence:

int selectedPosition = yourSpinner.getSelectedItemPosition()
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();

to load the selection onto the spinner when reusing the app:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
SharedPreferences prefs = getPreferences(0);

Hope this solves your issue :)