0

//当点击Random和NextTORandom按钮的Onclick时如何使用cursor.moveToPosition(x)进行迭代?

//这是我的 Mydatabase.java 代码。该文件用于从数据库中获取单行。

public Cursor getData(int _id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor =db.rawQuery("Select * from '"+DB_TABLE+"' where _id = ?", new    String[] { String.valueOf(_id)}); 

    if (cursor != null)
    {
    cursor.moveToFirst();
    }

    return cursor;

// 这是我的 MyActivity.java 代码

public void onClick(View v) {
cur=db.getData(position);
int firstpos=1; 
int lastpos=4;

switch(v.getId())
{

case R.id.NextToRandom :
{ 

if (cur != null && cur.getCount()> 0 && position < cur.getCount() && position != cur.getCount()){
cur.moveToPosition(position);
textView1.setText(""+cur.getString(1));// Display Columns 
position++;
cur.moveToNext();
}
if(cur.moveToPosition(lastpos))
{

cur.moveToPosition(firstpos); 
textView1.setText(""+cur.getString(1));
}
/*else
{
cur.moveToPosition(position); 
textView1.setText(""+cur.getString(1));
position++;
}*/


//display details code

}
break;
case R.id.random:
{
Random r = new Random();
int rnum = r.nextInt(max - min + 1) + min;
cur=db.getData(rnum);
setNewData(rnum);
}
}


}

private void setNewData (int xyz) {



}

//我想通过单击 Random_back_button、Random_button 和 Random_Next_button 来遍历所有记录。如何实施?

4

2 回答 2

1

您可以像这样遍历游标:

Cursor cursor = ...; // get cursor from somewhere
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext) {
    // your code here
}

游标确实提供随机访问,因此如果您需要访问特定行,请调用cursor.moveToPosition(int).

于 2013-08-06T18:35:44.970 回答
-1

官方代码在这里↓↓↓↓↓↓↓↓↓↓↓↓↓↓

    // ------------------------------
    // android.database.DatabaseUtils
    // ------------------------------

    public static void dumpCursor(Cursor cursor, StringBuilder sb) {
        sb.append(">>>>> Dumping cursor " + cursor + "\n");
        if (cursor != null) {
            int startPos = cursor.getPosition();

            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                dumpCurrentRow(cursor, sb);
            }
            cursor.moveToPosition(startPos);
        }
        sb.append("<<<<<\n");
    }
于 2017-09-21T09:57:24.560 回答