my database cant update
this is my updateMethod
public long updateInfo(ModelInsertInfo modelInsertInfo) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,modelInsertInfo.getId());
values.put(KEY_yearWater, modelInsertInfo.getYearWater());
values.put(KEY_MonthWater, modelInsertInfo.getMonthWater());
values.put(KEY_DayWater, modelInsertInfo.getDayWater());
values.put(KEY_HourWater, modelInsertInfo.getHourWater());
values.put(KEY_MinWater, modelInsertInfo.getMinWater());
return db.update(TABLE_Insert_Info, values, "" + KEY_ID + "= " + modelInsertInfo.getId() + "", null);
}
and this codes in activity
ModelInsertInfo modelInsertInfo = new ModelInsertInfo();
ActionInsertInfo actionInsertInfo = new ActionInsertInfo(getApplicationContext());
modelInsertInfo.setYearWater(yearFC);
modelInsertInfo.setMonthWater(monthFC);
modelInsertInfo.setDayWater(day1);
modelInsertInfo.setHourWater(hour);
modelInsertInfo.setMinWater(min);
long check = actionInsertInfo.updateInfo(modelInsertInfo);
if (check > 0) {
Snackbar.make(null, ":)", Snackbar.LENGTH_SHORT).show();
}else
{
Toast.makeText(ActivityDetails.this, ":(((", Toast.LENGTH_SHORT).show();
}
when select button return -1 and i use external database
thanks for help me :)
Related
I need to pass data from DeleteLayout to update data in historyActivity which will update once I edit the data.It does not throw any error but my data is not updating after editing. What can be done to pass data between activities and update the database.
My updateDatamethod in DatabaseHelper looks like this:
public boolean updateData(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, goalDate);
contentValues.put(Col3, goalWeight);
contentValues.put(Col4, currentWeight);
db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
return true;
}
Deletelayout
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deletelayout);
GoalDate = findViewById(R.id.goalDate2);
CurrentWeight = findViewById(R.id.weighGoal2);
GoalWeight = findViewById(R.id.weightCurrent2);
goalD = findViewById(R.id.goalDateInput);
goalW = findViewById(R.id.goalWeightInput);
currentW = findViewById(R.id.currentWeightInput);
imageView = findViewById(R.id.imageShow);
data = myDB.getListContents();
deleteB = findViewById(R.id.deleteB);
updateB = findViewById(R.id.updateButton);
// Entered information from the user are set to the respective variables.
int numRows = data.getCount();
j = new Intent(DeleteLayout.this, historyActivity.class);
if (numRows == 0) {
Toast.makeText(DeleteLayout.this, "Nothing in the db", Toast.LENGTH_LONG).show();
} else {
int i = 0;
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5));
gWt = user.getGoalWeight();
cWt = user.getCurrentWeight();
gDt = user.getGoalDate();
GoalDate.setText(gDt);
GoalWeight.setText(gWt);
CurrentWeight.setText(cWt);
deleteB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.deleteContent(GoalDate.getText().toString(), GoalWeight.getText().toString(), CurrentWeight.getText().toString());
startActivity(j);
}
});
updateB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean myUpdate = myDB.updateData(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
if(myUpdate == true){
Toast.makeText(DeleteLayout.this, "Data updated", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DeleteLayout.this, "Data not updated", Toast.LENGTH_SHORT).show();
}
startActivity(j);
}
});
}
}
}
Issues
One issue you have is that you are not asking for any changes to be made.
Additionally you are always assuming that a row or rows have always been update, i.e. you are not checking to see if any updates have been performed.
The SQliteDatabase update method returns an int that has the number of rows that have been updated. If none are updated then it will return 0.
Explanation
Consider that goalDate is 2019-01-01 and goalWeight is 100 and currentWeight is 200, then you are saying
update
goalDate to 2019-01-01 and
goalWeight to 100 and
currentWeight to 200
for the row(s) where
goalDate is 2019-01-01 and
goalWeight is 100 and
currentWeight is 200
Fix
Instead of :-
public boolean updateData(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, goalDate);
contentValues.put(Col3, goalWeight);
contentValues.put(Col4, currentWeight);
db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
return true;
}
What you want is something along the lines of :-
public boolean updateData(String goalDate, String goalWeight, String currentWeight, String newGoaldate, String newGoalWeight, String newCurrentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, newGoalDate);
contentValues.put(Col3, newGoalWeight);
contentValues.put(Col4, newCurrentWeight);
if (db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight}) > 0) {
return true;
}
return false;
}
The first 3 parameters are the original values (used to locate the row to be updated), the second set are the values to be used to update the located row or rows).
Extra
Ideally you should also change :-
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
to :-
String where = Col2 + "=? AND " + Col3 + "=? AND " + Col4 +"=?";
I have this code:
{
String SQL_CREATE_BOOKS_TABLE = "CREATE TABLE " + BooksContract.BooksEntry.TABLE_NAME + " ("
+ BooksContract.BooksEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT + " TEXT NOT NULL, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PRICE + " DECIMAL NOT NULL DEFAULT 0, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY + " INTEGER NOT NULL, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER + " TEXT, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PHONE + " INTEGER );";
db.execSQL(SQL_CREATE_BOOKS_TABLE);
}
Even though I didn't set the supplier to be not null, if I don't type it in my editText when I click the save button my app crashes. Also even though quantity is set to default 0, if I don't type any quantity it still crashes. why?
EditorActivity:
private void insertBooks() {
String productString = productName.getText().toString().trim();
String priceString = price.getText().toString().trim();
int price = Integer.parseInt(priceString);
String quantityString = quantity.getText().toString().trim();
int quantity = Integer.parseInt(quantityString);
String supplierString = supplier.getText().toString().trim();
String phoneString = supplierPhone.getText().toString().trim();
int phone = Integer.parseInt(phoneString);
BooksDbHelper dbHelper = new BooksDbHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT, productString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE, priceString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, quantityString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER, supplierString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PHONE, phoneString);
long newRowId = db.insert(BooksContract.BooksEntry.TABLE_NAME, null, values);
if (newRowId == -1) {
// If the row ID is -1, then there was an error with insertion.
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved with row id: " + newRowId, Toast.LENGTH_SHORT).show();
}
}
CatalogActivity:
private void insertBooks() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT, "Walks with men");
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE, 10.00);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, 2);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER, "Amazon");
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PHONE, 727213658);
long newRowId = db.insert(BooksContract.BooksEntry.TABLE_NAME, null, values);
}
Use this code in your insertBooks() method to avoid NumberFormatException:
String productString = productName.getText().toString().trim();
String priceString = price.getText().toString().trim();
double price = 0.0;
try {
price = Double.parseDouble(priceString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
String quantityString = quantity.getText().toString().trim();
int quantity = 0;
try {
quantity = Integer.parseInt(quantityString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
String supplierString = supplier.getText().toString().trim();
String phoneString = supplierPhone.getText().toString().trim();
Why is phone INTEGER?
Note:
The create table code you posted is probably part of the onCreate() method in your class that extends SQLiteOpenHelper.
The onCreate() method was executed the 1st time you ran the app and created the table. Since then you may have altered the columns either by type or name, or even inserted or deleted columns, but all these changes were made only in your code and not in the table. The onCreate() method has never again been triggered.
So if any of the above applies to you:
Uninstall the app from the emulator/device so that the database is deleted and run again your app to recreate it as it should be.
I want to update a row in a SQL table in a column (`click'). I can see the row in debug but it isn't recognized.
If click==0 so change to click==1.
Does someone know what is my mistake?
My code is:
public void UpdateClicked2(String name, int table) {
ContentValues values = new ContentValues();
String selectQuery = "SELECT * FROM " + MySQLiteGUESTS.TABLE_NAME
+ " WHERE " + MySQLiteGUESTS.COLUMN_TABLE + "=" + table;
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GuestInfo comment = cursorToComment(cursor);
if (comment.getName().toString() != name)
cursor.moveToNext();
else {
if (comment.getClick() == 1) {
values.put(MySQLiteGUESTS.COLUMN_CLICK, 0);
} else
values.put(MySQLiteGUESTS.COLUMN_CLICK, 1);
}
}
String newString = MySQLiteGUESTS.COLUMN_NAME + " = " + name;
database.update(MySQLiteHelper.TABLE_NAME, values, newString, null);
}
if (comment.getName().toString() != name)
Instead of this
Use this:
if (comment.getName().toString().equals(name))
{
}
So I am trying to delete only one instance of values from my SQLite database using the where args of db.update and db.delete in my app but it seems to delete and update all the matching ones. I only want to update or delete one. How do I do it? I tried using cursors but my implementation seems wrong. Help?
public long updateData(String oldFood, String oldCalorie, String newFood, Float newCalorie, String newDate) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(helper.FOOD_COLUMN, newFood);
contentValues.put(helper.CALORIE_COLUMN, newCalorie);
contentValues.put(helper.DATE, newDate);
String[] columns = {helper.UID, helper.FOOD_COLUMN, helper.CALORIE_COLUMN, helper.DATE};
//long id = db.update(helper.TABLE_NAME, contentValues, helper.FOOD_COLUMN + " = ? AND " + helper.CALORIE_COLUMN + " = ?", new String[]{oldFood, oldCalorie});
Cursor cursor = db.query(helper.TABLE_NAME, columns, null, null, null, null, null);
Information current = new Information();
int uidIndex = cursor.getColumnIndex(helper.UID);
int cid = cursor.getInt(uidIndex);
int foodIndex = cursor.getColumnIndex(helper.FOOD_COLUMN);
int calorieIndex = cursor.getColumnIndex(helper.CALORIE_COLUMN);
float oldCalorieFloat = Float.parseFloat(oldCalorie);
if (oldFood == cursor.getString(foodIndex) && oldCalorieFloat == cursor.getFloat(calorieIndex)) {
long id = db.update(helper.TABLE_NAME, contentValues, helper.FOOD_COLUMN + " = ? AND " + helper.CALORIE_COLUMN + " = ?", new String[]{oldFood, oldCalorie});
db.close();
return id;
}
long id=0;
return id;
}
I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;