所以...我一直在制作我自己的应用程序(它就像一个联系人应用程序,只是不同),这部分让我疯了!问题在于,无论何时调用getAllProfiles()方法,它都不会返回任何行,即使在插入新行之后......我做错了什么?
这是帮助类的代码:
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "profiles";
public static final String COLUMN_ID = "id";
public static final String COLUMN_FNAME = "fname";
public static final String COLUMN_LNAME = "lname";
public static final String COLUMN_SORT = "id DESC";
public DBHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// When creating the DB from the start...
db.execSQL("CREATE TABLE profiles(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, fname TEXT, lname TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertProfile(Profile p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("fname", p.getFname());
cv.put("lname", p.getLname());
long ret = db.insert("profiles", null, cv);
if(ret == -1){
Log.d("INSFL", "Insertion Failed!");
}
return true;
}
public Cursor getSpecificProfile(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM profiles WHERE id="+id+"" , null);
return res;
}
public int getNumOfProfiles(){
SQLiteDatabase db = this.getReadableDatabase();
int num = (int)DatabaseUtils.queryNumEntries(db, TABLE_NAME);
return num;
}
public int deleteProfile(Profile p){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("profiles", "id = "+p.getId()+"", null);
}
public ArrayList<Profile> getAllProfiles(){
ArrayList<Profile> profiles = new ArrayList<Profile>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {
COLUMN_ID,
COLUMN_FNAME,
COLUMN_LNAME
};
Cursor res = db.query(TABLE_NAME, projection, null ,null,null,null,COLUMN_SORT);
if(res.getCount() == 0){
Log.d("No Column", "ERROR: NO ROWS RETURNED");
}
if(res.moveToFirst()){
Log.d("BS", "Query Successful");
}
while (!(res.isAfterLast())){
// CHANGE ACCORDINGLY WHEN UPDATING
Profile p = new Profile();
int id = res.getInt(0);
String fname = res.getString(1);
String lname = res.getString(2);
p.setId(id);
p.setFname(fname);
p.setLname(lname);
profiles.add(p);
Log.d("BS", "Entry added successfully!");
}
return profiles;
}
}
答案 0 :(得分:0)
你的while循环无限重复,因为你永远不会将光标移到第一行之外。它将使用第一行的数据创建相同的Profile
个对象,并将它们添加到ArrayList
,直到内存不足为止。
我更喜欢使用for循环语法迭代游标,即使使用空游标也会表现良好:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// do something here
}
或者,在您的代码中,您只需要在cursor.moveToNext()
行之后添加profiles.add(p)
。