1

I'm using SimpleCursorAdapter to fetch data from database and display it in ListView. please anyone tell me how to select/delete one or more list items from that list. Or at least tell me how to fetch the data from database using ArrayAdapter to display it in ListView.

Tutorial will be best practice.

Thanks in advance.

nidhi_adiga
  • 1,114
  • 1
  • 16
  • 27
vinay
  • 11
  • 1
  • 6
  • http://androidzoo.wordpress.com/2011/10/28/working-with-listview-in-android-customize-listview-add-item-via-a-button-click-and-also-clickable-each-button-in-each-row/ – Raghunandan Mar 27 '13 at 07:43

1 Answers1

0

please anyone tell me how to select/delete one or more list items from that list.

So you need to get id of every row to be able to delete proper item from database. Problem with deleting only one item from List at the time is not too tricky, just create some OnItemClickListener or ContextMenu and offer to User delete option. Then if you are using some CursorAdapter, you automatic get rowId of selected item from long id parameter of OnItemClick method. In the case of ContextMenu you can get id from AdapterView.ContextMenuInfo.

Problem is the case if you want to delete more that one, there and usage of any listener or ContextMenu is not enough and efficient. You should decide to create own row of ListView where you will have CheckBox and then you can simply delete more that one row. You go throw List and every row that have CheckBox checked delete from database and make List refresh. This is my first idea that came to my head.

Or at least tell me how to fetch the data from database using ArrayAdapter to display it in ListView.

If you want to use ListAdapter(ArrayAdapter, BaseAdapter etc.) so now you need to fetch list of records from database. I suggest you create own ListAdapter subclass to get more control over Adapter. Here i recommend you to create own Object that will represent your table in database where properties of Object are equal to columns in table. Then simply fetch List from database. I will give you pseudocode below.

Example:

public List<OwnObject> getAll() {
   List<OwnObject> items = new ArrayList<OwnObject>();
   OwnObject o = null; 
   Cursor c = null;
   try {
      db = helper.getReadableDatabase(); // or created some method as open();
      String query = "select * from TableName";
      c = db.rawQuery(query, null);
      if (c.moveToFirst()) {
         do {
            o = new OwnObject();
            o.setProperty1(c.getString(c.getColumnIndex("Column1")));
            o.setProperty2(c.getString(c.getColumnIndex("Column2")));
            o.setProperty3(c.getString(c.getColumnIndex("Column3")));
            ...
            items.add(o);

         } while (c.moveToNext());
      }
      return items;
   }
   finally {
      if (c != null) {
         c.close();
      }
      // close also db
   }
}
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106