Android array list from database

爱⌒轻易说出口 提交于 2019-12-25 14:49:19

问题


I wanna create an array of cities that are stored in the database

Cities Table

CREATE TABLE cities (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);

Querying for City List

// City List
public Cursor cityList() throws SQLException {
    return db.query(TABLE_CITIES, new String[] {ID, KEY_NAME}, null, null, null, null, null, null);
}

Trying to Get the content into the Array

    Cursor cities = db.cityList();
    startManagingCursor(cities);

    String[] city_list = new String[] { DBAdapter.KEY_NAME };
    Spinner cityList = (Spinner)this.findViewById(R.id.citySpiner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, city_list);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    cityList.setAdapter(adapter);

Am not able to populate the Spinner.. with the database content.


回答1:


Try SimpleCursorAdapter

String[] from = new String[] {  DBAdapter.KEY_NAME  };
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_spinner_dropdown_item , cursor, from, to);
cityList.setAdapter(cursorAdapter);

Edit:

from means the column(s) from the Cursor which will be used to display as text array in Spinner. to means the id(s) of the view which will hold the value of that column. It is very interesting that the view at index N will hold the text from column at N.



来源:https://stackoverflow.com/questions/5817867/android-array-list-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!