Error in delete button

Asked

Viewed 111 times

2

Good Afternoon, I made a delete method in my database and called it in my Activity, only my problem is that when I click on the button it doesn’t happen anything, and doesn’t present me any error in Logcat, someone would know to help me?

Dbhelper:

package Base;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DbHelper extends SQLiteOpenHelper {

    private static final String NAME_BASE = "Resultados";
    private static final int VERSION_BASE = 1;

    public DbHelper(Context context) {

        super(context, NAME_BASE, null, VERSION_BASE);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlCreateTableResultado = "CREATE TABLE resultado("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "TimeCasa TEXT,"
                + "TimeFora TEXT,"
                + "GolsCasa INTEGER,"
                + "GolsFora INTEGER"+")";

        db.execSQL(sqlCreateTableResultado);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sqlDropTableResultado = "DROP TABLE resultado";

        db.execSQL(sqlDropTableResultado);

        onCreate(db);

    }

    public void insertResultado(Esporte resultado){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues valores = new ContentValues();
        valores.put("TimeCasa", resultado.getNomeTimeUm());
        valores.put("TimeFora", resultado.getNomeTimeDois());
        valores.put("GolsCasa", resultado.getValorUm());
        valores.put("GolsFora", resultado.getValorDois());

        db.insert("resultado", null, valores);

        db.close();
    }

    public List<Esporte> selectTodosResult(){
        List<Esporte> listResult = new ArrayList<Esporte>();
        SQLiteDatabase db = getReadableDatabase();

        String sqlSelectTodosResult = "SELECT * FROM resultado";

        Cursor c = db.rawQuery(sqlSelectTodosResult, null);

        if (c.moveToFirst()){
            do {
                Esporte onde = new Esporte();
                onde.setId(c.getInt(0));
                onde.setNomeTimeUm(c.getString(1));
                onde.setNomeTimeDois(c.getString(2));
                onde.setValorUm(c.getInt(3));
                onde.setValorDois(c.getInt(4));

                listResult.add(onde);
            }
            while (c.moveToNext());
        }

        db.close();
        return listResult;
     }

    public void delete(){
        SQLiteDatabase db = getReadableDatabase();
        String sqlSelectTodosResult = "DELETE * FROM resultado";
        Cursor c = db.rawQuery(sqlSelectTodosResult, null);
    }

}

My Activity:

package com.allsport.miyonic.allsport;

import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.ListView;
        import java.util.List;

        import Base.DbHelper;
        import Base.Esporte;

        import static android.os.FileObserver.DELETE;

public class ResultSimples extends AppCompatActivity {

    private ListView lista;
    private Button apagar;

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

        lista = (ListView) findViewById(R.id.ListaTimes);
        apagar = (Button) findViewById(R.id.btndeletar);

        apagar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DbHelper dd = new DbHelper(ResultSimples.this);
                dd.delete(); // É necessário passar o parâmetro
            }
        });
    }

    @Override
    public void onResume(){
        super.onResume();

        DbHelper dbhe = new DbHelper(this);
        List<Esporte> listaResultPartida = dbhe.selectTodosResult();

        ArrayAdapter<Esporte> adp = new ArrayAdapter<Esporte>(this, android.R.layout.simple_list_item_1, listaResultPartida);

        lista.setAdapter(adp);
    }


}

Thank you...

  • The error is on the line of dd.delete();

  • Nathan the dd.delete(); this without parameter, see that it asks for a number like long public void delete(long id).

  • So @Guilhermenascimento could put dd.delete(1); that would be a long kind right? (in this case)

  • 1

    @Nathan depends, the ID has to come from somewhere, play a random number there will not make sense, the id has to exist in the bank

2 answers

5

First of all, d.delete("resultado", "id = " + id, null); is a security breach. You are allowing an attack by calling SQL Injection. This third parameter exists precisely for this, avoid SQL Injection. Even if in this specific case it is impossible to practice an injection, it is better to be careful and not accustomed to writing SQL sentences in this way.

So this code should be

public void delete(long id){
    SQLiteDatabase d = getWritableDatabase();
    if (id > -1) {
        String[] whereArgs = new String[] { String.valueOf(id) };
        d.delete("resultado", "id=?", whereArgs);        
    }
    d.close();
}

The problem pointed out in the question is that the method delete inside DbHelper, asks as parameter a long and nothing is being passed

apagar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DbHelper dd = new DbHelper(ResultSimples.this);
        dd.delete(PARAMETRO_AQUI); // É necessário passar o parâmetro
    }
});
  • 1

    How is it possible to inject SQL into a situation like this?

  • That’s not the problem, @ramaral. It is accustomed to doing so and end up compromising other places (or even other applications) where there really may be risks of injection. I don’t know if you agree with me, but even if it’s harmless at first, it could lead to some future problems. I really expressed myself (fast and) badly in the reply, I will edit =)

3

The error is in the parameter that the method delete are receiving

public void delete(long id){
    SQLiteDatabase d = getWritableDatabase();
    if (id > -1) {
        d.delete("resultado", "id = " + id, null);
    }
    d.close();
}

He’s expecting a long and you’re not passing anything, it generates the error.

When it’s time to call

dd.delete();

You must pass this id together or remove this parameter there from the method.


Update ():

Leave your method this way

public void delete(){
   SQLiteDatabase d = getWritableDatabase();
   d.delete("resultado", null, null);
   d.close();
}

And then you can call

dd.delete();
  • But if I remove this parameter, how could I call the function in the database to delete the table when I click the button?

  • That one id works like the WHERE clause in SELECT, if you want to delete the whole table, then I see no need to pass a id, you can pass as null and remove the parameter there from the method

  • @Nathan Posted an Update (Solution): in my answer for you to understand better.

  • still giving error when I click the button...

  • Same error? You took the IF also there from the method or just removed the parameter?

  • @Nathan In my answer I forgot to put the d. before the close, it has to look like this: d.close();

  • java code is right... it is giving me error in onclick I will edit the question and take a look please

  • Ready @Leonardo Dias

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.