4

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.

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I try your code but i got error : java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.