gpt4 book ai didi

java - Arraylist 无法与游标查询一起正常工作

转载 作者:行者123 更新时间:2023-12-01 10:04:36 24 4
gpt4 key购买 nike

我有一个游标,它从下面的数据库查询中返回 5 个最新结果。

    public Cursor totaldistance(){
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.DSNM, DatabaseHelper.SDATE };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, DatabaseHelper._ID + " DESC limit 5");
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

然后我将返回的游标值分配给下面的数组列表。它工作正常,接受 arrayList 缺少最新的数据库记录值。例如,我可以在数据库中有 4 个值,但第二个最新值被分配给数组列表中的位置 0。我不确定是我的游标查询还是 while 语句有问题。有人知道吗?谢谢!

        List<String> distancearray = new ArrayList<String>();
distancearray.add("0");
distancearray.add("0");
distancearray.add("0");
distancearray.add("0");
distancearray.add("0");
int i = 0;

while(DistanceArray.moveToNext()){
String uname = DistanceArray.getString(DistanceArray.getColumnIndex("distance"));

distancearray.set(i, uname);
i++;
}

根据下面的建议,我更新了我的代码。它现在正在从数据库中检索第一个结果,但不会循环遍历下一个 4。运行下面的代码后,我的 arraylist 应该读取 10,8,6,1,0,但实际结果是 10,10,10,10 ,0.它正在重复第一个检索到的值。如何修复 do while 操作以将正确的结果写入数组?谢谢!

        List<String> distancearray = new ArrayList<String>();
distancearray.add(0, "0");
distancearray.add(1, "0");
distancearray.add(2, "0");
distancearray.add(3, "0");
distancearray.add(4, "0");
Cursor cursor = dbManager.totaldistance();
do{
String uname = DistanceArray.getString(DistanceArray.getColumnIndex("distance"));
distancearray.set(i, uname);
Log.i("Graph", "Value i = " + i);
Log.i("Graph", "Array value = " + uname);
i++;
}while ((cursor.moveToNext()));

最佳答案

我认为您在调用 cursor.moveToFirst(); 时“丢失”了一行

public Cursor totaldistance(){
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.DSNM, DatabaseHelper.SDATE };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, DatabaseHelper._ID + " DESC limit 5");
if (cursor != null) {
// Here you are pointing to the first row of the cursor
// you need to add this row content into your list
cursor.moveToFirst();
}
return cursor;
}

因此,当您在上一个方法中调用 moveToFirs() 时,将所有行添加到列表的代码应如下所示

List<String> distancearray = new ArrayList<String>();
Cursor cursor = dbManager.totaldistance();
do{
distancearray.add(cursor.getString(cursor.getColumnIndex("distance")));
}while ((cursor.moveToNext()));

// Be sure here to have at least the 5 desired elements into the list
while(distancearray.size() < 5){
distancearray.add("0");
}

关于java - Arraylist 无法与游标查询一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36544841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com