开发者

Android how to get selected item from data driven spinner

开发者 https://www.devze.com 2022-12-12 07:18 出处:网络
Newbie question. I\'m using a SimleCursorAdapter to populate a spinner from an SQLite table, as shown in the Android dev docs:

Newbie question. I'm using a SimleCursorAdapter to populate a spinner from an SQLite table, as shown in the Android dev docs:

Spinner list=(Spinner)findViewById(R.id.cboModel);        
SimpleCursorAdapter ModelAdapter = new SimpleCursorAdapter(this,
   android.R.layout.simple_spinner_item, model,
   new String[] {"Drug"},       
   new int[] {android.R.id.text1});
ModelAdapter.setDropDownViewResource(
        android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(ModelAdapter);
list.setOnItemSelectedListener(onModelSelect);

I've set up a listener, but I can't figure out how to get the selected item text, it pulls up the SQLiteCursor, not the actual text in the spinner.

private AdapterView.OnItemSelectedListener 
    onModelSelect= new AdapterView.OnItemSelectedListener() {
   开发者_开发问答     public void onItemSelected(AdapterView<?> 
            parent, View view, int position, long id) {
            ModelName = parent.getSelectedItem().toString(); 
            android.util.Log.w("OnItemSelect.cboModel", ModelName);     
        }
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub          
        }       
};

Google turns up the question on several message boards, but no answers, so it appears to be a common newbie question. It may be painfully obvious to some, but if you could point me in the right direction I would appreciate it. Thank you.


Since the selected item is a Cursor, you can easily get the value by calling getString with the index of the column in the original database query that you used to populate the Spinner.

String spinnerString = null;
Cursor cc = (Cursor)(yourSpinner.getSelectedItem());
if (cc != null) {
    spinnerString = cc.getString(
        cc.getColumnIndex("Drug"));
}

This technique definitely works when the Spinner is populated from the database. I have not tried it with a resource array.


Figured it out... get the id, then make a DB query:

String id_string = String.valueOf(id);

thismodel=Pkmodel.getById(id_string, dbModel);

ModelName=thismodel.getDrug();          
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号