简体   繁体   中英

Update method not saving changes Sqlite Database (Android Studio)

I'm trying to complete my update method on my database, but I'm not getting the results. My app doesn't show any error, I can access the object I want to edit, I'm able to change the data, but the changes are not saved. I've tried this code in another app and worked ok, but now I'm not able to save my changes when I edit the data I want to alter. Can anyone please give a hand?

My Database:

package com.myapplication.umdocededaisy;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MyDatabase extends SQLiteOpenHelper {

    List<MateriaPrima> listaProduto = new ArrayList<>();

    private final Context context;
    private static final String DATABASE_NAME = "BancoDoceDaisy.db";
    private static final int DATABASE_VERSION = 4;

    //Estruturas das Tabelas do banco de dados:

    //Tabela dos produtos - materia prima:
    private static final String TABLE_PRODUTO = "materia_prima";
    private static final String COLUMN_CODIGO = "codigo";
    private static final String COLUMN_PRODUTO = "produto";
    private static final String COLUMN_VALOR = "valor";
    private static final String COLUMN_QTD = "quantidade";
    private static final String COLUMN_TIPO = "tipo";
    //------------------------------------------------------

    MyDatabase(Context context) {
        super(context, DATABASE_NAME,null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE "+ TABLE_PRODUTO +
                " (" + COLUMN_CODIGO + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_PRODUTO + " TEXT, " +
                COLUMN_VALOR + " FLOAT, " +
                COLUMN_QTD + " FLOAT, " +
                COLUMN_TIPO + " TEXT); ";
        db.execSQL(query);
    }

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

    void addMateriaPrima(MateriaPrima materiaPrima) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_PRODUTO, materiaPrima.getProduto());
        cv.put(COLUMN_VALOR, materiaPrima.getValor());
        cv.put(COLUMN_QTD, materiaPrima.getQuantidade());
        cv.put(COLUMN_TIPO, materiaPrima.getTipo());

        long result = db.insert(TABLE_PRODUTO, null, cv);
        if (result == -1) {
            Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(context, R.string.strAddSucess, Toast.LENGTH_SHORT).show();
        }
        db.close();
    }

    Cursor readAllData(){
        String query = "SELECT * FROM " + TABLE_PRODUTO;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null){
            cursor = db.rawQuery(query,null);
        }
        return cursor;
    }

    public List<MateriaPrima> buscaProduto() {
        String columns[] = {COLUMN_CODIGO, COLUMN_PRODUTO, COLUMN_VALOR, COLUMN_QTD, COLUMN_TIPO};
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(TABLE_PRODUTO, columns, null, null, null,null, null);

        while (cursor.moveToNext()) {
            int index1 = cursor.getColumnIndex(COLUMN_CODIGO);
            int codigo = cursor.getInt(index1);
            int index2 = cursor.getColumnIndex(COLUMN_PRODUTO);
            String produto = cursor.getString(index2);
            int index3 = cursor.getColumnIndex(COLUMN_VALOR);
            float valor = cursor.getFloat(index3);
            int index4 = cursor.getColumnIndex(COLUMN_QTD);
            float quantidade = cursor.getFloat(index4);
            int index5 = cursor.getColumnIndex(COLUMN_TIPO);
            String tipo = cursor.getString(index5);
            MateriaPrima produtos = new MateriaPrima(codigo, produto, valor, quantidade, tipo);
            listaProduto.add(produtos);
        }
        return listaProduto;
    }

    void updateData(MateriaPrima materiaPrima) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_PRODUTO, materiaPrima.getProduto());
        cv.put(COLUMN_VALOR, materiaPrima.getValor());
        cv.put(COLUMN_QTD, materiaPrima.getQuantidade());
        cv.put(COLUMN_TIPO, materiaPrima.getTipo());

        long result = db.update(TABLE_PRODUTO, cv, " codigo=?",  new String[]{String.valueOf(materiaPrima.getCodigo())});
        if (result == -1) {
            Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
        }
        db.close();
    }

    void deleteOneRow(String materiaPrima) {
        SQLiteDatabase db = this.getWritableDatabase();
        long result = db.delete(TABLE_PRODUTO, COLUMN_CODIGO + " codigo", new String[]{String.valueOf(materiaPrima)});
        if (result == -1) {
            Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
        }
        db.close();
    }

    void deleteAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_PRODUTO);
        db.close();
    }
}

My Update Activity

package com.myapplication.umdocededaisy;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateActivity extends AppCompatActivity {

    EditText editCodigo2, editProduto2, editValor2, editQuantidade2, editTipo2;
    Button btnUpdate, btnDelete;
    String codigo, produto, valor, quantidade, tipo;
    InputMethodManager inputManager;


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

        //Declarações objetos:
        editCodigo2 = findViewById(R.id.editCodigo2);
        editProduto2 = findViewById(R.id.editProduto2);
        editValor2 = findViewById(R.id.editValor2);
        editQuantidade2 = findViewById(R.id.editQuantidade2);
        editTipo2 = findViewById(R.id.editTipo2);
        btnUpdate = findViewById(R.id.btnUpdate);
        btnDelete = findViewById(R.id.btnDelete);
        inputManager = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);

        getAndSetIntentData();

        ActionBar ab = getSupportActionBar();
        if(ab != null){
            ab.setTitle(produto);
        }

        btnUpdate.setOnClickListener(v -> {
            MateriaPrima materiaPrima = new MateriaPrima();
            MyDatabase myDB = new MyDatabase(UpdateActivity.this);
            produto = editProduto2.getText().toString().trim();
            valor = editValor2.getText().toString().trim();
            quantidade = editQuantidade2.getText().toString().trim();
            tipo = editTipo2.getText().toString().trim();
            myDB.updateData(materiaPrima);
            inputManager.hideSoftInputFromWindow(btnUpdate.getWindowToken(), 0);
            recreate();
        });

        btnDelete.setOnClickListener(v -> confirmDeleteDialog());

    }

    void getAndSetIntentData() {
        if (getIntent().hasExtra("codigo") && getIntent().hasExtra("produto") && getIntent().hasExtra("valor") &&
                getIntent().hasExtra("quantidade") && getIntent().hasExtra("tipo")){
            //Getting data:
            codigo = getIntent().getStringExtra("codigo");
            produto = getIntent().getStringExtra("produto");
            valor = getIntent().getStringExtra("valor");
            quantidade = getIntent().getStringExtra("quantidade");
            tipo = getIntent().getStringExtra("tipo");

            //Setting data:
            editCodigo2.setText(codigo);
            editProduto2.setText(produto);
            editValor2.setText(valor);
            editQuantidade2.setText(quantidade);
            editTipo2.setText(tipo);

        }else{
            Toast.makeText(this, R.string.strData0, Toast.LENGTH_SHORT).show();
        }
    }

    void confirmDeleteDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.strMsgDelete) + " " + produto);
        builder.setMessage(getString(R.string.strMsgDelete ) + " " + produto + " ?");
        builder.setPositiveButton(getString(R.string.strYes), (dialog, which) -> {
            MyDatabase myDB = new MyDatabase(UpdateActivity.this);
            myDB.deleteOneRow(codigo);
            finish();
        });
        builder.setNegativeButton(getString(R.string.strNo), (dialog, which) -> {

        });
        builder.create().show();
    }
}

Maybe you think that the table is not updated because you see the toast with the message that the update failed.

But, the condition that you check in order to show the correct message is not correct.
The method update() returns either the number of the rows affected (updated) or 0 if the update failed.
It never returns -1 .

Change your code like this:

if (result == 0) {
    Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}

Also, in the listener of btnUpdate you define a MateriaPrima object which you pass to updateData() without setting its properties.
Where do you get the Codigo property from?

Change to this:

btnUpdate.setOnClickListener(v -> {
    MateriaPrima materiaPrima = new MateriaPrima();
    MyDatabase myDB = new MyDatabase(UpdateActivity.this);

    materiaPrima.setCodigo(?????); // you must set this property   

    materiaPrima.setProduto(editProduto2.getText().toString().trim());
    materiaPrima.setValor(editValor2.getText().toString().trim());
    materiaPrima.setQuantidade(editQuantidade2.getText().toString().trim());
    materiaPrima.setTipo(editTipo2.getText().toString().trim());

    myDB.updateData(materiaPrima);
    inputManager.hideSoftInputFromWindow(btnUpdate.getWindowToken(), 0);
    recreate();
});

I was able to correct the error by rewriting my update method:

void updateData(String row_id, String produto, String valor, String quantidade, String tipo){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_PRODUTO, produto);
        cv.put(COLUMN_VALOR, valor);
        cv.put(COLUMN_QTD, quantidade);
        cv.put(COLUMN_TIPO, tipo);

        long result = db.update(TABLE_PRODUTO, cv, "codigo=?", new String[]{row_id});
        if(result == -1){
            Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
        }

        db.close();
    }

Thanks for all the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM