0

I am working on an android project and I am using a spinner which is populated manually. For example if, in the spinner I have the following items:

select

Category 1

Category 2

Category 3

Initially the spinner value is select now i selected category 2 How would I programmatically make Category 2 as the default value for next session(opening the app next time). Thank you.

Vijaya Varma Lanke
  • 603
  • 2
  • 7
  • 19

3 Answers3

1

In the first session you save the selected index in a SharedPreferences:

PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("srIndex",spinner.getSelectedItemPosition());

And in the second session you read the saved index and set it to the spinner:

spinner.setSelection(PreferenceManager.getDefaultSharedPreferences(this).getInt("srIndex",0));
Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39
  • could you please tell me in detail about srIndex and where i add this code, is it after spinner.setAdapter(dataAdapter); – Vijaya Varma Lanke Apr 13 '16 at 09:14
  • Call the first line when the app is closed (onPause / onStop). And the second line after initializing the Spinner (after setAdapter). "srIndex" is the name of the saved index. – Luca Ziegler Apr 13 '16 at 09:20
  • any where we can close the app, that means i have to add that in every class in my project, could you please clarify me – Vijaya Varma Lanke Apr 13 '16 at 09:46
0

If you know the position of "Category 2" you can do the item below. You can get the index from the adapter.

spinner.setSelection(indexOfCategory2);
jjz
  • 2,007
  • 3
  • 21
  • 30
0

You can use SharedPreferences to save the index of selected category and every time activity is loaded retrieve the index from SharedPreferences and set selection

Spinner.setSelection(index);

If you not aware of SharedPreferences you can refer to StackOverflow

Community
  • 1
  • 1
Shashank
  • 1,087
  • 1
  • 14
  • 26