Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store object return by a cursor into a arraylist?

Tags:

android

I am taking object from sqlite database with the help of cursor. And I would like to store them into an arraylist. THe problem is that I dont know the size of my returned data in advance. So How do I put them into an arraylist?

code:

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
like image 393
qwr qwr Avatar asked Aug 18 '26 12:08

qwr qwr


1 Answers

According to the 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.

This will help you to understand ArrayList in a better way.

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();
like image 110
SALMAN Avatar answered Aug 20 '26 03:08

SALMAN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!