I have an SQLite database with a table called author
. I'm trying to pull the id
and name
values and pass them to the MainActivity where id
will be stored as a variable and name
will be displayed in a ListView.
But this is how the log (and my ListView) looks:
[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]
I can see that the problem is because I'm adding both id
and name
to the AuthorList array but not specifying which one to show in the ListView. But how do I do that?
Snippet from DatabaseHelper class:
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;
}
Author class:
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;
}
}
Snippet from 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);
EDIT:
I solved the problem using this thread from the comment below. Adding this code to my Author class to override the toString()
method inherited from the Object
class did the trick:
@Override
public String toString() {
return name;
}