【问题标题】:How to get assign values to an arraylist item inside a cursor iterator如何将值分配给游标迭代器内的数组列表项
【发布时间】:2017-12-12 07:37:49
【问题描述】:

我试图将一个变量分配给游标内的 ArrayList 项,但它总是返回最后一个值。这是下面的代码。

从数据库中获取价值

 public ArrayList<Bean> getPendingData(String s) {
    SQLiteDatabase db = getWritableDatabase();
    String[] columns = {name};
    String[] selectionArgs = {s};
    Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null);
    cursor.moveToFirst();       
    ArrayList<Bean> pending = new ArrayList<>();
    String index0 = null;
    Bean bean;
    bean = new Bean();
    while(!cursor.isAfterLast()) {
        index0 = cursor.getString(cursor.getColumnIndex(name));
        bean.setQuestion(index0);
        pending.add(bean);
        cursor.moveToNext();
    }

    cursor.close();
    return pending;
}

Bean.java

public class Bean {
public static int id; // ans
public static String score;
public static String logo;
public static String image;

public static String getQuestion() {
    return question;
}

public static void setQuestion(String question) {
    Bean.question = question;
}

public static String question;
public static String description;
public static String option_three;
public static String OptionFour;

}

【问题讨论】:

    标签: android sqlite arraylist cursor


    【解决方案1】:

    你应该在 while 块中初始化你的 bean:

    while(!cursor.isAfterLast()) {
        Bean bean = new Bean();
        index0 = cursor.getString(cursor.getColumnIndex(name));
        bean.setQuestion(index0);
        pending.add(bean);
        cursor.moveToNext();
    }
    

    原因是 Java 通过引用使用对象,因此您总是将相同的对象添加到“待处理”数组中,但在接下来的迭代中,您正在更改该对象的值,所以最终您的值是最后一次迭代。

    【讨论】:

    • Igor 没有任何变化,它只返回最后一个值。
    • 你能试试这个代码吗?而不是 while 块:do { Bean bean = new Bean(); String index0 = cursor.getString(cursor.getColumnIndex(name)); bean.setQuestion(index0); pending.add(bean); } while (cursor.moveToNext()); 您也可以在此处添加断点来调试每次迭代中给出的值。
    【解决方案2】:

    cursor.isAfterLast() 在光标位于最后一行时返回true。添加!(不)意味着执行直到它不在光标的末尾。

    所以while(!cursor.isAfterLast()){} 表示while循环将遍历到光标的最后一条记录。

    使用此方法获取从游标返回的所有行。

    if (cursor != null) {
            if (cursor.getCount() > 0) {
                if (cursor.moveToFirst()) {
                    homeClassesArrayList = new ArrayList<>();
                    do {
                       // fetching data
                    } while (cursor.moveToNext());
                }
            }
    }
    

    【讨论】:

    • Dharmistha 没有任何变化,它只返回最后一个值。
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2021-02-11
    • 1970-01-01
    • 2021-02-10
    • 2021-06-22
    • 2015-06-27
    • 1970-01-01
    • 2014-10-16
    相关资源
    最近更新 更多