Database refusing to delete item

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.

But when I ran the code, the Item refused to delete.

InputContract.java

public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;

public class TaskEntry implements BaseColumns {
    public static final String TABLE = "tasks";

    public static final String COL_TASK_TITLE = "title";
}
}

InputDbHelper.java

public class InputDbHelper extends SQLiteOpenHelper {

public InputDbHelper(Context context) {
    super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + "    ( " +
            InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";

    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
    onCreate(db);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams. FLAG_FULLSCREEN);

    setContentView(R.layout.activity_main);
    init();
    mHelper = new InputDbHelper(this);
    updateUI();
    int no = list.getAdapter().getCount();
    amt.setText("" + no);
    setupListViewListener();
}
private void setupListViewListener() {
    list.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapter,
                                               View item, int pos, long id) {
                    // Remove the item within array at position
                    items.remove(pos);
                    // Refresh the adapter
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    db.delete(InputContract.TaskEntry.TABLE,
                            InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
                            new String[]{"Name of entry you want deleted"});
                    db.close();
                    updateUI();
                    itemsAdapter.notifyDataSetChanged();
                    // Return true consumes the long click event (marks it handled)
                    return true;
                }

            });
}

public void init(){
    ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.hide();

    list = (ListView)findViewById(R.id.list);

    displayText = (TextView)findViewById(R.id.displayText);
    amt = (TextView)findViewById(R.id.amt);
    itms = (TextView)findViewById(R.id.itms);

    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    list.setAdapter(itemsAdapter);

    l1 = (ConstraintLayout)findViewById(R.id.one);
    l2 = (ConstraintLayout)findViewById(R.id.two);



    Typeface regular = Typeface.createFromAsset(getAssets(),  "fonts/regular.ttf");
    Typeface bold = Typeface.createFromAsset(getAssets(),  "fonts/bold.ttf");

    amt.setTypeface(bold);
    itms.setTypeface(regular);
    displayText.setTypeface(regular);

}

public void add(View v){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.dialog, null);
    dialogBuilder.setView(dialogView);

    final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);

    dialogBuilder.setTitle("Add Item");
    dialogBuilder.setMessage("Enter text below");
    dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String txt = edt.getText().toString();
            items.add(txt);
            SQLiteDatabase db = mHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(InputContract.TaskEntry.COL_TASK_TITLE,   txt);
            db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            db.close();
            updateUI();
            int no = list.getAdapter().getCount();
            amt.setText("" + no);
        }
    });
    dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            //pass
        }
    });
    AlertDialog b = dialogBuilder.create();
    b.show();

}


public void play(View v){
    Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
    Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);

    l1.startAnimation(fadeOut);
    l1.setVisibility(View.GONE);
    l2.setVisibility(View.VISIBLE);
    l2.startAnimation(fadeIn);

    String[] array = new String[items.size()];
    final String[] mStringArray = items.toArray(array);

    final android.os.Handler handler = new android.os.Handler();
    handler.post(new Runnable() {

        int i = 0;

        @Override
        public void run() {
            displayText.setText(mStringArray[i]);
            i++;

            if (i == mStringArray.length) {
                handler.removeCallbacks(this);
            } else {
                handler.postDelayed(this, TIME);
            }
        }
    });



}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}


private void updateUI() {

    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
            new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (itemsAdapter== null) {
        itemsAdapter= new ArrayAdapter<>(this,  android.R.layout.simple_list_item_1,
                taskList);
        list.setAdapter(itemsAdapter);
    } else {
        itemsAdapter.clear();
        itemsAdapter.addAll(taskList);
        itemsAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

}

In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?

Answer

I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.

So try using :-

    private void setupListViewListener() {
        list.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapter,
                                               View item, int pos, long id) {

                    String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
                    // Remove the item within array at position
                    items.remove(pos);
                    // Refresh the adapter
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    db.delete(InputContract.TaskEntry.TABLE,
                            InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
                            new String[]{title_of_row_to_delete}); //<<<<<<<<
                    db.close();
                    updateUI();
                    itemsAdapter.notifyDataSetChanged();
                    // Return true consumes the long click event (marks it handled)
                    return true;
                }

            });
    }

This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.

//<<<<<<<< indicates changed lines.

Leave a Reply

Your email address will not be published. Required fields are marked *