How to Print SQLite entries into a ListView?

I am having some trouble learning the ins and outs of the SQLite world. I have some code that is allowing me to enter data into a DB. But what i want to do is return this data into a listview. At the moment all I could figure out to do was to have each row printed in a toast after a new entry is added. Can someone please show me how to alter my code to print it in a listview? Or to even look at my code and see that i am going about it in the right way. Thanks

This is the code i am using which calls a display record function

com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
      do
      {
         DisplayRecord(c);
      } while (c.moveToNext());
}
db.close();

This is the display record function

public void DisplayRecord(Cursor c)
        {
            Toast.makeText(this,"id: " + c.getString(0) + "\n" +"Item: " + c.getString(1) + "\n" +"Litres:  " + c.getString(2),Toast.LENGTH_SHORT).show();
        }

I know i need to change the second function but i dont know how to do that to make it print into a listview

Last updated:11/5/2014 3:10:03 AM

1 Answers

Mark Devid
Mark Devid

this is the code of getting data from database and insert into Arraylist and insert into arrayAdapter and than display it in listview .

i just done some editing in your existing code.


com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
            db.open();
 
            ArrayList<String> data_list = new ArrayList<String>();
            ListView lv = (ListView)findViewById(R.id.listView1);
            Cursor c = db.getAllRecords();
            if (c.moveToFirst())
            {
                do
                {
                    data_list.add(c.getString(0));
                    DisplayRecord(c);
                } while (c.moveToNext());
            }
            ArrayAdapter<String> aa = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data_list);
            lv.setAdapter(aa);

lv - is the object of ListView.

Answer