I want to add data into my created SQLite database with SQLite database manager programs i get the "readonly database"error
When i comment insertion line the program works fine and crashes when uncommented.
Note : I have requested read/write storage permission and it has been granted.
public static Context context;
public static SQLiteDatabase database;
public static String SDK = Environment.getExternalStorageDirectory().toString();
public static String DB = SDK + "/database/";
context = getApplicationContext();
File file = new File(DB);
file.mkdirs();
database = SQLiteDatabase.openOrCreateDatabase(DB + "/db.sqlite",null);
database = SQLiteDatabase.openDatabase(DB + "/db.sqlite",null,SQLiteDatabase.OPEN_READWRITE);
database.execSQL("CREATE TABLE IF NOT EXISTS 'tbltest' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , 'name' VARCHAR, 'family' VARCHAR)");
database.execSQL("INSERT INTO `tbltest` (`name`,`family`) VALUES (`John`,`Doe`)");
database.close();
Logcat error
` --------- beginning of crash
04-19 20:54:50.832 13353-13353/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: andishmand.database, PID: 13353
java.lang.RuntimeException: Unable to start activity ComponentInfo{andishmand.database/andishmand.database.MainActivity}: android.database.sqlite.SQLiteException: no such column: John (code 1): , while compiling: INSERT INTO `tbltest` (`name`,`family`) VALUES (`John`,`Doe`)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.database.sqlite.SQLiteException: no such column: John (code 1): , while compiling: INSERT INTO `tbltest` (`name`,`family`) VALUES (`John`,`Doe`)
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 andishmand.database.MainActivity.executecommand(MainActivity.java:128)
at andishmand.database.MainActivity.createdb(MainActivity.java:115)
at andishmand.database.MainActivity.requestperms(MainActivity.java:100)
at andishmand.database.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
04-19 20:54:50.853 1610-3265/? W/ActivityManager: Force finishing activity andishmand.database/.MainActivity`
Confirm that the device database is the way you want it as in your create statement in case your table was previously created without a column. You can do this by uninstalling the app and redeploying it.
Then use ContentValues class and the database.insert to do the actual insert. A good deal of this is explained here : https://developer.android.com/training/basics/data-storage/databases.html, but here is the short and simple:
remove this line :
database.execSQL("INSERT INTO `tbltest` (`name`,`family`) VALUES (`John`,`Doe`)");
And replace it with :
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("family", "Doe");
long insertedRowId = database.insert("tbltest", null, values);
SQL uses "double quotes" to quote table/column names, and 'single quotes' to quote strings.
`Backticks` are a misguided attempt to be MySQL compatible; don't use them, ever.
Related
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 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.
Friends I want to Update Blob Data Field where Column 'IS NULL'
whenever i try following code it generates error
I just want to know How To Update Blob Datatype ??
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.audiobook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.PNG,100,stream);
simple = stream.toByteArray();
String sql = "UPDATE Settings SET image = "+simple+"where image IS NULL";
db.execSQL(sql);
when I try this code it generates this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blackhat.rhythmbox/com.blackhat.rhythmbox.Welcome}: android.database.sqlite.SQLiteException: unrecognized token: ":" (code 1): , while compiling: UPDATE Settings SET image = :[B#27a97db7
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.database.sqlite.SQLiteException: unrecognized token: ":" (code 1): , while compiling: UPDATE Settings SET image = :[B#27a97db7
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
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:1704)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1635)
at com.blackhat.rhythmbox.Welcome.addtoDatabase(Welcome.java:124)
at com.blackhat.rhythmbox.Welcome.code(Welcome.java:67)
at com.blackhat.rhythmbox.Welcome.onCreate(Welcome.java:57)
at android.app.Activity.performCreate(Activity.java:6100)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
where i doing wrong or what i am doing wrong ???
add space before where like this:
String sql = "UPDATE Settings SET image = "+simple+" where image IS NULL";
Remove:
String sql = "UPDATE Settings SET image = "+simple+"where image IS NULL";
db.execSQL(sql);
Try using ContentValues.put() and SqliteDatabase.update()
ContentValues cv = new ContentValues();
cv.put("image", simple);
db.update("Settings", cv, "image is null", null);
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
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);