2 ssummeraw ssummeraw 于 2013.05.27 13:08 提问

如何在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中。为什么实现不了?

1个回答

myc_100
myc_100   2013.05.27 17:27
 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
    }
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!