问题描述
- 如何在Android spinner中设置数据?
-
我从spinner 中获得一个值,并把它储存在一个数据库中。但是在返回时,不能在Spinner设置Text。
如何在EditText中像设置其它功能一样设置这个功能?public class MainActivity_spinner extends Activity { Button save; Button show; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] items = new String[] {" ","Male","Female"}; final Spinner gender =(Spinner)findViewById(R.id.sex); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); gender.setAdapter(adapter); save=(Button)findViewById(R.id.save); show=(Button)findViewById(R.id.show); //---------------------------------------------------------------- save.setOnClickListener(new Button.OnClickListener() { public void onClick(View view){ ContentValues values = new ContentValues(); values.put("sex",gender.getSelectedItem().toString()); sql.Insert("db",null,values); sql.Close(); } }); show.setOnClickListener(new Button.OnClickListener() { public void onClick(View view){ sql.open(); String query = "select sex from db where id=2"; Cursor c = sql.rawQuery(query,null); c.moveToFirst(); (Error is here)it is my spinner i want show value >>>>>> gender.setSelection(c.getString(0), true); } }); } }
我把第二项保存在spinner中的数据库中。现在又重新设置了spinner。然后点击Show按钮,然后item就会以数据的形式显示在spinner中。为什么实现不了?
解决方案
ArrayList<String> options=new ArrayList<String>();
...onCreate(){
...
Cursor c=<your cursor with value>;
for(loop for total records){
options.add(<value from cursor>);
}
//now you have options with all values of your database
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,options);
mSpinner.setAdapter(adapter); // this will set list of values to spinner
mSpinner.setSelection(options.indexOf(<value you want to show selected>)));//set selected value in spinner
}
时间: 2024-10-31 14:15:50