Search code examples
androidsqliteandroid-listviewandroid-cursor

ListView is not updating the entries from array


I am trying to fiddle with sqlite database,listview and arraylist.On a click of button the data gets inserted into database,and then using cursor the data is extracted by 'select' and ideally should be reflected in the listview.Following is the code for the same:

The following activity takes place in onCreate method:

    lstitem=new ArrayList<String>();
    listadap=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lstitem);
    l1=(ListView)findViewById(R.id.listView1);
    l1.setAdapter(listadap);
    l1.setVisibility(View.VISIBLE);

And on button click the code is supposed to do following things,off which it is inserting values very well but I guess something is wrong with Cursor object and its instantiation using 'rawQuery' not sure about it:

     MainActivity.myDataBase.openDatabase("/data/data/packagename/databases/tablename", null,MainActivity.myDataBase.OPEN_READWRITE);
     MainActivity.myDataBase.execSQL("INSERT INTO " +
                      MainActivity.tablename +
                        " Values ('"+ finalnumber +"','"+ name +"','"+ message +"','"+ event +"','"+ ldate +"');");
     Cursor cu = MainActivity.myDataBase.rawQuery("SELECT Name FROM " + MainActivity.tablename + " WHERE Date =" + ldate +";" , null);

     cu.moveToFirst();
     Log.d("first rec", cu.toString());
     while(cu.isAfterLast())
     {
        try{
            lstitem.add(cu.getString(0));
            Log.d("first list item",lstitem.get(0)); //this is not returning any value in logcat.
            Log.d("first rec", cu.getString(0));// this is returning garbled value in logcat
            cu.moveToNext();
            }
        catch(Exception e)
            {
            e.printStackTrace();
        }
     }

Kindly clarify whether where my code is misbehaving.Thanks.


Solution

  • Call notifyDataSetChanged() on your Adapter.

    yourListAdapter.notifyDataSetChanged();