How to get spinner selected value and store as str

2019-07-28 18:59发布

问题:

I want to get the spinner selected value and return it as string to store in sqlite database read the data when needed.

I try the method as below,

sp = (Spinner) findViewById(R.id.spnCategory);      
ArrayAdapter<CharSequence> ar = ArrayAdapter.createFromResource(this,
                R.array.category, android.R.layout.simple_list_item_1);
ar.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp.setAdapter(ar);
String selection = sp.getSelectedItem().toString();

and get the string extras as below:

selection = extras.getString("category");

put extras as below:

v.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent=new Intent(context,ViewItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               

                intent.putExtra("category", category);

            }
        });

But I can't get the spinner value that selected, what I get just the first value in Spinner, may I know what wrong with my coding?

回答1:

Use onItemSelected

 public void onItemSelected(AdapterView<?> parent, View view, 
        int pos, long id) {
    // An item was selected. You can retrieve the selected item using
    // parent.getItemAtPosition(pos)

    TextView tv = (TextView)view;
    String selection = tv.getText().toString();   // or you can use the position but I do this to do other things with the TextView 
}

public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
}
}

Retrieving Spinner values

And make sure you implements OnItemSelectedListener in your Activity and set the listener on your Spinner

sp.setOnItemSelectedSpinner(this);

Note

You may want to declare selection as a member variable so that you can use it other places and assign it here