I'm trying to create database using this tutorial. I'm still new in android developing, so probably this is something very easy, but still learning. This is the error i'm getting:
07-19 14:37:18.235: E/SQLiteLog(9089): (1) no such table: grocery
07-19 14:37:18.245: E/AndroidRuntime(9089): FATAL EXCEPTION: main
07-19 14:37:18.245: E/AndroidRuntime(9089): Process: com.dusandimitrijevic.grocerylist, PID: 9089
07-19 14:37:18.245: E/AndroidRuntime(9089): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dusandimitrijevic.grocerylist/com.dusandimitrijevic.grocerylist.MainActivity}: android.database.sqlite.SQLiteException: no such table: grocery (code 1): , while compiling: SELECT _id, title, price FROM grocery
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread.access$900(ActivityThread.java:177)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.os.Handler.dispatchMessage(Handler.java:102)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.os.Looper.loop(Looper.java:145)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread.main(ActivityThread.java:5942)
07-19 14:37:18.245: E/AndroidRuntime(9089): at java.lang.reflect.Method.invoke(Native Method)
07-19 14:37:18.245: E/AndroidRuntime(9089): at java.lang.reflect.Method.invoke(Method.java:372)
07-19 14:37:18.245: E/AndroidRuntime(9089): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
07-19 14:37:18.245: E/AndroidRuntime(9089): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
07-19 14:37:18.245: E/AndroidRuntime(9089): Caused by: android.database.sqlite.SQLiteException: no such table: grocery (code 1): , while compiling: SELECT _id, title, price FROM grocery
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1440)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1287)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1158)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1326)
07-19 14:37:18.245: E/AndroidRuntime(9089): at com.dusandimitrijevic.data.GroceryDbAdapter.fetchAllItems(GroceryDbAdapter.java:145)
07-19 14:37:18.245: E/AndroidRuntime(9089): at com.dusandimitrijevic.grocerylist.MainActivity.fillData(MainActivity.java:79)
07-19 14:37:18.245: E/AndroidRuntime(9089): at com.dusandimitrijevic.grocerylist.MainActivity.onCreate(MainActivity.java:59)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.Activity.performCreate(Activity.java:6289)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
07-19 14:37:18.245: E/AndroidRuntime(9089): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
07-19 14:37:18.245: E/AndroidRuntime(9089): ... 10 more
Here is the code of my Database:
package com.dusandimitrijevic.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Simple notes database access helper class. Defines the basic CRUD operations
* for the notepad example, and gives the ability to list all notes as well as
* retrieve or modify a specific note.
*
* This has been improved from the first version of this tutorial through the
* addition of better error handling and also using returning a Cursor instead
* of using a collection of inner classes (which is less scalable and not
* recommended).
*/
public class GroceryDbAdapter {
public static final String KEY_TITLE = "title";
public static final String KEY_PRICE = "price";
public static final String KEY_ROWID = "_id";
private static final String TAG = "GroceryDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private Context mCtx;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table grocery (_id integer primary key autoincrement, "
+ "title text not null, price text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "grocery";
private static final int DATABASE_VERSION = 2;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* #param ctx the Context within which to work
*/
public GroceryDbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* Open the notes database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* #return this (self reference, allowing this to be chained in an
* initialization call)
* #throws SQLException if the database could be neither opened or created
*/
public GroceryDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
/**
* Create a new note using the title and body provided. If the note is
* successfully created return the new rowId for that note, otherwise return
* a -1 to indicate failure.
*
* #param title the title of the note
* #param body the body of the note
* #return rowId or -1 if failed
*/
public long createItem(String title, String price) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_PRICE, price);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Delete the note with the given rowId
*
* #param rowId id of note to delete
* #return true if deleted, false otherwise
*/
public boolean deleteItem(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
/**
* Return a Cursor over the list of all notes in the database
*
* #return Cursor over all notes
*/
public Cursor fetchAllItems() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_PRICE}, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the note that matches the given rowId
*
* #param rowId id of note to retrieve
* #return Cursor positioned to matching note, if found
* #throws SQLException if note could not be found/retrieved
*/
public Cursor fetchItem(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_PRICE}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Update the note using the details provided. The note to be updated is
* specified using the rowId, and it is altered to use the title and body
* values passed in
*
* #param rowId id of note to update
* #param title value to set note title to
* #param body value to set note body to
* #return true if the note was successfully updated, false otherwise
*/
public boolean updateItem(long rowId, String title, String price) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_PRICE, price);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
I'm still learning, so any help or advice would be appricieated.
Most probably, you change the SQL statement defined in your DATABASE_CREATE String and than you change your database version.
Changing the database version, onUpgrade() is called and the SQL statement inside it is called:
db.execSQL("DROP TABLE IF EXISTS notes");
This try to remove a table the probably does not exists.
Then the onCreate() is called and you try to create a table, but since it probably already exsists, nothing happen, but your table remains the one you created in the version 1.
So, the solutions can either be:
Unistall the app from your device and reinstall it (the previous version of the database will be deleted)
Remove the instruction:
db.execSQL("DROP TABLE IF EXISTS notes");
and use:
db.execSQL("DROP TABLE IF EXISTS grocery");
In your DATABASE_CREATE query remove semicolon that is inside the string It is causing error
private static final String DATABASE_CREATE =
"create table grocery (_id integer primary key autoincrement, "
+ "title text not null, price text not null)";//removed which was semicolon inside it
Related
I'm trying to insert rows in my Student Table which contains two rows : ID and Name
Here is the addHandler function which is implemented in MyDBHandler class :
public void addHandler(Student student) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, student.getID());
values.put(COLUMN_NAME, student.getStudentName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
The onCreate method is :-
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT )";
db.execSQL(CREATE_TABLE);
}
The attributes of MyDBHandler class which extends SQLiteOpenHelper :
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ID = "StudentID";
public static final String COLUMN_NAME = "StudentName";
I have a ADD Button in my activity_main.xml file and here is the code behind :
public void add(View view){
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
int id = Integer.parseInt(studentIdText.getText().toString());
String name = studentNameText.getText().toString();
Student student = new Student(id, name);
dbHandler.addHandler(student);
studentIdText.setText("");
studentNameText.setText("");
}
The app is running perfectly but when i want to insert a row in the table , i get the following errors in Run Tab :
E/SQLiteLog: (1) table Student has no column named StudentID
E/SQLiteDatabase: Error inserting StudentName=yassine StudentID=10
android.database.sqlite.SQLiteException: table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.test.MyDBHandler.addHandler(MyDBHandler.java:48)
at com.example.test.MainActivity.add(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5246)
at android.widget.TextView.performClick(TextView.java:10566)
at android.view.View$PerformClick.run(View.java:21256)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Any recommendations ?
Your issue is very likely a mis-conception in regard to the onCreate method. That is it onCreate doesn't run every time the App is run. onCreate will only run if the database doesn't actually exist. If the database has already been created by another previous run of the App then the onCreate method is not run.
As such any changes made to the structure of the database, as typically applied in the onCreate method will not be applied.
It would appear that you have added the defnition for the StudentId column, to the code in the onCreate method, after the App has been run.
As long as you have no data that needs to be preserved (which is very likely) then the simplest solution is to do 1 of the following :-
delete or clear the App's data (via settings/Apps)
uninstall the App
and then rerun the App, the database will then be created using the code as per the modified onCreate code.
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.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 5 years ago.
I have a Table named as notes and a method called getlist() which retrieve data from the database. Now the problem is when getlist() method is executed the application crashes and it says that no such column DeletedNotes even tho it is specified in create table statement.
Here is my code:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DB_Name="Notes.db";
public static final int DB_Version=1;
public static final String Table_Name="NoteData";
public static final String id="_id";
public static final String Note_Title="noteTitle";
public static final String Note_Text="NoteText";
public static final String Note_Created="NoteCreated";
public static final String DELETED_NOtes="DeletedNotes";
public static final String Archived_Notes="ArchiveNotes";
public static final int True=1;
public static final int False=0;
//SQLite Query
public static final String Table_Create=
"CREATE TABLE "+Table_Name+"("
+id+" INTEGER PRIMARY KEY, "
+Note_Title+" TEXT, "
+Note_Text+" TEXT, "
+Note_Created+" TEXT default CURRENT_TIMESTAMP, "
+DELETED_NOtes+"INTEGER DEFAULT "+False+", "
+Archived_Notes+"INTEGER DEFAULT "+False+" "
+");";
public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_Name, null, DB_Version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(Table_Create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+Table_Name);
onCreate(sqLiteDatabase);
}
public Cursor getList(){
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
Cursor data=sqLiteDatabase.rawQuery("Select * from "+Table_Name+" WHERE "+DELETED_NOtes+" = "+False+" AND "+Archived_Notes+" = "+False+"; ",null);
return data;
}
and here is my logcat:
08-26 18:52:14.812 8731-8731/com.example.chirag.stickynotes E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chirag.stickynotes, PID: 8731
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chirag.stickynotes/com.example.chirag.stickynotes.MainActivity}: android.database.sqlite.SQLiteException: no such column: DeletedNotes (code 1): , while compiling: Select * from NoteData WHERE DeletedNotes = 0 AND ArchiveNotes = 0;
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: DeletedNotes (code 1): , while compiling: Select * from NoteData WHERE DeletedNotes = 0 AND ArchiveNotes = 0;
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.example.chirag.stickynotes.DBOpenHelper.getList(DBOpenHelper.java:85)
at com.example.chirag.stickynotes.TextFragment.onCreateView(TextFragment.java:64)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:554)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6696)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
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)
08-26 18:52:14.893 1585-1662/system_process W/ActivityManager: Force finishing activity com.example.chirag.stickynotes/.MainActivity
08-26 18:52:15.121 1585-3167/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
08-26 18:52:15.121 1585-3167/system_process D/OpenGLRenderer: Swap behavior 1
You should leave space beside the column name, DELETED_NOtes and Archived_Notes. In your code, since you don't have space between the column name and the type INTEGER, the table would have got created with a column name like this: DeletedNotesINTEGER
public static final String Table_Create =
"CREATE TABLE "+Table_Name +"("
+id+" INTEGER PRIMARY KEY, "
+Note_Title+" TEXT, "
+Note_Text+" TEXT, "
+Note_Created+" TEXT default CURRENT_TIMESTAMP, "
+DELETED_NOtes+" INTEGER DEFAULT "+False+", "
+Archived_Notes+" INTEGER DEFAULT "+False+" "
+");";
my friends help me do this android app, but i dont really know what is the actual problems here. Can you guys help me? I try to run the code in the android, but when i try to login in my app login menu, it crashes
Here is my Database Helper
package com.example.ikramhs.shoerack;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "login";
private static final int DB_VERSION = 1;
private static final String DB_TABLE = "create table user (id integer primary key autoincrement, " + "username text not null,password text not null;";
public DatabaseHelper(Context context){
super(context, DB_NAME, null,DB_VERSION) ;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade (SQLiteDatabase database, int oldVersion, int newVersion ){
Log.w(DatabaseHelper.class.getName(),
"Upgrading database from version" + oldVersion + "to " + newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS user");
onCreate(database);
}
}
and here is my Database Adapter file
package com.example.ikramhs.shoerack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
private static final String LOGIN_TABLE = "user";
public static final String COL_ID = "id";
public static final String COL_USERNAME = "username";
public static final String COL_PASSWORD = "password";
private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() {
dbHelper = new DatabaseHelper(context) ;
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createUser (String username, String password)
{
ContentValues initialValues = createUserTableContentValues ( username,password );
return database.insert(LOGIN_TABLE,null,initialValues);
}
public Cursor fetchUser(String username, String password)
{
Cursor myCursor = database.query(LOGIN_TABLE, new String[] {COL_ID, COL_USERNAME, COL_PASSWORD},
COL_USERNAME + "=" + username + "'AND" + COL_PASSWORD + "='" + password + "'", null,null,null,null);
if (myCursor != null) {
myCursor.moveToFirst();
}
return myCursor;
}
private ContentValues createUserTableContentValues(String username, String password) {
ContentValues values = new ContentValues();
values.put(COL_USERNAME, username);
values.put(COL_PASSWORD, password);
return values;
}
}
Here's the logcat in Android Monitor
02-02 01:55:48.439 2659-2659/com.example.ikramhs.shoerack I/art: Not late-enabling -Xcheck:jni (already on)
02-02 01:55:48.585 2659-2659/com.example.ikramhs.shoerack W/System: ClassLoader referenced unknown path: /data/app/com.example.ikramhs.shoerack-2/lib/x86
02-02 01:55:48.639 2659-2672/com.example.ikramhs.shoerack D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-02 01:55:48.725 2659-2672/com.example.ikramhs.shoerack I/OpenGLRenderer: Initialized EGL, version 1.4
02-02 01:55:48.770 2659-2672/com.example.ikramhs.shoerack W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 01:55:48.770 2659-2672/com.example.ikramhs.shoerack W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad920680, error=EGL_SUCCESS
02-02 01:55:49.803 2659-2665/com.example.ikramhs.shoerack W/art: Suspending all threads took: 23.765ms
02-02 01:55:53.288 2659-2672/com.example.ikramhs.shoerack E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab9c45a0
02-02 01:55:54.230 2659-2665/com.example.ikramhs.shoerack W/art: Suspending all threads took: 8.143ms
02-02 01:55:54.294 2659-2672/com.example.ikramhs.shoerack W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 01:55:54.294 2659-2672/com.example.ikramhs.shoerack W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad926e60, error=EGL_SUCCESS
02-02 01:56:08.158 2659-2659/com.example.ikramhs.shoerack E/SQLiteLog: (1) near "'ANDpassword='": syntax error
02-02 01:56:08.159 2659-2659/com.example.ikramhs.shoerack D/AndroidRuntime: Shutting down VM
02-02 01:56:08.159 2659-2659/com.example.ikramhs.shoerack E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ikramhs.shoerack, PID: 2659
android.database.sqlite.SQLiteException: near "'ANDpassword='": syntax error (code 1): , while compiling: SELECT id, username, password FROM user WHERE username=therhaman'ANDpassword='091192'
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.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.example.ikramhs.shoerack.DatabaseAdapter.fetchUser(DatabaseAdapter.java:42)
at com.example.ikramhs.shoerack.welcome.LogMeIn(welcome.java:68)
at com.example.ikramhs.shoerack.welcome.access$000(welcome.java:17)
at com.example.ikramhs.shoerack.welcome$1.onClick(welcome.java:46)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java: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)
02-02 01:56:09.955 2659-2659/? I/Process: Sending signal. PID: 2659 SIG: 9
android.database.sqlite.SQLiteException: near "'ANDpassword='": syntax error (code 1): , while compiling: SELECT id, username, password FROM user WHERE username=therhaman'ANDpassword='091192'
You need a space between AND and password.
Your Logcat is clearly said it "near "'ANDpassword='": syntax error (code 1)".
You have SQL syntax error and I believe it should be "AND password=". Change below line such that it becomes (space after COL_PASSWORD):
COL_USERNAME + "=" + username + "' AND " + COL_PASSWORD + "='" + password + "
I know that there are a lot of topics on this error but I tried a lot of solutions and still I am stuck whit this error.
It´s my first time playing around with SQLite, and I don´t understand what is happening wrong there.
05-26 08:34:20.369 23124-23124/com.danynuria.fmp D/ODOperations﹕ Overall Table Created
05-26 08:34:20.373 23124-23124/com.danynuria.fmp E/SQLiteLog﹕ (1) no such table: database_info
05-26 08:34:20.374 23124-23124/com.danynuria.fmp E/SQLiteDatabase﹕ Error inserting date=26 / 4 / 2015 county=Bedfordshire co2_saved=149 distance=1245 distance_type=run user_id=1
android.database.sqlite.SQLiteException: no such table: database_info (code 1): , while compiling: INSERT INTO database_info(date,county,co2_saved,distance,distance_type,user_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:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.danynuria.fmp.OverallDatabaseOperations.putInformation(OverallDatabaseOperations.java:73)
at com.danynuria.fmp.MainActivity$1.onClick(MainActivity.java:121)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-26 08:34:20.374 23124-23124/com.danynuria.fmp D/ODOperations﹕ One row inserted
And my code:
package com.danynuria.fmp;
import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.danynuria.fmp.OverallTableData.OverallTableinfo;
import java.sql.SQLException;
public class OverallDatabaseOperations extends SQLiteOpenHelper {
// Create integer that register version of database
private static final int overallDatabase_version = 1;
// Create query
public String CREATE_QUERY = "CREATE TABLE "+OverallTableinfo.OVERALL_TABLE_NAME+"( "+OverallTableinfo.USER_ID+" INTEGER, "+OverallTableinfo.DISTANCE+
" INTEGER, "+OverallTableinfo.DISTANCE_TYPE+" TEXT, "+OverallTableinfo.COUNTY+" TEXT, "+OverallTableinfo.CO2_SAVED+
" INTEGER, "+OverallTableinfo.DATE+" TEXT);";
// Creating the database using SQLiteOpenHelper constructor
public OverallDatabaseOperations(Context context) {
super(context, OverallTableinfo.OVERALL_DATABASE_NAME, null, overallDatabase_version);
}
public void onCreate(SQLiteDatabase odb ){
odb.execSQL(CREATE_QUERY);
Log.d("ODOperations", "Overall Table Created");
}
public void onUpgrade(SQLiteDatabase arg0,int arg1, int arg2){
}
// Create a method to insert data into database
public void putInformation(OverallDatabaseOperations dop, Integer id, Integer distance, String type, String county, Integer co2saved, String date) {
// Create a SQLite database object
SQLiteDatabase OSQ = dop.getWritableDatabase();
// Create an object for content values
ContentValues ncv = new ContentValues();
// Passing the first column value
ncv.put(OverallTableinfo.USER_ID, id);
ncv.put(OverallTableinfo.DISTANCE, distance);
ncv.put(OverallTableinfo.DISTANCE_TYPE, type);
ncv.put(OverallTableinfo.COUNTY, county);
ncv.put(OverallTableinfo.CO2_SAVED, co2saved);
ncv.put(OverallTableinfo.DATE, date);
// Inserting data into table
OSQ.insert(OverallTableinfo.OVERALL_DATABASE_NAME, null, ncv);
Log.d("ODOperations", "One row inserted");
}
}
And the other class:
package com.danynuria.fmp;
import android.provider.BaseColumns;
public class OverallTableData {
// Create constructor
public OverallTableData() {
}
// Create abstract class
public static abstract class OverallTableinfo implements BaseColumns {
// Create first column in database
public static final String USER_ID = "user_id";
// Create second column in database
public static final String DISTANCE = "distance";
// Create third column in database
public static final String DISTANCE_TYPE = "distance_type";
// Create forth column in database
public static final String COUNTY = "county";
// Create fifth column in database
public static final String CO2_SAVED = "co2_saved";
// Create sixth column in database
public static final String DATE = "date";
// Define database name
public static final String OVERALL_DATABASE_NAME = "database_info";
// Define table name
public static final String OVERALL_TABLE_NAME = "overall_info";
}
}
Any suggestions are highly appreciated
you have to use OVERALL_TABLE_NAME instead of OVERALL_DATABASE_NAME in your insert:
OSQ.insert(OverallTableinfo.OVERALL_TABLE_NAME, null, ncv);