gpt4 book ai didi

android - 如何将游标返回的对象存储到数组列表中?

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:55 25 4
gpt4 key购买 nike

我在游标的帮助下从 sqlite 数据库中获取对象。我想将它们存储到数组列表中。问题是我事先不知道返回数据的大小。那么如何将它们放入数组列表中呢?

代码:

public Student findAll()
{
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", null
);

if(cursor.moveToNext())
return new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age")));
return null;
}

Main:

ArrayList<Student> studentArrayList = new ArrayList<Student>();

studentArrayList.add(dao.findAll()); //doing this will only return the first object from the database

最佳答案

根据ArrayList docs

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

这将帮助您更好地理解 ArrayList。

public List<Student> findAll() {
List<Student> studentArrayList = new ArrayList<Student>();
db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select sid, name, age from t_student", null
);



while(cursor.moveToNext()) {
studentArrayList.add(new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age"))));
}

return studentArrayList ;
}

ArrayList<Student> studentArrayList = new ArrayList<Student>();

studentArrayList=findAll();

关于android - 如何将游标返回的对象存储到数组列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11602944/

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