Search code examples
androidandroid-listviewarraylistsimplecursoradapter

Listview repeating information


I am trying to do a listview with 2 database collumn. I succeded but my problem is that only the first information of the database appears in the listview. If i have x data in the database it will show the x rows in the listview with only the first entry.

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
data = new ArrayList();
    Cursor cursor = mydb.rawQuery("SELECT * FROM projeto", null);

    if (cursor.moveToFirst()) {
        Toast.makeText(getApplicationContext(), "Caminhos:", 3000).show();
        data.clear();
        do {
            data.add(cursor.getString(cursor.getColumnIndex("id_proj")));
            data.add(cursor.getString(cursor.getColumnIndex("nome")));
            map.put("id", data.get(0).toString());
            map.put("nome", data.get(1).toString());
            map.put("hora", "17:00");
            mylist.add(map);
        } while (cursor.moveToNext());


        SimpleAdapter resul = new SimpleAdapter(MainActivity.this, mylist,R.layout.list_item,new String[] {"id", "nome", "hora"}, new int[] {R.id.i, R.id.n, R.id.h});
        lista.setAdapter(resul);

Solution

  • I see two problems in your code:

    • You don't clear data (Like said in a previous answer) so you always get the first two values
    • You always use the same map. Since map is an object you will always modify the same and your list will be fill will one map.

    To fix this two points try this:

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    data = new ArrayList();
    Cursor cursor = mydb.rawQuery("SELECT * FROM projeto", null);
    
    if (cursor.moveToFirst()) {
        Toast.makeText(getApplicationContext(), "Caminhos:", 3000).show();
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            data.clear();
            data.add(cursor.getString(cursor.getColumnIndex("id_proj")));
            data.add(cursor.getString(cursor.getColumnIndex("nome")));
            map.put("id", data.get(0).toString());
            map.put("nome", data.get(1).toString());
            map.put("hora", "17:00");
            mylist.add(map);
        } while (cursor.moveToNext());
    
    
        SimpleAdapter resul = new SimpleAdapter(MainActivity.this, mylist,R.layout.list_item,new String[] {"id", "nome", "hora"}, new int[] {R.id.i, R.id.n, R.id.h});
        lista.setAdapter(resul);