我在数据库类中使用以下方法。它不起作用,我看不出问题出在哪里。也许有人可以帮助我。
public ArrayList<Profile> getAllProfile() {
db = this.getWritableDatabase();
Profile profile = new Profile();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USER, null);
ArrayList<Profile> profiles = new ArrayList<>();
if (cursor!=null){
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext() ){
profile.setId(cursor.getInt(cursor.getColumnIndex(ID)));
profile.setFirstName(cursor.getString(cursor.getColumnIndex(FIRST_NAME)));
profile.setLastName(cursor.getString(cursor.getColumnIndex(LAST_NAME)));
profile.setFatherName(cursor.getString(cursor.getColumnIndex(FATHER)));
profile.setAge(cursor.getInt(cursor.getColumnIndex(AGE)));
profile.setEmail(cursor.getString(cursor.getColumnIndex(EMAIL)));
profile.setGender(cursor.getInt(cursor.getColumnIndex(GENDER)));
profile.setPhoneNumber(cursor.getString(cursor.getColumnIndex(PHONE_NUMBER)));
profiles.add(profile);
App.myLog("is : " +profile.getFirstName());
}
cursor.close();
return profiles;
}
cursor.close();
return null;
}
答案 0 :(得分:0)
问题似乎是,您在循环之前仅创建Profile
对象的一个实例,并且仅将此实例添加到循环中的列表中。
因此,请如下更改代码:
public ArrayList getAllProfile()
{
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USER, null);
if (cursor != null)
{
ArrayList<Profile> profiles = new ArrayList<>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext() )
{
Profile profile = new Profile(); // create a new instance in your loop, instead only creating one instance before the loop
profile.setId(cursor.getInt(cursor.getColumnIndex(ID)));
profile.setFirstName(cursor.getString(cursor.getColumnIndex(FIRST_NAME)));
profile.setLastName(cursor.getString(cursor.getColumnIndex(LAST_NAME)));
profile.setFatherName(cursor.getString(cursor.getColumnIndex(FATHER)));
profile.setAge(cursor.getInt(cursor.getColumnIndex(AGE)));
profile.setEmail(cursor.getString(cursor.getColumnIndex(EMAIL)));
profile.setGender(cursor.getInt(cursor.getColumnIndex(GENDER)));
profile.setPhoneNumber(cursor.getString(cursor.getColumnIndex(PHONE_NUMBER)));
profiles.add(profile);
App.myLog("is : " +profile.getFirstName());
}
cursor.close();
return profiles;
}
if(cursor != null)
{
cursor.close();
return null;
}
}