如何从数据库填充微调内容(SQLite)
我有POJO:类别,包含id和name, 我已经有了表,有一个函数来获取这样的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;
}
然后在Activity上我这样称呼它:
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);
当我运行它时,它会加载如下字符串:&#34; schema.SetcardCategory@22293c98"和许多其他人的价值相似。
如何填充微调器以将名称字段显示为标签,将id字段显示为我们提取以保存到数据库中的值?
答案 0 :(得分:3)
class Pojo{
private String name;
@Override
public String toString() {
return name;
}
}
在pojo类中这样做,所以当它在适配器中使用to string方法来加载数据时,它将为对象返回一个值
答案 1 :(得分:2)
解决方案1 覆盖SetcardCategory类中的toString方法
class SetcardCategory {
...
...
@Override
public String toString() {
return this.name;
}
}
解决方案2 如果您只想显示名称,只需从DB中选择名称
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);