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.
Related
I have a problem when editing and adding the database
I tried to edit and search for the problem but could not find the solution
public boolean insert_dealer(get_set_db dealer){
ContentValues Values = new ContentValues();
Values.put(My_data.dealer_CLN_NMEA , dealer.getName());
Values.put(My_data.dealer_CLN_description , dealer.getDescribe());
Values.put(My_data.dealer_CLN_image , dealer.getImage());
Values.put(My_data.dealer_CLN_WHOLESALE , dealer.getWholesale());
Values.put(My_data.dealer_CLN_INDIVIDUAL , dealer.getAn_individual());
long result = database.insert(My_data.dealer_TB_NAME,null,Values);
return result != -1;
}
Logs details
2019-07-11 09:28:44.341 31418-31418/com.example.dealer E/SQLiteLog: (1) near "individual": syntax error
2019-07-11 09:28:44.348 31418-31418/com.example.dealer E/SQLiteDatabase: Error inserting image=kcc An individual=3.0 describe=othman wholesale=2.0 Name=ott
android.database.sqlite.SQLiteException: near "individual": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO dealerr(image,An individual,describe,wholesale,Name) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514)
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.insertWithOnConflict(SQLiteDatabase.java:1562)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.dealer.DatabaseAccess.insert_dealer(DatabaseAccess.java:49)
at com.example.dealer.Main2Activity.onOptionsItemSelected(Main2Activity.java:154)
Here dealer.getAn_CLN_INDIVIDUAL() returning "An individual", here you can not keep an attribute name with space. Just change it to an_individual, hope it will work.
My_data.dealer_CLN_INDIVIDUAL , dealer.getAn_individual()
The constant My_data.dealer_CLN_INDIVIDUAL which represents a column's name, has been defined as:
String dealer_CLN_INDIVIDUAL = "An individual";
A column's name must not contain spaces.
You can enclose it in square brackets to solve the problem:
String dealer_CLN_INDIVIDUAL = "[An individual]";
I am trying to make the cart of a shopping app where I first query a cart element and from the id of a cart, list element find the corresponding meta-data related to the product by querying another table containing product information. I am able to successfully query the product list while showing the "menu" and am trying to apply the same code to the cart. Yet it tells me that the column "_id" doesn't exist. I have stuck on this for a while.
You can find the entire project on GitHub
Here are important parts of relevant files
YourCart.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_cart);
ContentValues values = new ContentValues();
values.put(CartContract.CartEntry._ID, 2);
values.put(CartContract.CartEntry.COLUMN_NAME_ORDERED_QUANTITY, 37);
getContentResolver().insert(CartContract.CartEntry.CONTENT_URI, values);
String[] projection = {
CartContract.CartEntry._ID,
CartContract.CartEntry.COLUMN_NAME_ORDERED_QUANTITY
};
//gets the entire cart
cart = getContentResolver().query(CartContract.CartEntry.CONTENT_URI, projection, null, null, null);
ListView cartList = findViewById(R.id.CartListView);
cartList.setAdapter(new cartAdapter(YourCart.this, cart));
}
// Following is part of cartAdapter
#Override
public void bindView(View view, Context context, Cursor cart) {
prodName = view.findViewById(R.id.cartListElementProductNameTextView);
prodPrice = view.findViewById(R.id.cartListElementProductPriceTextView);
//Projection is just the name of the columns we would like to receive
String[] projection = {
ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_THUMBNAIL,
ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_NAME,
ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_PRICE
};
Integer ui = cart.getInt(cart.getColumnIndexOrThrow(CartContract.CartEntry._ID));
String[] hoho = {ui.toString()};
Cursor productCursor = getContentResolver().query(ProductListContract.ProductEntry.CONTENT_URI, projection, ProductListContract.ProductEntry._ID, hoho, null);
prodName.setText(productCursor.getInt(productCursor.getColumnIndexOrThrow(ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_NAME)));
ui = productCursor.getInt(productCursor.getColumnIndexOrThrow(ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_PRICE));
prodPrice.setText(ui.toString());
productCursor.close();
}
I'm pretty sure the column gets created when the table is created as can be seen here from an excerpt from the Database Helper
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " ( " +
_ID + " INTEGER NON NULL, " +
COLUMN_NAME_ORDERED_QUANTITY + " INTEGER)";
Finally here is the log of the crash. The app crashes as soon as the YourCart activity is launched
03-16 09:50:30.987 11672-11672/com.example.tanmay.shoppingapp E/SQLiteLog: (1) table cart has no column named _id
03-16 09:50:30.991 11672-11672/com.example.tanmay.shoppingapp E/SQLiteDatabase: Error inserting quantity=37 _id=2
android.database.sqlite.SQLiteException: table cart has no column named _id (code 1): , while compiling: INSERT INTO cart(quantity,_id) VALUES (?,?)
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.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1472)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.tanmay.shoppingapp.DataSet.DataProvider.insertCart(DataProvider.java:169)
at com.example.tanmay.shoppingapp.DataSet.DataProvider.insert(DataProvider.java:155)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:264)
at android.content.ContentResolver.insert(ContentResolver.java:1279)
at com.example.tanmay.shoppingapp.YourCart.onCreate(YourCart.java:34)
at android.app.Activity.performCreate(Activity.java:6684)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
03-16 09:50:30.991 11672-11672/com.example.tanmay.shoppingapp E/com.whatever.tag: Failed to insert row for content://com.example.tanmay.shoppingapp/cart
03-16 09:50:30.992 11672-11672/com.example.tanmay.shoppingapp E/SQLiteLog: (1) no such column: _id
03-16 09:50:30.994 11672-11672/com.example.tanmay.shoppingapp D/AndroidRuntime: Shutting down VM
03-16 09:50:30.996 11672-11672/com.example.tanmay.shoppingapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tanmay.shoppingapp, PID: 11672
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tanmay.shoppingapp/com.example.tanmay.shoppingapp.YourCart}: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, quantity FROM cart
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2699)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
Caused by: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, quantity FROM cart
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.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1165)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1036)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1204)
at com.example.tanmay.shoppingapp.DataSet.DataProvider.query(DataProvider.java:92)
at android.content.ContentProvider.query(ContentProvider.java:1020)
at android.content.ContentProvider$Transport.query(ContentProvider.java:239)
at android.content.ContentResolver.query(ContentResolver.java:534)
at android.content.ContentResolver.query(ContentResolver.java:475)
at com.example.tanmay.shoppingapp.YourCart.onCreate(YourCart.java:44)
at android.app.Activity.performCreate(Activity.java:6684)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
For some reason the table does not contain the column named _id. However, it is not because of the SQL, even though the SQL likely does not do what you wish.
More specifically the use of INTEGER NON(instead of NOT)NULL will rather than add the NOT NULL constraint, it will give the column a column_type of INTEGER NON which will equate, as it contains INT, to a column-type (affinity) of INTEGER.
As an example (this utilises the logDatabaseInfo to be found here) which with the SQL as :-
CREATE TABLE cart (_ID INTEGER NON NULL, quantity INTEGER)
Shows :-
D/SQLITE_CSU: DatabaseList Row 1 Name=main File=/data/data/soupd.so49313202updatefailed/databases/mydb
D/SQLITE_CSU: Database Version = 1
D/SQLITE_CSU: Table Name = android_metadata Created Using = CREATE TABLE android_metadata (locale TEXT)
D/SQLITE_CSU: Table = android_metadata ColumnName = locale ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table Name = cart Created Using = CREATE TABLE cart (_ID INTEGER NON NULL, quantity INTEGER)
D/SQLITE_CSU: Table = cart ColumnName = _ID ColumnType = INTEGER NON Default Value = null PRIMARY KEY SEQUENCE = 0
D/SQLITE_CSU: Table = cart ColumnName = quantity ColumnType = INTEGER Default Value = null PRIMARY KEY SEQUENCE = 0
Table = cart ColumnName = _ID ColumnType = INTEGER NON Default Value = null being the pertinent information.
The SQL should likely be :-
CREATE TABLE cart (_ID INTEGER NOT NULL, quantity INTEGER)
Note normally _id/_ID is used for a column that holds a unique identifier that is automatically generated by SQLite, and thus
typically you would have _ID INTEGER PRIMARY KEY for the column
definition. Coding this and not providing a value for the _id will
result in the unique identifier being generated by SQLite (typically
1,2,3,4.....).
Note I haven't shown this in the SQL below because you would need to look at inserting without the id.
The Likely Real Issue
The real issue is elsewhere but is very likely due to the DatabaseHelper's onCreate method not having been called. It has likely been called once as the database exists. So the most likely issue is that the table structure has been changed but the database hasn't been deleted.
More specifically the onCreate method is only invoked (automatically) once when the database is created.
The Likely Fix
The likely fix is that the database should be deleted and then the App rerun.
- You can delete the database by deleting the App's data
- or by uninstalling the App.
- I'd suggest changing the SQL as shown above.
try replacing your create SQL_CREATE_ENTRIES statement by this,
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " ( " +
_ID + " INTEGER NOT NULL, " +
COLUMN_NAME_ORDERED_QUANTITY + " INTEGER)";
your query has invalid key word which is "NON" in _ID column.
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)});
I am working on a attendance apps for teacher. I have created database and trying to insert a new row but I am getting errors.I am giving few necessary code below.
Database creation is as:
String aquery="CREATE TABLE "+ATTENDANCE_TABLE_NAME+" ( COLUMN_DATE TEXT PRIMARY KEY );";
db.execSQL(aquery);
And ALTER the table as:
String aquery="ALTER TABLE "+ATTENDANCE_TABLE_NAME+" ADD COLUMN '"+new_col_name+"' TEXT;";
db.execSQL(aquery);
now I am inserting a row a new row as:
ContentValues Values=new ContentValues();
SQLiteDatabase db=getWritableDatabase();
// finding all column
Cursor dbCursor = db.query(ATTENDANCE_TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
String zero="0";
for (int i=0;i<columnNames.length;i++)
{
// saving values to each specific column
if(i==0)
Values.put("COLUMN_DATE", date );
else
Values.put(columnNames[i],"'"+zero+"'");
}
check = db.insert(ATTENDANCE_TABLE_NAME, null , Values);
But I am getting this error:
05-25 18:52:23.023 19480-19480/com.example.vikas.scannerproject E/SQLiteLog: (1) near "14202": syntax error
05-25 18:52:23.023 19480-19480/com.example.vikas.scannerproject E/SQLiteDatabase: Error inserting COLUMN_DATE=2017-05-25 14202='0'
android.database.sqlite.SQLiteException: near "14202": syntax error (code 1): , while compiling: INSERT INTO CSE_OS_2017_ATTENDANCE(COLUMN_DATE,14202) VALUES (?,?)
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.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.vikas.scannerproject.Index_DBHandler.takingAttendance(Index_DBHandler.java:148)
at com.example.vikas.scannerproject.ScanresultActivity.takeAttendance(ScanresultActivity.java:44)
at com.example.vikas.scannerproject.ScanresultActivity.onCreate(ScanresultActivity.java:32)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Please help me in insertion of new row.
Column Names in SqLite may not start with a number[0-9]. Change the column name to something like "A14202".
BTW Adding a column for each assignment may not be the best design. SqLite will only allow 2000 columns.
Column names in sqlite should be start with the Alphabet letter{A-Z,a-z}.
It should not start with numeric value.
Try this:
String aquery="ALTER TABLE "+ATTENDANCE_TABLE_NAME+" ADD COLUMN '"+"A"+new_col_name+"' TEXT;";
db.execSQL(aquery);
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...