Question

i made a listView with custom adapter its getting data from DB and binding it to list view, Adapter Picks number of records very well but it keep showing last record for all entries , for example if there are 5 records retrieved from db the list view will show last record for five time.

here is the code

Activities SetAct = new Activities();
final ArrayList<Activities> sData = new ArrayList<Activities>();
try{
    SQLiteDatabase db = openOrCreateDatabase("iTimeDB", MODE_PRIVATE, null);
    Cursor c2 = db.rawQuery("SELECT * FROM Activities", null);   // WHERE ID = '" +ID+"'"
    for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
        String title =c2.getString(c2.getColumnIndex("Title"));
        String details =c2.getString(c2.getColumnIndex("Details"));
        String time =c2.getString(c2.getColumnIndex("Time"));
        String ref= c2.getString(c2.getColumnIndex("Ref"));
        String matter =c2.getString(c2.getColumnIndex("Matter"));
        String date = c2.getString(c2.getColumnIndex("Date"));
        String ID = c2.getString(c2.getColumnIndex("ID"));
        String IMEI1 =  c2.getString(c2.getColumnIndex("IMEI"));
        SetAct.setTitle(title);
        SetAct.setDetails(details);
        SetAct.setMatter(matter);
        SetAct.setRef(ref);
        SetAct.setTime(time);
        SetAct.setDate(date);
        SetAct.setID(ID);
        sData.add(SetAct);
        }
    c2.close();
    db.close();
    }
    catch(Exception e){
        e.printStackTrace();
        Log.v("YYY", e.toString());
    }
    final ListView listView = (ListView) findViewById(R.id.listView1);
    listView.setAdapter(new CustomListAdapter(this, sData));
Was it helpful?

Solution

Remove below line from outside for loop Add it in inside for loop

Activities SetAct = new Activities();

Example

for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
       Activities SetAct = new Activities();
       String title =c2.getString(c2.getColumnIndex("Title"));
       // Remaining as it is..
}

OTHER TIPS

use like this.

I use the following pattern to read the query result.

  SQLiteDatabase db = new DbHelper().getWritableDatabase();
    String sql = "SELECT ...";
    String[] args = ...;
    Cursor cs = db.rawQuery(sql, args);
    while (cs.moveToNext()) {
        // cs.getXxx(0), cs.getXxx(1)
    }
    cs.close();
    db.close();

DbHelper is a class that I extend from SQLiteOpenHelper

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top