[英]Populate spinner from database content (SQLite)
如何從數據庫(SQLite)填充微調框內容
我有POJO:類別,包含ID和名稱,我已經有表,並具有獲取ArrayList的功能,如下所示:
public List<SetcardCategory> getAllSetcardCategory()
{
List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
SetcardCategory setcardCategory = new SetcardCategory();
setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
setcardCategory.setName(c.getString(c.getColumnIndex("name")));
// adding to tags list
setcardCategories.add(setcardCategory);
} while (c.moveToNext());
}
return setcardCategories;
}
然后在活動上,我這樣稱呼它:
List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
sItems.setAdapter(arrayAdapter);
當我運行它時,它會加載這樣的字符串:“ schema.SetcardCategory@22293c98”以及許多與此類似的值。
如何填充微調框,以將名稱字段顯示為標簽,將id字段顯示為我們獲取以保存到DB中的值?
class Pojo{
private String name;
@Override
public String toString() {
return name;
}
}
在pojo類中這樣做,因此當它在適配器中使用to字符串方法來加載數據時,它將為該對象返回一個值。
解決方案1覆蓋SetcardCategory類中的toString方法
class SetcardCategory {
...
...
@Override
public String toString() {
return this.name;
}
}
解決方案2如果僅想顯示名稱,則僅從數據庫中選擇名稱
public List<String> getAllSetcardCategory()
{
List<String> setcardCategories = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
// adding to tags list
setcardCategories.add(c.getString(c.getColumnIndex("name")));
} while (c.moveToNext());
}
return setcardCategories;
}
並創建陣列適配器為
List<String> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.