Вопрос

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.

Это было полезно?

Решение

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();
}

Другие советы

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?

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();

Solved!

Changes made on onCLick():

public void onClick(DialogInterface dialog,
                                        int whichButton) {

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

                                }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top