我创建了一个方法,其目的是检索我在SQLite数据库中创建的表中的所有条目。我创建了一个DatabaseHandler类并编写了所有方法,但是我想要获取所有条目的方法都不起作用。获得单个条目没有问题,但检索所有用户似乎非常不安。您将在下面找到该类的完整代码,因为另一种方法可能是问题的根源。您还可以找到一些快速信息,这些信息可以使一些事情变得更加清晰。
快速信息: -Cursor移动到第一个,并在最后一个条目 -The Cursor.getCount()方法返回所有条目的计数,但while循环仍然执行4次 -4用户已创建,但由于计数始终保持不变,因此所有用户都相同 - 我尝试了不同的循环并搜索了我的问题,但到目前为止还没有任何工作
守则:
package com.example.devtest;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String
DATABASE_NAME = "userManager",
TABLE_NAME = "users",
KEY_ID = "id",
KEY_USERNAME = "username",
KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERNAME + " TEXT," + KEY_EMAIL + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void dropTable() {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void createTable() {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERNAME + " TEXT," + KEY_EMAIL + " TEXT)");
}
public void addUser(User user) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, user.getUsername());
values.put(KEY_EMAIL, user.getEmail());
db.insert(TABLE_NAME, null, values);
db.close();
}
public User getUser(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID, KEY_USERNAME, KEY_EMAIL }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return new User(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
}
public int getUserCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int cursorCount = cursor.getCount();
cursor.close();
return cursorCount;
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if (cursor.moveToFirst()) {
do {
users.add(new User(cursor.getInt(cursor.getColumnIndex(KEY_ID)), cursor.getString(cursor.getColumnIndex(KEY_USERNAME)), cursor.getString(cursor.getColumnIndex(KEY_EMAIL))));
Log.d("dbDebug", String.valueOf(cursor.getCount()));
}
while (cursor.moveToNext());
}
return users;
}
}