0

I am building an application in which I'm populating data from the database into the listview of my activity. Now, on longItemClick Listener I want to delete that value from the database and update my listview in the app.

Here my code for longClickListener on the listview:

private ListView showing_history;
private ListAdapter mHistoryListAdapter;
private ArrayList<SearchHistoryDetails> searchArrayList;
private ArrayList<SearchHistoryDetails> HistoryObjArrayList;


    mHistoryListAdapter = new ArrayAdapter<String>(this,
            R.layout.mylistlayout, populateList());
    showing_history.setAdapter(mHistoryListAdapter);
    HistoryObjArrayList = new ArrayList<SearchHistoryDetails>();

/**
     * Long tap on listview to delete the selected item from the history
     * list.
     * */
    showing_history
            .setOnItemLongClickListener(new OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> arg0,
                        View arg1, int arg2, long arg3) {
                    final AlertDialog.Builder b = new AlertDialog.Builder(
                            MainActivity.this);
                    b.setIcon(android.R.drawable.ic_dialog_alert);
                    b.setMessage("Delete this from history?");
                    b.setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    Toast.makeText(getApplicationContext(),
                                            "Yes", Toast.LENGTH_LONG)
                                            .show();
                                }
                            });
                    b.setNegativeButton("No",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    dialog.cancel();
                                }
                            });

                    b.show();
                    return true;
                }
            });

By this code I'm inserting data into the database:

/**
 * Inserting the string when user searches for anything into the database.
 * */
public void insertHistory(SearchHistoryDetails paraHistoryDetailsPojoObj) {

    AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(
            this);

    SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj
            .getWritableDatabase();

    ContentValues contentValues = new ContentValues();

    contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING,
            paraHistoryDetailsPojoObj.getHistoryName());
    @SuppressWarnings("unused")
    long affectedColumnId = sqliteDatabase.insert(
            AndroidOpenDbHelper.TABLE_NAME_HISTORY, null, contentValues);

    sqliteDatabase.close();

}

Here is the code from which I'm retrieving data from the database and repopulating it into the list view:

public List<String> populateList() {

    List<String> HistoryNamesList = new ArrayList<String>();

    AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

    SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

    Cursor cursor = sqliteDatabase
            .query(AndroidOpenDbHelper.TABLE_NAME_HISTORY,
                    new String[] { AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING },
                    null, null, null, null, AndroidOpenDbHelper.ID
                            + " DESC");

    startManagingCursor(cursor);

    while (cursor.moveToNext()) {
        String ugName = cursor
                .getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_HISTORY_STRING));

        SearchHistoryDetails histPojoClass = new SearchHistoryDetails();
        histPojoClass.setHistoryName(ugName);

        searchArrayList.add(histPojoClass);

        HistoryNamesList.add(ugName);
    }

    sqliteDatabase.close();

    int history_db = cursor.getCount();

    if (history_db == 0) {
        history_layout.setVisibility(LinearLayout.GONE);
    } else {
        history_layout.setVisibility(LinearLayout.VISIBLE);
    }

    return HistoryNamesList;
}

Retrieving and inserting data all things are perfectly, but deleting of a particular row is not working for me. Right now I have done some action using toast and it is working, what should I do so that, the database data updates after deletion of the row from the listview. Please give me any idea to overcome this problem.

Anupam
  • 3,742
  • 18
  • 55
  • 87

4 Answers4

1

Try this..,.

b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
            DatabaseHandler db=new DatabaseHandler(getApplicationContext());
            db.delete(arg3+"");
            list.remove(position);
            YourActivity.this.adapter.notifyDataSetChanged();
  }
});

and in DatabaseHandler class

public void delete(String id)
{
    SQLiteDatabase db = this.getReadableDatabase();
    db.delete(TABLE_NAME, KEY_ID + "=?", new String[]{id});
    db.close();
}
MKB
  • 7,587
  • 9
  • 45
  • 71
  • Thank you for your answer but, `list.remove(position);` is giving me error, and when I changed it to `list.removeViewAt(position);` I was getting force close, with error **11-15 10:15:10.484: E/AndroidRuntime(11889): java.lang.UnsupportedOperationException: removeViewAt(int) is not supported in AdapterView **. Do you have any idea about this? – Anupam Nov 15 '12 at 04:54
  • Just edited my question. Hope now you can understand my whole problem. – Anupam Nov 15 '12 at 06:38
  • ok make a global variable eg List dataList; and initialize it as dataList=populateList(); and pass it to the adapter mHistoryListAdapter = new ArrayAdapter(this,R.layout.mylistlayout, dataList); and then try my code with dataList.remove(position); – MKB Nov 15 '12 at 07:24
  • Getting force close, caused by `11-15 13:04:17.593: E/AndroidRuntime(18317): Caused by: java.lang.NullPointerException` on onCreate() `11-15 13:04:17.593: E/AndroidRuntime(18317): at com.search.MainActivity.onCreate(MainActivity.java:461)`. Any idea why this is happening, has done all the things as you suggested. – Anupam Nov 15 '12 at 07:38
  • ok lets proceed step by step..,.forgot about listview update..,. IN your first comment, list.remove(position); giving you error, before this we are deleting data from database, is it works for deletion – MKB Nov 15 '12 at 07:46
  • No, I have used `private List HistoryNamesList;`, ran without any error. But nothing is being removed, I have restarted my app and called onCreate method to populate the list. All list items are as it is. – Anupam Nov 15 '12 at 08:04
  • 1
    Got idea from your answer to meet my requirement. Though I was satisfied with your answer. – Anupam Nov 15 '12 at 09:57
0

most proper solution is to use Loaders.. especially CursorLoader along with Content Provider. If Content Provider is an overkill for what you are doing try CursorLoader from commonsware. The update after deletion happens automatically and not in the ui thread which is good. https://github.com/commonsguy/cwac-loaderex.. its pretty easy once you get your head around this.

However if you still want to delete the row as per your code. Just delete it in your longpress listener. But after that refresh the adapter. How to refresh Android listview?

Community
  • 1
  • 1
AndroidGecko
  • 14,034
  • 3
  • 35
  • 49
  • I'm using sqlite for storing the data in my database, you must have figured that out by seeing my code. I'm unable to delete the data from the listview, my first task would be to delete the data selected on button click. Please share something related to this, actually I'm a bit confused from your answer. – Anupam Nov 14 '12 at 12:03
0

To update list.. Firstly call the method where you specified the delete query from builder positive button.

After that delete the item from HistoryNamesList array list

Now the data removed from both database and arraylist but listview still show previous data so you have to notify listview adapter as show below adapter.notifyDataSetChanged(); adapter.notifyDataSetInvalidated();

Karan Rana
  • 638
  • 4
  • 14
  • First I want to delete data from the database then, my next task would be to refresh listview. Please help in deleting the data on Click of positive button of the alert dialog. – Anupam Nov 14 '12 at 12:10
0

Solved!

Changes made on onCLick():

public void onClick(DialogInterface dialog,
                                        int whichButton) {

                                    HistoryNamesList.remove(pos);
                                    ((BaseAdapter) mHistoryListAdapter)
                                            .notifyDataSetChanged();

                                }
Anupam
  • 3,742
  • 18
  • 55
  • 87