N. Park
N. Park

Reputation: 397

How to make a spinner show previously selected item after refresh?

What I have is a Settings activity on which I choose the language via spinner. When I change it to Russian for example the language changes, but when I open the Settings menu again the selected item on the spinner is the first item (English) and not the current one (Russian).

This is my spinner

Resources res = getResources();
language = res.getStringArray(R.array.languages_arrays);
Spinner spinner = (Spinner) findViewById(R.id.toolbar_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, R.layout.spinner_item_dropdown,
             language);

spinner.setAdapter(adapter);

What do I need to change in the spinner in order to show the selected language?

Upvotes: 0

Views: 3709

Answers (3)

Ahlem Jarrar
Ahlem Jarrar

Reputation: 1129

If you want to set the previous selected item of a spinner you have to store the selected item and then set your selection : here's an example wish i'am getting my previous selected item then fetching the item's position from he's array adapter

  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String language = preferences.getString("language", "");
        if(!language.equalsIgnoreCase(""))
        {
            int spinnerPosition = arrayAdapter.getPosition(language);
            spinner.setSelection(spinnerPosition);

        }

You can store your data as below :

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
       {

 SharedPreferences.Editor editor = preferences.edit();
 editor.putString("language",spinner.getSelectedItem().toString(););
 editor.apply();



        }


        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Upvotes: 1

surendrasheoran
surendrasheoran

Reputation: 3

You have to save previous selected value somewhere in your app. When you open setting again check for that value and find position of it in array. Once you find location of it set Spinner selection to that position like below:

spinner.setSelection(position_of_selected_item);

Upvotes: 0

Anil
Anil

Reputation: 1614

For that u need to set spinner value programatically

for (int i=0 ;i<languages.length;i++)
                {
                    if(languages[i] = "RUSSIAN")//change it according to ur prrefence
                   spinner.setSelection(i);
                }

Upvotes: 0

Related Questions