Barcode Scanner Android Sqlite - android

Good day sir/ma'am, everytime I press save the item name, item price and item description, my app automatically crash and directed to main screen. this is the error. would you mind to help me?
E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.num.barcodescannerproject, PID: 15141
android.database.sqlite.SQLiteException: unrecognized token: "8850007011743jumel50wew" (code 1): , while
compiling: INSERT INTO scanresults VALUES(8850007011743jumel50wew);
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:906)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:517)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1704)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1635)
at app.num.barcodescannerproject.popupDialouge$1.onClick(popupDialouge.java:36)
at android.view.View.performClick(View.java:4909)
at android.view.View$PerformClick.run(View.java:20390)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5877)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
I/Process: Sending signal. PID: 15141 SIG: 9 Application terminated.
This is my code
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = openOrCreateDatabase("barcodescan",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS scanresults(barcode VARCHAR,item VARCHAR,price VARCHAR ,note VARCHAR);");
db.execSQL("INSERT INTO scanresults VALUES("+Barcode+item.getText().toString()+itemPrice.getText().toString()+itemNote.getText().toString()+");");
Toast.makeText(popupDialouge.this, "Item Saved", Toast.LENGTH_SHORT).show();
finish();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});

I'm afraid you are using wrong methods for the insert methods.Add a method inside the button click, and follow below example.
public void InsertScanResult(String barcodeItem,String itemPrice,String itemNote)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("BarCodeColumnNamed", barcodeItem);
cv.put("PriceColumnName",itemPrice);
cv.put("ItemColumnName", itemNote);
db.insert("YourTableNamed", null, cv);
}
You can get example from Android SQLite Database Tutorial

I think you need to quote your Strings inside your SQL-statement
see : this answer

Instead of executing raw statement using db.execSQL(), its better to use most preferred built-in method db.insert() to insert data through ContentValues.
Update your onClick() method as below:
#Override
public void onClick(View v) {
SQLiteDatabase db = openOrCreateDatabase("barcodescan",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS scanresults(barcode VARCHAR, item VARCHAR, price VARCHAR , note VARCHAR);");
// Data to be inserted
ContentValues values = new ContentValues();
values.put("barcode", Barcode);
values.put("item", item.getText().toString());
values.put("price", itemPrice.getText().toString());
values.put("note", itemNote.getText().toString());
// Insert data
db.insert("scanresults", null, values);
Toast.makeText(popupDialouge.this, "Item Saved", Toast.LENGTH_SHORT).show();
finish();
}
Hope this will help~

I think you forgot the quotes:
db.execSQL("INSERT INTO scanresults VALUES('"Barcode+ "', '" +item.getText().toString()+"', '" + itemPrice.getText().toString()+"', '" +itemNote.getText().toString()+"');");
However, you should really consider using prepared statements...

Related

SQLite: db.insert not functioning inside an if statement

I am trying to use a SQLite database to store information for a recycler view. I would like the database to contain only unique records according to their description. I have tried to set the description field to unique when I create the database and it does not seem to help. I instead decided to create a function that checks if the description already exists inside the database and then insert the new record with this information. This function works fine, after running the debug tool to see where I went wrong. Where I think the error lies is in the db.insert function that does not seem to execute when inside the if statement. Any help is appreciated.
P.S. I'm a total noob at SQLite and not very familiar with the jargon around it.
Here is part of the code for the class that helps with database handling
public class DataBaseHandler extends SQLiteOpenHelper {
private final Context context;
public DataBaseHandler(#Nullable Context context) {
super(context, Constants.DB_NAME, null, Constants.DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FOOD_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "("
+ Constants.KEY_ID + " INTEGER PRIMARY KEY,"
+ Constants.KEY_FOOD_ITEM + " INTEGER,"
+ Constants.KEY_PRICE + " TEXT,"
+ Constants.KEY_QTY_NUMBER + " INTEGER,"
+ Constants.KEY_DESCRIPTION + " TEXT,"
+ Constants.KEY_DATE_NAME + " LONG);";
db.execSQL(CREATE_FOOD_TABLE);
}
Here is the code for the hasObject function:
public boolean hasObject(String foodCode) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + Constants.TABLE_NAME + " WHERE " + Constants.KEY_DESCRIPTION + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {foodCode});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
}
cursor.close();
db.close();
return hasObject;
}
The constants are defined in a seperate class as a static final.
Here is my code where the problem exists.
public void addItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.KEY_FOOD_ITEM, item.getItemName());
values.put(Constants.KEY_PRICE, item.getPrice_double());
values.put(Constants.KEY_QTY_NUMBER, item.getItemQuantity());
values.put(Constants.KEY_DESCRIPTION, item.getDescription());
values.put(Constants.KEY_DATE_NAME,
java.lang.System.currentTimeMillis());//timestamp of the system
// db.insert(Constants.TABLE_NAME, null, values);
// Log.d("DBHandler", "added Item: ");
//Check if the record already exists in the database
if(!hasObject(item.getDescription())){
//Insert the row
db.insert(Constants.TABLE_NAME, null, values); // This is not running as planned
Log.d("DBHandler", "added Item: ");
}
else {
//Don't insert the row
Log.d("DBHandler", "Item exists");
}
}
As you noticed, I tried running the db.insert function just as it is, without checking if the record already exists in the database, and it works fine.
But if I keep adding records regardless if they are in the database, there will too many duplicates and this messes up the recycler view.
The additem function is being called here:
databaseHandler= new DataBaseHandler(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
itemList= new ArrayList<>();
//tempitemlist = new ArrayList<>();
//Get items from Firebase
mfoodRef.addValueEventListener(new ValueEventListener() {
//Will run everytime there is an update to the condition value in the database
//So this will run when the .setValue function runs in the button onClickListener classes
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//tempitemlist.clear();
Iterable<DataSnapshot> databaseMenu = dataSnapshot.getChildren();
for (DataSnapshot data:databaseMenu){
Menu tempMenu = data.getValue(Menu.class);
Item tempItem = new Item(tempMenu.getFoodName(),tempMenu.getFoodCode(),tempMenu.getFoodPrice());
//itemList.add(tempItem);
databaseHandler.addItem(tempItem);
}
}
// In case we run into any errors
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
And yes, I am using the information on my Firebase realtime database to update the contents of the databasehandler in the onDataChange method. Which is why I need to check for duplicates when I am inserting a new record.
EDIT:
This is what I found in the debug log:
Process: com.example.vendorwrecycler, PID: 12882
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.example.vendorwrecycler/databases/foodList
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:57)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1567)
at android.database.sqlite.SQLiteDatabase.insertOrThrow(SQLiteDatabase.java:1494)
at com.example.vendorwrecycler.data.DataBaseHandler.addItem(DataBaseHandler.java:68)
at com.example.vendorwrecycler.ListActivity.saveItem(ListActivity.java:184)
at com.example.vendorwrecycler.ListActivity.access$500(ListActivity.java:34)
at com.example.vendorwrecycler.ListActivity$4.onClick(ListActivity.java:159)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
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:930)
Maybe it might be something to do with the IllegalStateException ?
You are trying to execute operation on a closed DB instance. Try moving SQLiteDatabase db = getWritableDatabase(); inside if statements.
if(!hasObject(item.getDescription())){
//Insert the row
SQLiteDatabase db = getWritableDatabase();
db.insert(Constants.TABLE_NAME, null, values);
Log.d("DBHandler", "added Item: ");
}
else {
//Don't insert the row
Log.d("DBHandler", "Item exists");
}
You closed the connection of DB inside hasObject function.
there's no item description in the tempItem variable.
Item tempItem = new Item(tempMenu.getFoodName(),tempMenu.getFoodCode(),tempMenu.getFoodPrice());
so item.getDescription() must be null or empty
log all the tempItem object variables and make sure none of the variables are null or empty.
hope this helps

SQLite Column Error : table XXXX has no column named ZZZZ

I'm trying to insert rows in my Student Table which contains two rows : ID and Name
Here is the addHandler function which is implemented in MyDBHandler class :
public void addHandler(Student student) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, student.getID());
values.put(COLUMN_NAME, student.getStudentName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
The onCreate method is :-
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT )";
db.execSQL(CREATE_TABLE);
}
The attributes of MyDBHandler class which extends SQLiteOpenHelper :
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ID = "StudentID";
public static final String COLUMN_NAME = "StudentName";
I have a ADD Button in my activity_main.xml file and here is the code behind :
public void add(View view){
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
int id = Integer.parseInt(studentIdText.getText().toString());
String name = studentNameText.getText().toString();
Student student = new Student(id, name);
dbHandler.addHandler(student);
studentIdText.setText("");
studentNameText.setText("");
}
The app is running perfectly but when i want to insert a row in the table , i get the following errors in Run Tab :
E/SQLiteLog: (1) table Student has no column named StudentID
E/SQLiteDatabase: Error inserting StudentName=yassine StudentID=10
android.database.sqlite.SQLiteException: table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.test.MyDBHandler.addHandler(MyDBHandler.java:48)
at com.example.test.MainActivity.add(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5246)
at android.widget.TextView.performClick(TextView.java:10566)
at android.view.View$PerformClick.run(View.java:21256)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Any recommendations ?
Your issue is very likely a mis-conception in regard to the onCreate method. That is it onCreate doesn't run every time the App is run. onCreate will only run if the database doesn't actually exist. If the database has already been created by another previous run of the App then the onCreate method is not run.
As such any changes made to the structure of the database, as typically applied in the onCreate method will not be applied.
It would appear that you have added the defnition for the StudentId column, to the code in the onCreate method, after the App has been run.
As long as you have no data that needs to be preserved (which is very likely) then the simplest solution is to do 1 of the following :-
delete or clear the App's data (via settings/Apps)
uninstall the App
and then rerun the App, the database will then be created using the code as per the modified onCreate code.

Deleting Row by Primary Key - SQLite Android

I have ran into a bit of a problem regarding deleting a row by primary key in my android application that has a background database of SQLite.
At the minute I have 6 line types. e.g. S1, S2, S3 etc. I can only have 6 lines at one time and therefore I only have 6 rows in my database. Beside each button on my application I have an "X" button and when they click on say the X button beside S1 I want the database to delete the row with primary key "S1".
I think there is a quick solution but ive tried to manipulate my query many different ways and cant get the correct answer.
Here is some code I have:
DB Helper:
public void deleteProgressBar4() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_2 + "=", new String[]{"S1"});
return;
}
COL_2 is the LineType by the way..
X button code :
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDb.deleteProgressBar4();
Toast.makeText(Dashboard.this, "Line S1 Cleared!", Toast.LENGTH_SHORT).show();
}
});
Can anyone see the mistake that I am making in the delete function? here is the error I am getting when I run this:
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: DELETE FROM pharma_tracker_table WHERE LINETYPE=
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1499)
at com.almac.tracker.DatabaseHelper.deleteProgressBar4(DatabaseHelper.java:141)
at com.almac.tracker.Dashboard$6$1.onClick(Dashboard.java:219)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Application terminated.
Thanks!
Just Replace with you table name and column name
SQLiteDatabase db = this.getWritableDatabase();
long i =db.delete("tableName", "column Name = ?", new String[]{String.valueof(Id)});

Android Sqlite database not working properly

I am simply trying to create a quiz app for that I am storing the data in the database . The following code is not working, and the app crashes every time I feed the data
public class QuestionFeedMainPage extends AppCompatActivity {
Button b1;
EditText e1,e2,e3,e4,e5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_feed_main_page);
b1 = (Button)findViewById(R.id.submitQF);
e1 = (EditText)findViewById(R.id.q);
e2 = (EditText)findViewById(R.id.o1);
e3 = (EditText)findViewById(R.id.o2);
e4 = (EditText)findViewById(R.id.o3);
e5 = (EditText)findViewById(R.id.o4);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String q = e1.getText().toString();
String o1 = e2.getText().toString();
String o2 = e3.getText().toString();
String o3 = e4.getText().toString();
String o4 = e5.getText().toString();
if(q.equals("") || o1.equals("") || o2.equals("") || o3.equals("") || o4.equals("")){
Toast.makeText(QuestionFeedMainPage.this, "Please fill all the fields", Toast.LENGTH_SHORT).show();
}
else {
SQLiteDatabase sql = openOrCreateDatabase("multip",MODE_PRIVATE,null);
sql.execSQL("create table if not exists questions (sno INTEGER PRIMARY KEY AUTOINCREMENT,question varchar,optionone varchar,optiontwo varchar,optionthree varchar,optionfour varchar)");
String s4 = "select * from questions where question='"+q+"'";
Cursor cursor = sql.rawQuery(s4,null);
if(cursor.getCount()>0){
Toast.makeText(QuestionFeedMainPage.this, "This question already exist", Toast.LENGTH_SHORT).show();
}
else{
sql.execSQL("insert into questions values ('"+q+"','"+o1+"','"+o2+"','"+o3+"','"+o4+"')");
Toast.makeText(QuestionFeedMainPage.this, "Question Added", Toast.LENGTH_SHORT).show();
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
}
}
}
});
}
}
Error log:
D/ActivityThreadInjector: clearCachedDrawables.
D/OpenGLRenderer: endAllStagingAnimators on 0x55596f0a20 (RippleDrawable) with handle 0x55594260c0
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#352760c
E/SQLiteLog: (1) table questions has 6 columns but 5 values were supplied
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fridaygmail.saurabh.multip, PID: 25409
android.database.sqlite.SQLiteException: table questions has 6 columns but 5 values were supplied (code 1): , while compiling: insert into questions values ('x','x','x','x','x')
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.fridaygmail.saurabh.multip.QuestionFeedMainPage$1.onClick(QuestionFeedMainPage.java:48)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21177)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
I/Process: Sending signal. PID: 25409 SIG: 9
Application terminated.
You want to fill 5 values into a table with 6 columns. You don't want to insert the primary key sno.
Something like this should work:
sql.execSQL("insert into questions (question,optionone,optiontwo,optionthree,optionfour) values ('"+q+"','"+o1+"','"+o2+"','"+o3+"','"+o4+"')");
The error message pretty much explains what's going on:
android.database.sqlite.SQLiteException: table questions has 6 columns but 5 values were supplied (code 1): , while compiling: insert into questions values ('x','x','x','x','x')
Try something along these lines:
String sql = "INSERT INTO questions (question, optionone, optiontwo, optionthree, optionfour) VALUES (?, ?, ?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
String q = e1.getText().toString();
String q1 = e2.getText().toString();
String q2 = e3.getText().toString();
String q3 = e4.getText().toString();
String q4 = e5.getText().toString();
statement.bindString(1, q); // These match to the five question marks in the sql string
statement.bindString(2, q1);
statement.bindString(3, q2);
statement.bindString(4, q3);
statement.bindString(5, q4);
long rowId = statement.executeInsert();

android.database.sqlite.SQLiteException: near ";": syntax error (code 1):

I am getting this error when I am trying to delete a record from the database. Here is the error in full
FATAL EXCEPTION: main
Process: itp231.dba.nyp.com.bloommain, PID: 12274
android.database.sqlite.SQLiteException: near ";": syntax error (code 1): , while compiling: DELETE FROM events WHERE id= ;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at itp231.dba.nyp.com.bloommain.EventInformationPage$1.onClick(EventInformationPage.java:135)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Looking at the log, it directed me to this line of codes (my deleteRecord() method -
private void deleteRecord() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want delete this person?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
String id = editTextId.getText().toString().trim();
String sql = "DELETE FROM events WHERE id= " + id + ";";
db.execSQL(sql);
Toast.makeText(getApplicationContext(), "Record Deleted", Toast.LENGTH_LONG).show();
c = db.rawQuery(SELECT_SQL,null);
}
});
1 - Your id is a blank string, therefore it can't be parsed in your SQL command.
2 - If your id field is a TEXT (???), then you need to enclose it in single quotes.
3 - For SQL commands, use execSQL() instead of rawQuery() - rawQuery() only works on... queries (SELECT)
4 - And... prepared statements (or bound parameters) are a better choice. The placeholders (?) will be replaced automatically in their positional order and the quotes won't be a problem anymore (Android will handle that for you!).
You can use prepared statements
SQLiteStatement stmt = db.compileStatement("DELETE FROM events WHERE id = ?");
stmt.bindString(1, id);
stmt.execute();
try this..
db.delete("events","id=?",new String[]{Integer.toString(id)});
in which,
first paramater -> will be table name from where the deletion of data need to de done.
Second parameter -> Selection field in table.based on which field we are going to perform the deletion
Third parameter -> specifies the value,to be compare it with second paramters field if it is matched,then the particular column will be deleted.

Categories

Resources