How to insert a new row of table of sqlite in android? - android

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

Related

error in counting the number of a specific record in database

how can I create a query that counts the number of an Specific record in database.
I tried this code:
public int getContactsCount(String name) {
String countQuery = "SELECT count(*) FROM database_names where _name ="+name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
but it did not work.
it says :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 26655
android.database.sqlite.SQLiteException: incomplete input (Sqlite code 1 SQLITE_ERROR): , while compiling: SELECT count(*) FROM database_names where _name =, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:948)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:559)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1493)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1427)
at com.example.myapplication.database_names.getContactsCount(database_names.java:68)
at com.example.myapplication.HazineHaActivity$1.onClick(HazineHaActivity.java:62)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
how can I do it?
Probably your problem is that you don't surround the parameter name in single quotes.But the correct way to do it is to use a placeholder in your query and pass name as a parameter:
Cursor c = db.rawQuery(
"SELECT COUNT(*) AS counter FROM MY TABLE WHERE _NAME = ?",
new String[] {name}
);
Replace db with your SQLiteOpenHelper object.
select COUNT(id) as count from tblstudent where name='test'

I have a problem when dealing with the local database when adding and modifying

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]";

E/SQLiteLog: (1) near "(": syntax

I try to save data in my app database for a while but i still get the same issue. Here is what my code looks like.
In the database page:
public void insererTrajetTest (String et_VilleD, String et_VilleA, String
et_LieuDepart, String et_LieuArrivee,String et_dateDepartAller, String
et_heureDepartAller, String et_flexibilite, String et_bagage, String et_detour,
String et_iduser, String et_trajet, String et_commentaire, String et_place,
String et_dateArriveeAller, String et_heureArriveeAller, String et_prix, String
et_distance, String et_duree) {
db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME3;
Cursor cursor = db.rawQuery(query, null);
ContentValues values = new ContentValues();
values.put(COLUMN_VILLE_DEPART, et_VilleD);
values.put(COLUMN_VILLE_ARRIVEE, et_VilleA);
values.put(COLUMN_LIEU_DEPART, et_LieuDepart);
values.put(COLUMN_LIEU_ARRIVEE, et_LieuArrivee);
values.put(COLUMN_DATE_DEPART, et_dateDepartAller);
values.put(COLUMN_HEURE_DEPART, et_heureDepartAller);
values.put(COLUMN_FLEXIBILITE, et_flexibilite);
values.put(COLUMN_BAGAGE, et_bagage);
values.put(COLUMN_DETOUR, et_detour);
values.put(COLUMN_ID_CHAUFFEUR, et_iduser);
values.put(COLUMN_TRAJET, et_trajet);
values.put(COLUMN_COMMENTAIRE, et_commentaire);
values.put(COLUMN_PLACES_PROPOSEES, et_place);
values.put(COLUMN_PLACES_DISPONIBLES, et_place);
values.put(COLUMN_DATE_ARRIVEE, et_dateArriveeAller);
values.put(COLUMN_HEURE_ARRIVEE, et_heureArriveeAller);
values.put(COLUMN_PRIX, et_prix);
values.put(COLUMN_DISTANCE, et_distance);
values.put(COLUMN_DUREE, et_duree);
db.insert(TABLE_NAME3, null, values);
Log.d("Base de données", "Un nouveau voyage a été créé...");
db.close();
cursor.close();
}
However I always get the followings in the logcat:
09-18 22:15:49.986 4108-4427/cm.opep.opep E/SQLiteLog: (1) near "(": syntax error
09-18 22:15:49.990 4108-4427/cm.opep.opep E/SQLiteDatabase: Error inserting VilleDépart=Abong-Mbang Trajet=Abong-Mbang --> Ambam: HeureDépart=23:45 DateDépart=2018-09-28 Flexibilité=+/- 30 minutes HeureArrivée=05:59 Bagage=Petit Commentaire=Nine LieuArrivée=Er VilleArrivée=Ambam Durée=06 h 14 min DateArrivée=2018-09-29 LieuDépart=Az IDChauffeur=5 Détour=+/- 15 minutes Prix=3100 Distance(Km)=422 PlacesDisponibles=5 PlacesProposées=5
android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,Distance(Km),PlacesDisponibles,PlacesProposées) 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:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at cm.opep.opep.DatabaseHelper.insererTrajetTest(DatabaseHelper.java:1328)
at cm.opep.opep.fragment.BackGroundTask.doInBackground(BackGroundTask.java:56)
at cm.opep.opep.fragment.BackGroundTask.doInBackground(BackGroundTask.java:12)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Can anyone tell me what goes wrong with my code ?
I believe that the issue is with the column named Distance(Km), to use such a column name. You'd have to enclose it e.g.
Prix,`Distance(Km)`,PlacesDisponibles,
You could do this bay changing COLUMN_DISTANCE to be defined using
COLUMN_DISTANCE = "`Distance(Km)`"
This would result in :
INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,`Distance(Km)`,PlacesDisponibles,PlacesProposées) VALUES (
'Abong-Mbang','Abong-Mbang --> Ambam:','23:45','2018-09-28','+/- 30 minutes','05:59','Petit','Nine','Er','Ambam','06 h 14 min','2018-09-29',
'Az',5,'+/- 15 minutes',3100,422,5,5
);
Which works as per :-
INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,`Distance(Km)`,PlacesDisponibles,PlacesProposées) VALUES (
'Abong-Mbang','Abong-Mbang --> Ambam:','23:45','2018-09-28','+/- 30 minutes','05:59','Petit','Nine','Er','Ambam','06 h 14 min','2018-09-29',
'Az',5,'+/- 15 minutes',3100,422,5,5
)
> Affected rows: 1
> Time: 0.23s
Note for the column to exist then it's name must have been enclosed when the table was defined.
However, I'd suggest renaming the column to Distance_Km.
There are alternative enclosing characters you could also use
"Distance(Km)" i.e. enclosed in " and "
[Distance(Km)] i.e. enclosed in [ and ]
'Distance(Km)' i.e. enclosed in ' and '
This is covered at SQL As Understood By SQLite - SQLite Keywords

Unable to query database in Android

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.

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)});

Categories

Resources