How to get spinner selected value and store as string in sqlite?

安稳与你 提交于 2019-12-11 04:28:37

问题


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



来源:https://stackoverflow.com/questions/16874653/how-to-get-spinner-selected-value-and-store-as-string-in-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!