How to add data in android sqlite? - android

I want to add my new values in the previous one at a specific id, but every time when I want to add it created data on a new id rather than added with the previous one.
Here is the method of my databasehelper class:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = null,previous2 = null,previous3= null;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
while(res.moveToNext()) {
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
}
contentValues.put(COL_2, value1 + previous1);
contentValues.put(COL_3, value2 + previous2);
contentValues.put(COL_4, value3 + previous3);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;}
here is the method of mainactivity class
private void AddAllData() {
btnaddall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.addalldata(edit1.getText().toString(),
edit2.getText().toString(),
edit3.getText().toString());
if (isInserted = true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
}

try this:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = "0",previous2 = "0",previous3= "0";
long result = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
if(res.getCount()>0){
res.moveToFirst();
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
try{
contentValues.put(COL_2, Integer.parseInt(value1) + Integer.parseInt(previous1));
contentValues.put(COL_3, Integer.parseInt(value2) + Integer.parseInt(previous2));
contentValues.put(COL_4, Integer.parseInt(value3) + Integer.parseInt(previous3));
result = db.update(TABLE_NAME, contentValues, "id = ?", new String[]{"1"});
}catch(Exception e){
result = -1;
}
if (result == -1)
return false;
else
return true;
}else{
contentValues.put(COL_2, value1);
contentValues.put(COL_3, value2);
contentValues.put(COL_4, value3);
result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
if there is no record in the database then insert a new record using db.insert otherwise update the existing record by using db.update

try res.moveToFirst().This will move your cursor to first position so that furthur checking starts from the first row.

Related

Database is not updating data from one activity to another

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 +"=?";

dataBase does not update

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 :)

How do I use contentvalue for inserting (Custom)ARRAY list in SQlite?

ERROR- am getting as type mistmatch.
Here is my code-Please help
public void addDetailDescription(List<Detail> detailList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < detailList.size(); i++) {
Log.e("vlaue inserting==", "" + detailList.get(i));
values.put(DETAIL_ID, String.valueOf(detailList.get(i)));
values.put(COLUMN_HEADING, String.valueOf(detailList.get(i)));
values.put(COLUMN_IMAGE_DETAIl, String.valueOf(detailList.get(i)));
values.put(COLUMN_DETAIL, String.valueOf(detailList.get(i)));
values.put(DETAIL_DESCRIPTION_ID, String.valueOf(detailList.get(i)));
}
db.insert(DESCRIPTION_DETAIL_TABLE, null, values);
db.close();
}
I think you have to write a function like this and in a for cycle ,call this function for each item of list.
public long SaveUsers(Users users) {
long id = -1;
ContentValues contentValues = null;
try {
contentValues = new ContentValues();
contentValues.put("name", users.getName());
contentValues.put("email", users.getEmail());
contentValues.put("phone", users.getPhone());
contentValues.put("password", users.getPassword());
db=sqliteHelper.getWritableDatabase();
id = db.insert(SqliteHelper.TABLE_USERS, null, contentValues);
} catch (Exception e) {
Log.d("Database Insert","Exception:"+e.getMessage());
} finally {
if(db!=null && db.isOpen())
db.close();
}
return id;
}
In your code, contentValue change every time and finally just the last item will be inserted to database and it's completely wrong.

How to use Correct Conditioning?

Is this the correct query?
DbFertility info = new DbFertility(this);
info.open();
String name = info.getUserInfo();
info.close();
if(name != null){
Intent i = new Intent(this, Create.class);
startActivity(i);
}else{
Intent i2 = new Intent(this, CalendarMain.class);
startActivity(i2);
}
problem: if the name null i want to direct it create class.. my real problem is even my name is empty or not it always direct me to the CalendarMain.(help)
public String getUserInfo() {
String[] columns = new String[]{KEY_USER_ID, KEY_NAME, KEY_AGE, KEY_STATUS};
Cursor c = getOurDatabase().query(TABLE_USER, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_USER_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iAge c.getColumnIndex(KEY_AGE);
int iStatus = c.getColumnIndex(KEY_STATUS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iName) + " " + c.getString(iAge) + c.getString(iStatus) + "\n";
}
return result;
}
Save:
public long createUser(String name, String age, String status) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_AGE, age);
cv.put(KEY_STATUS, status);
return getOurDatabase().insert(TABLE_USER, null, cv);
}
use TextUtils.isEmpty(name), it returns true if the string is null or if its length is equal to zero.
Intent i = null;
if(!TextUtils.isEmpty(name)) {
i = new Intent(this, Create.class);
} else {
i = new Intent(this, CalendarMain.class);
}
startActivity(i);

Android SQLite copy values from table to another table

I'm trying to copy some data in a table and insert into another table. I entered the data into an ArrayList, however, is only copied a given and not all those present. What am I missing?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
final ArrayList<Dettaglio_i> dettaglii = new ArrayList<Dettaglio_i>();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()){
Dettaglio_i e = new Dettaglio_i();
e.data_ = c.getString(0);
e.unita_di_misura = c.getString(1);
dettaglii.add(e);
}
c.close();
ContentValues cv = new ContentValues();
Dettaglio_i e = new Dettaglio_i();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, e.data_);
cv.put(VerTable .U_M, e.unita_di_misura);
boolean inserite = false;
if (!inserite){
long result = db.insert(VerTable .TABLE_NAME, null, cv);
if (result > 0){
inserite = true;
}
}
if (inserite){
}
db.close();
}
Try replacing your code with this:
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String insert = String.format("INSERT INTO %s (%s, %s, %s) ",
VerTable.TABLE_NAME, VerTable.SI_NO, VerTable.DATA, VerTable .U_M);
String select = "SELECT '0', data, unita_di_misura FROM prev WHERE " +
"numero='"+numero_ricevuto+"'";
db.rawQuery(insert+select, null);
db.close();
}

Categories

Resources