Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

database - Android Spinner Selected Item

I am populating a spinner from the database like this

    // Populating the City Spinner
    Cursor cities = db.cityList();
    startManagingCursor(cities);

    // create an array to specify which fields we want to display
    String[] from = new String[] { DBAdapter.KEY_NAME };
    // create an array of the display item we want to bind our data to
    int[] to = new int[] { android.R.id.text1 };

    Spinner cityList = (Spinner) this.findViewById(R.id.citySpiner);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cities, from, to);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    cityList.setAdapter(adapter);

When i try to get the content from the selected item of the spinner like this

// Get the City
                Spinner getCity = (Spinner) findViewById(R.id.citySpiner);
                String cityName = getCity.getSelectedItem().toString();

i get the following. Is there a way i can get the city name or the city id from the database.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think, as you are using a customadapter and giving three lists in adapter...

you can't get the selected text simply by calling the getSelectedItem()..

Use this:

Spinner mySpinner = (Spinner)findViewbyId(R.id.spinner);
int position = mySpinner.getSelectedItemPosition();
String Text = yourCityList[position].toString(); // dont know which list is holding the city list... 
// i didn't use any db in any of my app so cant tell you how can you get list... 
// leaving it to you... :)

Hope it helps....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...