• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to add SQLite rows to an ArrayList<>

Fred Pino

Lurker
Hello,
Could anyone please help me and tell me how can I add SQLite rows into an ArrayList ?


Java:
Select_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

final String GetInfo = "SELECT "
        +TableClass.ID_Column+", "+
        TableClass.Name_Column+", "+
        TableClass.FirstName_Column+", "+
        TableClass.Age_Column+
        " FROM " + TableClass.TABLE_NAME +
        " WHERE " + TableClass.Name_Column + " LIKE '%Carlos%' AND " + TableClass.Mail_Column +
        " LIKE 'gmail' ";

        SQLiteDatabase db = DBH.getReadableDatabase();
        Cursor check = db.rawQuery(GetInfo, null);

        try {
        do {
        check.moveToFirst();
        ArrayList<String> info = new ArrayList<>();

        Carbons.add(
        check.getInt(check.getColumnIndex(TableClass.Name_Column)),
        check.getInt(check.getColumnIndex(TableClass.FirstName_Column)),
        check.getString(check.getColumnIndex(TableClass.Age_Column)));
        } while (check.moveToNext());

        }catch (Exception e){
        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); }
        }
        });
 
Assuming you want to create an Array of Strings, as you've declared

Code:
ArrayList<String> info

then just write

Code:
info.add(check.getString(check.getColumnIndex(TableClass.Name_Column))

Assuming TableClass.Name_Column is a string value.

If you want to create an ArrayList containing objects corresponding to the rows in your database table, then you'll have to create a class that represents all the data fields in that table. E.g.

Code:
class Person {
  private String firstName;
  private String surName;
  private Integer age;
}

then create Person objects using rows retrieved from the database, and declare an ArrayList like this

Code:
ArrayList<Person> people = new ArrayList<>;
 
Back
Top Bottom