Ich versuche, eine Liste von Büchern zu speichern, aber wenn ich die Tabelle lese, bekomme ich nur ein Buch.Android: sqlite speichert nur einen Artikel
DatabaseHelper.java
...
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" (id TEXT PRIMARY KEY,title TEXT, description TEXT)"
);
}
public boolean insertBook (String id, String title, String publisher, String format,
String description, String creator, String category, String language, String date)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("id", id);
contentValues.put("title", title);
contentValues.put("description", description);
db.insert(TABLE_NAME, null, contentValues);
db.close();
return true;
}
public List<Book> getBooks()
{
Book book = new Book();
List<Book> bookList = new ArrayList<Book>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery("select * from tblbooks", null);
if (cursor.moveToLast()) {
do {
book.setId(cursor.getString(cursor.getColumnIndex("id")));
book.setTitle(cursor.getString(cursor.getColumnIndex("title")));
book.setDescription(cursor.getString(cursor.getColumnIndex("description")));
bookList.add(book);
} while (cursor.moveToNext());
}
return bookList;
}
...
MainActivity.java
Hier habe ich eine für lus, die die Werte in Buch ändert und in diesem lus habe ich diesen Code zu setzen, so dass mit jedes neue Buch das Buch wird gespeichert:
...
//Save books localy
dbHelper.insertBook( //the value of book changes, I've tested it so this is not the problem
book.getId(),
book.getTitle(),
book.getDescription()
);
Danach verwende ich diesen Code zu erhalten alle Bücher aus der Datenbank, das ist, wo ich nur 1 Buch bekommen ...
...
//Get bookshelf of local database
for (int i = 0; i < dbHelper.getBooks().size(); i++) {
bookList.add(dbHelper.getBooks().get(i)); <-- should put all books in this list.
}
...
Ausgang ist immer nur ein Buch ...
Ihr Cursor bewegt letzter Punkt und Ihre Schleife stoppen nach einer Iteration. Ändern Sie einfach für cursor.movetofirsrt –