更新方法不保存更改 Sqlite 数据库(Android Studio)
Update method not saving changes Sqlite Database (Android Studio)
我正尝试在我的数据库上完成我的更新方法,但我没有得到结果。
我的应用程序没有显示任何错误,我可以访问我要编辑的对象,我可以更改数据,但更改不会保存。
我已经在另一个应用程序中尝试过此代码并且工作正常,但现在我无法在编辑要更改的数据时保存我的更改。
任何人都可以伸出援手吗?
我的数据库:
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();
}
}
我的更新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();
}
}
也许您认为 table 没有更新,因为您看到提示信息更新失败。
但是,您检查以显示正确消息的条件不正确。
方法 update()
returns 受影响(更新)的行数或 0
如果更新失败。
它永远不会 returns -1
.
像这样更改您的代码:
if (result == 0) {
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}
此外,在 btnUpdate
的侦听器中,您定义了一个 MateriaPrima
对象,您将其传递给 updateData()
而无需设置其属性。
你从哪里得到 Codigo
属性?
改为:
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();
});
我能够通过重写我的更新方法来更正错误:
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();
}
感谢大家的帮助
我正尝试在我的数据库上完成我的更新方法,但我没有得到结果。 我的应用程序没有显示任何错误,我可以访问我要编辑的对象,我可以更改数据,但更改不会保存。 我已经在另一个应用程序中尝试过此代码并且工作正常,但现在我无法在编辑要更改的数据时保存我的更改。 任何人都可以伸出援手吗?
我的数据库:
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();
}
}
我的更新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();
}
}
也许您认为 table 没有更新,因为您看到提示信息更新失败。
但是,您检查以显示正确消息的条件不正确。
方法 update()
returns 受影响(更新)的行数或 0
如果更新失败。
它永远不会 returns -1
.
像这样更改您的代码:
if (result == 0) {
Toast.makeText(context, R.string.strFailed, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, R.string.strSucess, Toast.LENGTH_SHORT).show();
}
此外,在 btnUpdate
的侦听器中,您定义了一个 MateriaPrima
对象,您将其传递给 updateData()
而无需设置其属性。
你从哪里得到 Codigo
属性?
改为:
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();
});
我能够通过重写我的更新方法来更正错误:
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();
}
感谢大家的帮助