There is something wrong with my update statement. I am trying to update an user from my database, I am sure this user is in my database, but I just can't update him. I think I have a fault with my column name because the error said:
android.database.sqlite.SQLiteException: no such column: UPDATE
But I never asked for this column, nnn isn't a column at all in my scheme. Here is the statement
public void changeprofiel(String id, Profiel p){
SQLiteDatabase db = this.getWritableDatabase();
/* ContentValues contentValues = new ContentValues();
contentValues.put(COL_2_PROFIELEN, p.getUsername());
contentValues.put(COL_3_PROFIELEN, p.getFirstname());
contentValues.put(COL_4_PROFIELEN, p.getEmail());
contentValues.put(COL_5_PROFIELEN, p.getPassword());*/
// de insert methode geeft -1 terug als het niet gelukt is en de row value als het wel gelukt is
System.out.println(getProfielWid(id).getId());
// db.update(TABLE_NAME_PROFIELEN, contentValues,COL_1_PROFIELEN ="'" + id +"'",null);
db.execSQL("UPDATE "+ TABLE_NAME_PROFIELEN + " SET "+COL_2_PROFIELEN+" = "+p.getUsername()+", " +COL_3_PROFIELEN+" = "+p.getFirstname()+", "+COL_4_PROFIELEN+" = "+p.getEmail()+", "+COL_5_PROFIELEN+" = "+p.getPassword()+
" WHERE " + COL_1_PROFIELEN + "=" + id + "");
}
I also tried this way for the where closule:
" WHERE " + COL_1_PROFIELEN + "='" + id + "'");
But they give me both this error:
I/System.out: nnnnnn
E/SQLiteLog: (1) no such column: nnn
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cedri.bcv, PID: 13908
android.database.sqlite.SQLiteException: no such column: nnn (code 1): , while compiling: UPDATE profielen SET username = nnn, firstname = nnn, email = nnn, password = xxx WHERE profile_id=nnnnnn
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.executeSql(SQLiteDatabase.java:1677)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.cedri.bcv.DB.DatabaseHelper.changeprofiel(DatabaseHelper.java:82)
at com.example.cedri.bcv.Activities.MainActivity.savechanges(MainActivity.java:94)
at com.example.cedri.bcv.Fragments.AccountFragment$1.onClick(AccountFragment.java:86)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Do I need to set every value between single quotes?
You need to wrap your values with single quotes ('') if the column's type is text.
Your query should look like this:
UPDATE profielen SET username = 'nnn', firstname = 'nnn', email = 'nnn', password = 'xxx'
WHERE profile_id='nnnnnn'
Related
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
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.
onCreate method of the database :
private static String DATABASE = "DB1.db";
private static String TABLE ="NotesTable";
private static String TITLE = "title";
private static String NAME ="name";
private static String TIME = "time";
private static String BOOKMARK = "bookm";
private static String NOTITIME = "notitime";
DatabaseHelper(Context context) {
super(context, DATABASE, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "
+ TABLE + "( "
+ TITLE + " TEXT, "
+ NAME + " TEXT, "
+ NOTITIME + " LONG, "
+ BOOKMARK + " INTEGER DEFAULT 1 )");
}
Error occurs in the following code of the database :
//cursor to get all the column's data
List<DataModel> getdata(){
List<DataModel> data=new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
StringBuilder stringBuffer = new StringBuilder();
DataModel dataModel;
#SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from "+TABLE+" ORDER BY " + TIME + " DESC;",null);
while (cursor.moveToNext()) {
dataModel= new DataModel();
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
Long time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
Integer book = cursor.getInt(cursor.getColumnIndexOrThrow("bookm"));
Long notitime = cursor.getLong(cursor.getColumnIndexOrThrow("notitime"));
dataModel.setTitle(title);
dataModel.setName(name);
dataModel.setDate(time);
dataModel.setBookmark(book);
dataModel.setNotiTime(notitime);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
StackTrace :
FATAL EXCEPTION: main
Process: com.tank.vishal.sample, PID: 5981
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tank.vishal.sample/com.tank.vishal.sample.MainActivity}: android.database.sqlite.SQLiteException: no such column: time (code 1): , while compiling: select * from NotesTable ORDER BY time DESC;
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.database.sqlite.SQLiteException: no such column: time (code 1): , while compiling: select * from NotesTable ORDER BY time DESC;
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.rawQuery(SQLiteDatabase.java:1257)
at com.tank.vishal.sample.DatabaseHelper.getdata(DatabaseHelper.java:102)
at com.tank.vishal.sample.MainActivity.initViews(MainActivity.java:114)
at com.tank.vishal.sample.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
What I've tried :
Changing the name of table and database,
Uninstalling the app itself and remove all the data from device.
this error never occurred before while making this app, it was running perfectly till today.
P.S. - I tried installing the app in a device in which it is not installed before NOT EVEN ONCE and it returned below error :
Failure [INSTALL_CANCELED_BY_USER]
$ adb shell pm uninstall com.tank.vishal.sample
DELETE_FAILED_INTERNAL_ERROR
Error while Installing APK
Your CREATE TABLE SQL does not create a column with the name of time. First add the column specification for it and only then uninstall and reinstall your app.
In onCreate, you didn't create column time
Im trying to update a specific user's information in SQL database when a user Login and I dont know why do I get this error. Please help :(
I check the record first. If there is none, I will add the user, and if it exist in my SQL. Not sure if im getting this correct.
public String RecordCheck(){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
userEmail = user.getEmail().toString();
String RecordHolder = "";
SQLiteDatabase db = getWritableDatabase();
String query = "" + "SELECT * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USEREMAIL + " = '" + userEmail.trim() + "'";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
if(c.equals("")){
RecordHolder = "adduser";
}
else
RecordHolder = "updateuser";
db.close();
return RecordHolder;
I have this in my Welcome Back class to know if its going to update if user exist or add if user doesnt exist.
String Record = dbHandler.RecordCheck();
if(Record.equals("adduser")){
dbHandler.addUser(userdata);
}
else {
dbHandler.updateUser(userdata);
}
if update is called
public void updateUser(Users user){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser userf = firebaseAuth.getCurrentUser();
userEmail = userf.getEmail();
ContentValues values = new ContentValues();
values.put(MyDBHandler.COLUMN_USEREMAIL, user.get_useremail());
values.put(MyDBHandler.COLUMN_NAME, user.getName());
values.put(MyDBHandler.COLUMN_SEX, user.getSex());
values.put(MyDBHandler.COLUMN_BDAY, user.getBday());
values.put(MyDBHandler.COLUMN_HEIGHT, user.getHeight());
values.put(MyDBHandler.COLUMN_MHEIGHT, user.getMheight());
values.put(MyDBHandler.COLUMN_WEIGHT, user.getWeight());
values.put(MyDBHandler.COLUMN_MWEIGHT, user.getMweight());
values.put(MyDBHandler.COLUMN_USEREXPERIENCE, user.getUserexperience());
values.put(MyDBHandler.COLUMN_FQUESTION, user.getFquestion());
values.put(MyDBHandler.COLUMN_SQUESTION, user.getSquestion());
values.put(MyDBHandler.COLUMN_TQUESTION, user.getTquestion());
values.put(MyDBHandler.COLUMN_BODYSTATE, user.getBodystate());
values.put(MyDBHandler.COLUMN_APPARENTLYHEALTHY, user.isApparentlyhealthy());
values.put(MyDBHandler.COLUMN_HYPERTENSION, user.isHypertension());
values.put(MyDBHandler.COLUMN_DIABETES, user.isDiabetes());
values.put(MyDBHandler.COLUMN_ASTHMA, user.isAsthma());
SQLiteDatabase db = getWritableDatabase();
db.update(MyDBHandler.TABLE_USERINFO, values, userEmail, null);
db.close();
}
--------- beginning of crash
11-22 12:44:13.179 17496-17496/com.example.abad.maxfitness2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abad.maxfitness2, PID: 17496
android.database.sqlite.SQLiteException: near "#gmail": syntax error (code 1): , while compiling: UPDATE users SET fquestion=?,mheight=?,tquestion=?,asthma=?,height=?,bodystate=?,diabetes=?,weight=?,bday=?,useremail=?,squestion=?,hypertension=?,name=?,healthy=?,mweight=?,userexp=?,sex=? WHERE testing8#gmail.com
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.updateWithOnConflict(SQLiteDatabase.java:1577)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1525)
at com.example.abad.maxfitness2.LocalDatabase.MyDBHandler.updateUser(MyDBHandler.java:139)
at com.example.abad.maxfitness2.WelcomeBack$1.onDataChange(WelcomeBack.java:83)
at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You have to pass the where argument in the below format
db.update(MyDBHandler.TABLE_USERINFO,values,MyDBHandler.COLUMN_USEREMAIL+"='"+userEmail+"'", null);
You need to update query from
db.update(MyDBHandler.TABLE_USERINFO, values, userEmail, null);
to:
db.update(MyDBHandler.TABLE_USERINFO, values, "columnId ='"+userEmail+"'", null);
Note: The columnId mentioned should be the id of column in table of db e.g email etc
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.