mardi 22 décembre 2015

How do I use one button to swap between adding and deleting data from an sqlite database?

I have an sqlite database that collects data from the user and can delete it as well. Here is it being created:

db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATA TEXT UNIQUE) ");

Here's the code for the adding data and removing data

public boolean insertData(String data) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cValues = new ContentValues();
    cValues.put(Col_2, data);
    long result = db.insert(TABLE_NAME, null, cValues);
    if (result == -1)
        return false;
    else
        return true;
}


 public boolean deleteData(String data){
    SQLiteDatabase db = this.getWritableDatabase();
    long result = db.delete(TABLE_NAME, "DATA = ?", new String[]{data});
    ContentValues cValues = new ContentValues();
    if (result == 0)
        return false;
    else
        return true;
}

Here is the java button im trying to use

public void changeData(){
    favBtn.setOnClickListener(
            new View.OnClickListener(){
                @Override
                    public void onClick(View v){
                       boolean isInserted = myDB.insertData(textView.getText().toString());

                    if(isInserted == true)
                        Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();

                    else
                        Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
                        myDB.deleteData(textView.getText().toString());


                }
            }
    );
}

The issue is that when this button is clicked it adds data but then will not remove said data. It will just continue playing the "added data" toast and add said data to the database- there is a unique constraint with the data column but I'm not really sure what I'm doing wrong or missing as I understand it should not be added twice. It should remove the data if that is already added and vice versa.

Aucun commentaire:

Enregistrer un commentaire