2013-06-01 35 views
1

我想获取微调器选定的值并将其作为字符串返回以便在sqlite数据库中存储需要时读取的数据。如何获得微调器选定的值并作为字符串存储在sqlite中?

我试试下面的方法,

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(); 

,并获得额外的字符串如下:如下

selection = extras.getString("category"); 

放演员:

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); 

      } 
     }); 

但我不能获得所选的微调值,我只能得到Spinner的第一个值,我可以知道我的编码有什么问题吗?

回答

2

使用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

并确保您implements OnItemSelectedListenerActivity并设置监听你的Spinner

sp.setOnItemSelectedSpinner(this); 

注意

您可能想声明selection作为成员变量,以便您可以在其他地方使用它并在此处指定它

+0

是的,它的工作!谢谢^^ – user2301281

+1

不客气。很高兴我能帮上忙 – codeMagic

相关问题