Q.Ali
Q.Ali

Reputation: 67

How to save spinner state for specific item

So I have an android app that organises a list of items. Each item has the same fields. Including one selected by way of spinner.
I can save the details of each item individually just fine, and open them and edit them without any problem.
However, when ever I change the spinner value on one item, it changes it for all of them. How can I set the position of the spinner, for each individual item? The code below shows how I create the spinner, and save it's state. The problem is it's state is saved for all items in the list. How can I save it individually?

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, genres);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    //SET SELECTION AFTER YOU SET THE ADAPTER NOT BEFORE IT
    spinner.setSelection(preferences.getInt("spinnerSelection",0));
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        SharedPreferences preferences =PreferenceManager.getDefaultSharedPreferences(MovieInfo.this);

        public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
            int item = spinner.getSelectedItemPosition();

            //String selected = spinner.getItemAtPosition(position).toString();
            //Toast.makeText(MovieInfo.this, "Selected item: " + selected, Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("spinnerSelection", item);
            editor.commit();

        }
        public void onNothingSelected(AdapterView<?> arg0) {

         }
    });

Upvotes: 0

Views: 1061

Answers (1)

Nabin
Nabin

Reputation: 11776

Though you can accomplish this using SharedPreferences, I would recommend you to use database instead.

Add the related code inside the onItemSelected() method. May be you want to add the record in sqlite inside the method.

Update:

As per you question in chat, you can use Field variable instead of local to remove the need to make it final.

Upvotes: 1

Related Questions