near "?": syntax error (code 1): , while compiling: UPDATE and DELETE - android

//deleting query
public void deleteFromQuestion(int questionId) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from Questions where question_id =" + questionId);
}
//updating query
public void updateQuestion(String question, String answerOne, String answerTwo, String answerThree, String answerFour, String correctAnswer, int id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("question", question);
contentValues.put("answer_one", answerOne);
contentValues.put("answer_two", answerTwo);
contentValues.put("answer_three", answerThree);
contentValues.put("answer_four", answerFour);
contentValues.put("correct_answer", correctAnswer);
db.update("Questions", contentValues,"question_id ?", new String[]{String.valueOf(id)});
}
and this is the code of update and delete
//update button code
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
questionStr = String.valueOf(questionET.getText());
answerOneStr = String.valueOf(ansOneET.getText());
answerTwoStr = String.valueOf(ansTwoET.getText());
answerThreeStr = String.valueOf(ansThreeET.getText());
answerFourStr = String.valueOf(ansFourET.getText());
correctAnswerStr = String.valueOf(correctAnsET.getText());
if (questionStr == null || answerOneStr == null || answerTwoStr == null || correctAnswerStr == null) {
Toast.makeText(getApplicationContext(), "Please Fill Fields ", Toast.LENGTH_SHORT).show();
} else {
questionManagerObject.updateQuestion(questionStr, answerOneStr, answerTwoStr, answerThreeStr, answerFourStr, correctAnswerStr, questionId);
Toast.makeText(getApplicationContext(), "Question Updated ", Toast.LENGTH_SHORT).show();
}
}
});
//delete button code
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
questionManagerObject.deleteFromQuestion(questionId);
Toast.makeText(getApplicationContext(), "Question deleted ", Toast.LENGTH_SHORT).show();
}
});
it is supposed to delete with the question id and update with it also these are buttons when click it , it will delete or update ...... this error, what's wrong with this code??

You missed adding "=" before "?".Change it to -
db.update("Questions", contentValues,"question_id = ?", new String[]{String.valueOf(id)});

Related

Insert data to the sqlite database

i am trying to send data to database but i,m getting this error
under this line (db.insertData(fname, lname, pnumber, email, nic)) the error is
insertdata() in databasehelper cannot be applied to fname:java.lang.String fname(android.widget.EditText)
the code is looks like this
` public void onClick(View view) {
if (fname.getText().toString().trim().length() == 0 ||
lname.getText().toString().trim().length() == 0 ||
pnumber.getText().toString().trim().length() == 0 ||
email.getText().toString().trim().length() == 0 ||
nic.getText().toString().trim().length() == 0) {
Toast.makeText(AddEmployee.this, "Complete all fields", Toast.LENGTH_SHORT).show();
} else if (db.insertData(fname, lname, pnumber, email, nic)) {
Toast.makeText(AddEmployee.this, "Employee Register Successfully", Toast.LENGTH_SHORT).show();
fname.setText("");
lname.setText("");
pnumber.setText("");
email.setText("");
nic.setText("");
} else {
Toast.makeText(AddEmployee.this, "Error", Toast.LENGTH_SHORT).show();
}
}`
Database Helper is like this
public boolean insertData(String fname, String lname, Integer pnumber, String email, String nic) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FNAME, fname);
contentValues.put(LNAME, lname);
contentValues.put(PNUMBER, pnumber);
contentValues.put(EMAIL, email);
contentValues.put(NIC, nic);
long result = db.insert(DB_TABLE, null, contentValues);
return result != -1;
}
As I understand you are passing edittext to DB but you have to pass string
So instead of fname write fname.getText().toString() in your else if and this will solve your problem

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

How to delete a row from sqlite table in recycler view items in Android?

I am trying to delete a row in sqlite database from recyclerview adapter. Based on the position of the adapter, I am deleting my row in sqlite like this :
helper = new DBHelper(v.getContext());
database = helper.getWritableDatabase();
//statement = database.compileStatement("update result set ANS =? where SNO ='" + pos + "'");
// statement = database.compileStatement("delete result where SNO ='" + pos + "'");
//statement.bindString(1, ANS);
// statement.executeInsert();
database.delete("result",
"SNO = ? ",
new String[]{Integer.toString(pos)});
Log.d("pos", "" + pos);
// helper.Delete(pos);
database.close();
but it is not deleting in my table, and I am not getting any error. What am I doing wrong?
db = this.getWritableDatabase();
int l;
l = db.delete("result", SNO = ? " , new String[]{pos+1});
if (l > 0) {
Toast.makeText(context, "Removed "+(pos+1), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
db.close();
Here you have pass "pos" so you have not passed right SNO(pos).
Please check SNO is passes on delete query
Try this method ,
public int deleteItem(String id) {
open();
int b = 0;
try {
b = db.delete(DATABASE_TABLE_POST_ITEMS, TAG_PLUS + " = '" + id + "'", null);
} catch (Exception e) {
e.printStackTrace();
}
close();
return b;
}
call this by using this sentence,
holder.img_plus.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbhelper.deleteItem((chatMessageList.get((int) v.getTag()).getListid()));
chatMessageList.remove(position);
notifyDataSetChanged();
}
});

update row by id, cannote resolve sqlite update method

I need to update a row of my database, but I get an error with SQLiteDatabase update method not resolved.
I think this is because of the custom class I had to create:
public class DBAccess {
public static String LOG_TAG = "DBAccess";
private SQLiteDatabase database;
private DBHelper dbHelper;
public DBAccess(Context context) {
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Integer saveVehicle (Vehicle v){
Integer id = null;
if(this.database.isOpen() && !this.database.isReadOnly()){
String queryInsert = DBHelper.QueryAccessoAlDato.INSERT_VEHICLE;
try{
this.database.execSQL(queryInsert, new Object[]{v.getManufacturer(), v.getModel(), v.getPlate(),
v.getKmAmount(), v.getPrezzoGiorno(), v.getPrezzoSettimana(), v.getPrezzoMese(), v.getFuel(),
v.getGruppoMacchina()});
}catch (SQLException e){
Log.e(LOG_TAG, "Si รจ verificato un errore in inserimento " + e.getMessage());
e.printStackTrace();
return null;
}
Then this is the OnClick method of the main activity:
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "Marca: "+this.etManufacturer.getText());
Log.d(LOG_TAG, "Modello: "+this.etModel.getText());
Log.d(LOG_TAG, "Targa: "+this.etPlate.getText());
Log.d(LOG_TAG, "Kilometraggio: "+this.etKmAmount.getText());
Log.d(LOG_TAG, "PrezzoGiorno: "+this.etPrezzoGiorno.getText());
Log.d(LOG_TAG, "PrezzoSettimana: "+this.etPrezzoSettimana.getText());
Log.d(LOG_TAG, "PrezzoMese: "+this.etPrezzoMese.getText());
Log.d(LOG_TAG, "Fuel: "+this.etFuel.getText());
Log.d(LOG_TAG, "Gruppo Macchina: "+this.etGruppoMacchina.getText());
if(!(this.etManufacturer.getText().length() == 0) &&
!(this.etModel.getText().length() == 0) &&
!(this.etPlate.getText().length() == 0) &&
!(this.etKmAmount.getText().length() == 0) &&
!(this.etPrezzoGiorno.getText().length() == 0) &&
!(this.etPrezzoSettimana.getText().length() == 0) &&
!(this.etPrezzoMese.getText().length() == 0) &&
!(this.etFuel.getText().length() == 0) &&
!(this.etGruppoMacchina.getText().length() == 0)
){
Vehicle myVehicle = null;
String manufacturer = this.etManufacturer.getText().toString();
String model = this.etModel.getText().toString();
String plate = this.etPlate.getText().toString();
long KmAmount = Long.parseLong(this.etKmAmount.getText().toString());
int prezzoGiorno = Integer.parseInt(etPrezzoGiorno.getText().toString());
int prezzoSettimana = Integer.parseInt(etPrezzoSettimana.getText().toString());
int prezzoMese = Integer.parseInt(etPrezzoMese.getText().toString());
String fuel = this.etFuel.getText().toString();
String gruppoMacchina = this.etGruppoMacchina.getText().toString();
myVehicle = new Vehicle (manufacturer, model, plate, KmAmount, prezzoGiorno,
prezzoSettimana, prezzoMese,fuel, gruppoMacchina);
Log.d(LOG_TAG, "Hai aggiunto " + myVehicle + "con id" + vehicleID);
DBAccess dba = new DBAccess(this.getApplicationContext());
dba.open();
Log.d(LOG_TAG, "Avvio lettura da db");
if (this.getIntent().hasExtra(Const.ID_VEHICLE)) {
//http://stackoverflow.com/questions/9798473/sqlite-in-android-how-to-update-a-specific-row
ContentValues values= new ContentValues();
values.put(DBHelper.VEHICLE_MANUFACTORER_COLUMN, manufacturer);
values.put(DBHelper.VEHICLE_MODEL_COLUMN, model);
//values.put(DBHelper.KEY_PEDLOCATION, ped_location);
// values.put(DBHelper.KEY_PEDEMAIL, ped_emailid);
// etc etc
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
finish();
}else{
dba.saveVehicle(myVehicle);
Log.d(LOG_TAG, "Ho salvato" + myVehicle);
dba.close();
finish();
So i get the error at line :
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=" + vehicleID, null);
How can I resolve this? Thank you!
First your DBAccess class should extend SQLiteOpenHelper class.
The Update method declaration is as below, the last parameter should be a String array,
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Change your code to as shown below:
dba.update(DBHelper.TABLE_VEHICLE, values, DBHelper.VEHICLE_ID_COLUMN + "=?", new String[]{String.valueOf(vehicleID));

searching in sqlite database

i want to search in database in my android application. when i get a select query if its been or not been in database its show nothing.
this is my code:
final String havy = edtSearch.getText().toString();
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Cursor cursor = G.dataBase.rawQuery("SELECT * FROM db WHERE info_title=" + "'" + havy + "'", null);
if (cursor.moveToNext()) {
Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
intent.putExtra(G.selectedItem.face, true);
SearchActivity.this.finish();
} else {
Toast.makeText(SearchActivity.this, "shows something", Toast.LENGTH_SHORT).show();
}
}
});
Check if your cursor is not null and size is greater that zero, then iterate over the cursor.

Categories

Resources