我在游标的帮助下从sqlite数据库中获取对象。我想将它们存储在一个arraylist中。问题是我不提前知道我返回数据的大小。那么如何将它们放入arraylist?
代码:
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
答案 0 :(得分:7)
每个ArrayList实例都有一个容量。容量是用于存储列表中元素的数组的大小。它始终至少与列表大小一样大。当元素添加到ArrayList时,其容量会自动增加。除了添加元素具有恒定的摊销时间成本这一事实之外,未指定增长政策的细节。
这将帮助您更好地理解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();
谢谢:)
答案 1 :(得分:2)
试试这个:
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 ;
}
答案 2 :(得分:1)
你的问题不是:
if(c.moveToNext()) {
// ...
}
你必须使用while循环进行迭代:
while(c.moveToNext()) {
// ...
}
因此:
List<Student> myList = new ArrayList<String>();
Cursor c = ...
while(c.moveToNext()) {
myList.add(new Student(cursor.getInt(cursor.getColumnIndex("sid")), cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age")));
}
c.close();