GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

Erro ao inserir dados no SQLite

Tags: #<Tag:0x00007fb8695bd258> #<Tag:0x00007fb8695bce70>

Olá.
Estou com problemas nesse projeto pessoal. Ao tentar salvar um produto, o SQLite não curtiu o Price, que está definido como float, mas ao salvar no db (que está definido como REAL, até alterei para NUMERIC para verificar se resolvia, mas sem sucesso), ele não salva no db. Segue a mensagem de erro, bem como o ProductActivity.

public class ProductActivity extends AppCompatActivity {

    private EditText txtBarCode;
    private EditText txtName;
    private EditText txtQuantity;
    private EditText txtPrice;
    private Button btnSave;

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

        txtBarCode = (EditText) findViewById(R.id.txtProductBarCode);
        txtName = (EditText) findViewById(R.id.txtProductName);
        txtQuantity = (EditText) findViewById(R.id.txtQuantity);
        txtPrice = (EditText) findViewById(R.id.txtProductPrice);

        btnSave = (Button) findViewById(R.id.btnSaveProduct);

        this.clickSaveButtonListener();

    }

    private void clickSaveButtonListener() {

        this.btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Product productToSave = getDataProductFromForm();

                if (productToSave != null) {
                    ProductController productController = new ProductController(ConnectionSQLite.getInstance(ProductActivity.this));
                    long idProduct = productController.saveProductController(productToSave);

                    if (idProduct > 0)
                        Toast.makeText(ProductActivity.this, "Product successfully saved!", Toast.LENGTH_LONG).show();
                    else {
                        Toast.makeText(ProductActivity.this, "An exception occurred while trying to save the product. " +
                                "Remember, all fields are required and with the appropriate data type.", Toast.LENGTH_LONG).show();
                    }

                } else {
                    Toast.makeText(ProductActivity.this, "Please, fill in all fields.", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private Product getDataProductFromForm(){

        Product product = new Product();

        if (!this.txtBarCode.getText().toString().isEmpty())
            product.setId(Integer.parseInt(this.txtBarCode.getText().toString()));
        else {
            return null;
        }

        if (!this.txtName.getText().toString().isEmpty())
            product.setName(this.txtName.getText().toString());
        else {
            return null;
        }

        if (!this.txtQuantity.getText().toString().isEmpty()) {
            int productQuantity = Integer.parseInt(this.txtQuantity.getText().toString());
            product.setStockQuantity(productQuantity);
        }
        else {
            return null;
        }

        if (!this.txtPrice.getText().toString().isEmpty()) {
            float productPrice = Float.parseFloat(this.txtPrice.getText().toString());
            product.setPrice(productPrice);
        }
        else {
            return null;
        }

        return product;

    }
}

2021-02-16 17:58:35.318 4929-4929/com.gustavojw.blproductsapp E/SQLiteLog: (1) near ")": syntax error
2021-02-16 17:58:35.320 4929-4929/com.gustavojw.blproductsapp E/SQLiteDatabase: Error inserting =18.5
    android.database.sqlite.SQLiteException: near ")": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO product() VALUES (?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1597)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1468)
        at com.gustavojw.blproductsapp.DAO.ProductDAO.saveProductDAO(ProductDAO.java:29)
        at com.gustavojw.blproductsapp.controller.ProductController.saveProductController(ProductController.java:16)
        at com.gustavojw.blproductsapp.activities.ProductActivity$1.onClick(ProductActivity.java:50)
        at android.view.View.performClick(View.java:7161)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
        at android.view.View.performClickInternal(View.java:7133)
        at android.view.View.access$3500(View.java:804)
        at android.view.View$PerformClick.run(View.java:27416)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:241)
        at android.app.ActivityThread.main(ActivityThread.java:7617)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)

Pelo erro sua query tá assim:

INSERT INTO () VALUES(?)
android.database.sqlite.SQLiteException: near “)”: syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO product() VALUES (?)

Vc esqueceu de colocar as colunas. Exemplo:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);

Pior que estou usando uma DAO. Segue o código do método DAO para salvar os dados na db:

public long saveProductDAO(Product product){

        SQLiteDatabase dataBase = connectionSQLite.getWritableDatabase();

    try{

        ContentValues values = new ContentValues();
        values.put("", product.getId());
        values.put("", product.getName());
        values.put("", product.getStockQuantity());
        values.put("", product.getPrice());

        long insertedProductId = dataBase.insert("product", null, values);
        return insertedProductId;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return 0;

}

Resolvido. Não havia especificado qual era a coluna q receberia tal valor. A solução ficou assim:

values.put("id", product.getId());
values.put("name", product.getName());
values.put("quantityInStock", product.getStockQuantity());
values.put("price", product.getPrice());
//