如何使用游标在android studio中使用SQLite列出表中的所有行

时间:2015-07-11 04:34:47

标签: android sqlite

我正在使用android studio来处理数据库SQLite。 我需要将列表中的所有项目列为列表视图中的项目。我该怎么做。 我知道如何使用cursor.moveToFirst()像这样获取第一个项目

public Rows getRows(){
    String query = "SELECT * FROM "+TABLE_NAME;
    SQLiteDatabase db = getWritableDatabase();
    cursor = db.rawQuery(query,null);
    Rows rows;
    if(cursor.moveToFirst()){
                rows.setcol1(cursor.getString(0));
                rows.setcol2(cursor.getString(1));
                rows.setcol3(cursor.getString(2));
                cursor.close();
            }
    else{
               rows=null;
        }
    return rows;
}

我可以使用cursor.moveToNext()如果是,请给我代码....

2 个答案:

答案 0 :(得分:4)

像这样使用,

public ArrayList<Rows> getRows(){
    String query = "SELECT * FROM "+TABLE_NAME;
    SQLiteDatabase db = getWritableDatabase();
    cursor = db.rawQuery(query,null);
    ArrayList<Rows> list=new ArrayList<Rows>();

    while(cursor.moveToNext()){
          Rows row=new Rows();
          row.setcol1(cursor.getString(0));
          row.setcol2(cursor.getString(1));
          row.setcol3(cursor.getString(2));
          list.add(row);
     }

    cursor.close();
    db.close();
    return list;
}

答案 1 :(得分:1)

String retq="SELECT * FROM information ";
                sql=openOrCreateDatabase("detail.db", MODE_PRIVATE, null);
                Cursor c=sql.rawQuery(retq, null);
                c.moveToFirst();
                do
                {   
                    id=c.getInt(0); 
                    String nam=c.getString(1);
                    String dob=c.getString(2);
                    String qualification=c.getString(3);
                    String gender=c.getString(4);
                    String mariage=c.getString(5);
                    String experience=c.getString(6);

                    //Toast.makeText(RetrievedActivity.this, c.getString(1), Toast.LENGTH_SHORT).show();
                    s=("id:"+id+"\nname:"+nam+"\nDate Of Birth:"+dob+"\nqualification:"+qualification+"\nGender:"+gender+"\nmariage:"+mariage+"\nexperience:"+experience);              
                    alist2.add(s);   
                     adapter = new ArrayAdapter<String>(Retrieve.this, android.R.layout.simple_list_item_1, alist2);
                     retrieve.setAdapter(adapter);
                }while(c.moveToNext());

                c.close();
                sql.close();

                //adapter.notifyDataSetChanged();
            }});