Search code examples
androidlistviewonlongclicklistener

Listview onlongclick delete


Database

package sg.edu.rp.c346.todolist;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by User on 26/12/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    // final is a constant

    public static final String DATABASE_NAME = "mylist.db";
    public  static final String TABLE_NAME = "mylist_data";
    public static final String COL1 = "ID";
    public static final String COL2 = "ITEM1";

    public DatabaseHelper(Context context){
        super (context, DATABASE_NAME, null , 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = " CREATE TABLE " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT," +
               " ITEM1 TEXT)";
                db.execSQL(createTable);



    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXITS "+ TABLE_NAME);
        onCreate(db);




    }
    public boolean addData(String item1) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item1);


        long result = db.insert(TABLE_NAME, null, contentValues);

        //if date as instered incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }
        /**
         * Return all the data from database
         * @return
         */
        //cursor is know indirect subclass
        public Cursor getListContent() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data =db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
        return data;


    }
    /**
     * Returns only the ID that matches the name passed in
     * @param name
     * @return
     */
    public  Cursor getItemID(String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query = "SELECT "+ COL1 +" FROM "+TABLE_NAME+
                " WHERE "+ COL2 +" = '"+ name +"'";
        Cursor data = db.rawQuery(query,null);
        return data;
    }


    /**
     * Delete from database
     * @param id
     * @param name
     */
    public void deleteName(int id, String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL1 + " = '"
                + id + "'"+" AND " + COL2 + "= '" + name + "'";
        db.execSQL(query);

    }


}
package sg.edu.rp.c346.todolist;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by User on 26/12/2017.
 */

public class ListDataActivity extends AppCompatActivity {


    DatabaseHelper myDB;
    ListView listView;
    ArrayAdapter<String> listAdapter;
    Button button;
    Button btnRefresh;
    String selectedName;
    int selectedID;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_layout);

        listView = (ListView) findViewById(R.id.listView);
        button = (Button) findViewById(R.id.add);
        btnRefresh = (Button) findViewById(R.id.refresh);
        myDB = new DatabaseHelper(this);

        // get the intent extra from the ListDataActivity
        Intent receivedIntent=getIntent();

        // now get the itemID we passed as an extra
        selectedID=receivedIntent.getIntExtra("id",-1);//NOTE -1 it just a default values

        // now get the name we passed as an extra
        selectedName=receivedIntent.getStringExtra("name");


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ListDataActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ListDataActivity.this, ListDataActivity.class);
                startActivity(intent);
            }
        });


        //populate an ArrayList<String> from the databases and then view it
        final ArrayList<String> theList = new ArrayList<>();
        Cursor data = myDB.getListContent();



        if (data.getCount() == 0) {
            Toast.makeText(ListDataActivity.this, "The database was empty", Toast.LENGTH_LONG).show();
        } else {
            while (data.moveToNext()) {
                // get the value from the database in column 1
                // then add it to the ArrayList
                theList.add(data.getString(1));
                // create the list adapter and set the adapter
                listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
                listView.setAdapter(listAdapter);

                // set an onItemClickListen to the listView
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        String name = adapterView.getItemAtPosition(i).toString();


                        Cursor data = myDB.getItemID(name); //get the id assosicated with the name
                        int itemID = 1;
                        while (data.moveToNext()) {
                            itemID = data.getInt(0);
                        }
                        if (itemID > -1) {
                            Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
                            editScreenIntent.putExtra("id", itemID);
                            editScreenIntent.putExtra("name", name);
                            startActivity(editScreenIntent);
                        } else {
                            Toast.makeText(ListDataActivity.this, "No ID assosciated", Toast.LENGTH_SHORT).show();
                        }

                    }
                });


            }
        }
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    myDB.deleteName(selectedID,selectedName);
                    theList.remove(i);
                    listAdapter.notifyDataSetChanged(); //change to your adapter instance here
                    Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });

        }
        }

How to remove/delete using function setOnItemLongClickListener from database my code seem doesn't delete .

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            myDB.deleteName(selectedID,selectedName);
            Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
            return true;
        }
});

This code is the database Activity

   public void deleteName(int id, String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL1 + " = '"
                + id + "'"+" AND " + COL2 + "= '" + name + "'";
        db.execSQL(query);

    }


}

Solution

  • As you are deleting data from your database but the list attached to adapter still holds the data, you have to remove from that position and notify your adapter.
    Try this code:

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            myDB.deleteName(theList.get(i));
            theList.remove(i); 
            listAdapter.notifyDataSetChanged();
            Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
            return true;
        }
    });
    

    If you want to delete selected item you can use:

    public void deleteName(String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL2 + "= '" + name + "'";
        db.execSQL(query);
    
    }
    

    and call deleteName() as:

    myDB.deleteName(theList.get(i));