Abdalrahman Makahleh Abdalrahman Makahleh - 6 months ago 13
Android Question

I want to retrieve data from SQL lite as an array of object using android

public List<Report> selectAll() {
List<Report> list = new ArrayList<Report>();
Report report = new Report();
int id,Temp;
String Date,Tank,Tankuse;
SQLiteDatabase db = this.getWritableDatabase();
String query = "select ID, Date,Temp,Tank,Tankuse from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
if (cursor.moveToFirst()) {

id=cursor.getInt(0);
report.setID(id);
Date=cursor.getString(1);
report.setDateTime(Date);
Temp=cursor.getInt(2);
report.setTemp(Temp);
Tank=cursor.getString(3);
report.setTank(Tank);
Tankuse=cursor.getString(4);
report.setTank(Tankuse);
list.add(report);
while (cursor.moveToNext());
}
return list;
}


how i can retrieve the data as array of objects this is my first time Using SQL lite i use 3 tires architecture in asp.net but i don't know how that's work here so can some tell me how or what i should change in my code to make it return an array of object ?

Answer

Example:

 public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
    do {
        Contact contact = new Contact();
        contact.setID(Integer.parseInt(cursor.getString(0)));
        contact.setName(cursor.getString(1));
        contact.setPhoneNumber(cursor.getString(2));
        // Adding contact to list
        contactList.add(contact);
    } while (cursor.moveToNext());
}

// return contact list
return contactList;
}
Comments