【发布时间】:2017-10-30 13:26:57
【问题描述】:
我有一个 SQLite 数据库,其中有一个名为 author 的表。我正在尝试提取id 和name 值并将它们传递给MainActivity,其中id 将作为变量存储,name 将显示在ListView 中。
但这就是日志(和我的 ListView)的外观:
[com.example.apple.bookshelf.Author@31e44c75,
com.example.apple.bookshelf.Author@24fe640a,
com.example.apple.bookshelf.Author@2c87d47b,
com.example.apple.bookshelf.Author@2ab52298,
com.example.apple.bookshelf.Author@393a3af1,
com.example.apple.bookshelf.Author@2326b6d6]
我可以看到问题是因为我将 id 和 name 添加到 AuthorList 数组,但没有指定要在 ListView 中显示哪一个。但是我该怎么做呢?
来自 DatabaseHelper 类的片段:
public List<String> getAllAuthors() {
List authorList = new ArrayList();
// Select all query
String selectQuery = "SELECT * FROM " + AUTHORS + " ORDER BY name_alphabetic";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Author author = new Author();
author.setID(Integer.parseInt(cursor.getString(0)));
author.setName(cursor.getString(1));
authorList.add(author);
} while (cursor.moveToNext());
}
// return author list
return authorList;
}
作者类别:
public class Author {
int id;
String name;
String name_alphabetic;
public Author() {
}
public Author(int id, String name, String name_alphabetic) {
this.id = id;
this.name = name;
this.name_alphabetic = name_alphabetic;
}
// getters
public int getID() {
return this.id;
}
public String getName() {
return this.name;
}
public String getNameAlphabetic() {
return this.name_alphabetic;
}
// setters
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setNameAlphabetic(String name_alphabetic) {
this.name_alphabetic = name_alphabetic;
}
}
来自 MainActivity 的片段:
// connect authorsListView variable to XML ListView
authorsListView = (ListView) findViewById(R.id.authors_list_view);
// create new database helper
DatabaseHelper db = new DatabaseHelper(this);
// create new list through getAllAuthors method (in DatabaseHelper class)
List authorList = db.getAllAuthors();
Log.i("authors", authorList.toString());
// create new Array Adapter
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, authorList);
// link ListView and Array Adapter
authorsListView.setAdapter(arrayAdapter);
编辑:
我在下面的评论中使用this thread 解决了这个问题。将此代码添加到我的 Author 类以覆盖从 Object 类继承的 toString() 方法就可以了:
@Override
public String toString() {
return name;
}
【问题讨论】:
-
简单的列表项布局就是这样做的。您可能应该为列表项编写了正确的布局,因此它们不依赖于
toString()。 -
使用泛型。如果您将
List authorList = new ArrayList()替换为List<String> authorList = new ArrayList<>(),那么您将在编译时看到您的问题。 -
方式一:从作者列表中,单独创建一个新列表以及作者姓名,并设置到阵列适配器中。方式二:通过继承ArrayAdapter创建一个自定义的Adapter类。
标签: java android sqlite listview