Rashid Faheem Rashid Faheem - 2 months ago 7
Android Question

Getting data from Sqlite using custom object ArrayList?

This is code for Employee class.

public class Employee {
String name;
String email;
byte[] picture;

public Employee(String name, String email, byte[] picture) {
this.name = name;
this.email = email;
this.picture = picture;
}
}


And this is my code to get data from Database which is currently not working because i could'nt figure out how to get these three things (String name, email and byte array image) from database. However i have successfully inserted all three things into Sqlite database.

public List<Employee> getImage(){

Employee employee_list = null;
ourDatabase = this.getReadableDatabase();
String[] field = {KEY_Name,KEY_Email,KEY_IMAGE};
Cursor c = ourDatabase.query(DATABASE_TABLE, field, null, null, null, null, null);

int iname = c.getColumnIndex(KEY_Name);
int iemail = c.getColumnIndex(KEY_Email);
int image = c.getColumnIndex(KEY_IMAGE);

for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
String name = c.getString(iname);
String email = c.getString(iemail);
byte[] pic = c.getBlob(image);
employee_list = new Employee(name, email, pic);

}

return employee_list;
}

Answer Source

You are assigning a new Employee object to employee_list each and every time you go through the for-loop

Change your employee_list to this

List<Employee> employee_list = new ArrayList<Employee>();

You can add an object to that list like this at the end of your for-loop

employee_list.add(new Employee(name, email, pic));

The complete code would look like this

public List<Employee> getImage(){

    List<Employee> employee_list = new ArrayList<Employee>();
    ourDatabase = this.getReadableDatabase();
    String[] field = {KEY_Name,KEY_Email,KEY_IMAGE};
    Cursor c = ourDatabase.query(DATABASE_TABLE, field, null, null, null, null, null);

    int iname = c.getColumnIndex(KEY_Name);
    int iemail = c.getColumnIndex(KEY_Email);
    int image = c.getColumnIndex(KEY_IMAGE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        String name = c.getString(iname);
        String email = c.getString(iemail);
        byte[] pic = c.getBlob(image);
        employee_list.add(new Employee(name, email, pic));

    }

    return employee_list;
}

You can then use it like this

List<Employee> employees = getImage();

for (Employee employee : employees) {
    // You can use employee here that represents an Employee entry in the list
}