Android Cursor不会循环,应用程序冻结

时间:2012-07-29 06:23:29

标签: android

所以在这里,我有这个应用程序从数据库中检索记录,我从我的数据库中有5个条目,并使用此代码检索它;

Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);

之后我循环它以检索我的数据库中的数据pero行;

c.moveToFirst();
while(!c.isAfterLast())
{
 //Some code to put records per column in to a Patient Object 
 c.moveToNext();
}

所以我的问题是,当它进入循环时,我的模拟器冻结,当我试图将每条记录显示到一个日志中时,我不会因为它自己已经冻结而模拟它。

有人可以告诉我这个问题,这个问题对我来说真的很新鲜

修改

是的已经尝试了baya和ofir建议..他们已经解决了但是我在使用这个循环代码进行迭代时遇到了这个空错误

Cursor c = dbHelper.retrieveAllData();

                c.moveToFirst();

                while(c.moveToNext())
                {
                    Log.d("dbcheck",Integer.toString(c.getPosition()));
                    //Log.d("dbcheck",c.getString(c.getColumnIndex("firstname")));
                    //Log.d("dbcheck",c.getString(c.getColumnIndex("lastname")));
                    **p.setFname(c.getString(c.getColumnIndex("firstname")));**
                    p.setMi(c.getString(c.getColumnIndex("middleinitial")));
                    p.setLname(c.getString(c.getColumnIndex("lastname")));
                    p.setAddr(c.getString(c.getColumnIndex("address")));
                    p.setAge(c.getInt(c.getColumnIndex("age")));
                    p.setMed_history(c.getString(c.getColumnIndex("med_history")));
                    p.setPat_status(c.getString(c.getColumnIndex("status")));
                    patientList.add(p);

                }

我在p.setFname()行上有一个空异常错误..我不知道它是如何变为null的,实际上我已经使用注释掉的代码显示了它。

2 个答案:

答案 0 :(得分:4)

试试吧,

         Cursor c = dbconnection.rawQuery("SELECT * from Patients", null);
    if (c.getCount() > 0) {

        Patient p;

        while(c.moveToNext) {

            //initialize ur object to store new patient info.
            p = new Patient();
            p.setFname(c.getString(c.getColumnIndex("firstname")));

            //add newly created patient to ur list
            patientList.add(p);

        }
    }
c.close();

答案 1 :(得分:0)

尝试这样做:

    // return all columns
    Cursor cursor = mDb.query(Patients, null, null, null, null, null, null);

    if ((cursor != null) && (cursor.getCount() > 0)) {
       while(cursor.moveToNext()){

    //Some code to put records per column in to a Patient Object 

    }
                    cursor.close();
   }
相关问题