I know this has been asked allot but i have checked all the other Questions and none Fixed my problem.
This is the Exception:
E/SQLiteLog: (1) table Traust_Du_Dich_App has no column named name
E/SQLiteDatabase: Error inserting name=Loras gender=Male birthday=21
android.database.sqlite.SQLiteException: table Traust_Du_Dich_App has no column named name (code 1): , while compiling: INSERT INTO Traust_Du_Dich_App(name,gender,birthday) 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.lukas.saufapp.MyDbHandler.addProduct(MyDbHandler.java:57)
at com.lukas.saufapp.MainActivity$3.onClick(MainActivity.java:232)
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)
This is the HelperClass:
public class MyDbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "quadstudios_de";
private static final String TABLE_PRODUCTS = "Traust_Du_Dich_App";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GENDER = "gender";
public static final String COLUMN_BDAY = "birthday";
public MyDbHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," + COLUMN_GENDER + " TEXT," + COLUMN_BDAY + " TEXT" + ")";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
public void AddUser(User user) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, user.Name);
values.put(COLUMN_GENDER, user.Gender);
values.put(COLUMN_BDAY, user.Birthday);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
}
Here I call It:
Btn_FaceBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDbHandler handler = new MyDbHandler(MainActivity.this, null, null, 1);
User user = new User("Thomas", "Male", "21");
handler.AddUser(user);
}
The only problem I can think of is not updating your version number. Whenever you modify the columns in the database, you have to update the version number as well.
Instead of this:
private static final int DATABASE_VERSION = 2;
Try this:
private static final int DATABASE_VERSION = 3;
uninstall the app from the device where you are testing it. This will delete the database. Now reinstall the app so it will recreate the database from the beginning.
Related
I'm trying to select from my database certain row by column "ID_TABLITSY" by using method "getid" but I get an error "no such column in mytable".
Database class code:
public class dbelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "orginizer.db";
private static final int SCHEMA = 2;
static final String TABLE = "mytable";
static final String TABLE_DOM = "table_dom";
static final String TABLE_RAB = "table_rab";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NOTE = "note";
public static final String COLUMN_DATE = "date";
public static final String ID_TABLITSY = "idtable";
public dbelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(LOG_TAG, "--- onCreate database ---");
db.execSQL("create table mytable(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NOTE + " TEXT, " + COLUMN_DATE + " TEXT, " + ID_TABLITSY + " INTEGER);");
db.execSQL("create table table_dom(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NOTE + " TEXT, " + COLUMN_DATE + " TEXT);");
db.execSQL("create table table_rab(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NOTE + " TEXT, " + COLUMN_DATE + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE);
db.execSQL("DROP TABLE IF EXISTS "+TABLE_DOM);
db.execSQL("DROP TABLE IF EXISTS "+TABLE_RAB);
onCreate(db);
}
public Cursor getid(int ID_TABLITS){
SQLiteDatabase db = this.getReadableDatabase();
String sqlQuery = "select * from mytable where ID_TABLITSY = " + ID_TABLITS + ";";
return db.rawQuery(sqlQuery, null);
}
}
and here the way i use this method in the other class
#Override
public void onResume() {
Cursor cursor = dbHelper.getid(1);
if (cursor.moveToFirst()) {
super.onResume();
db = dbHelper.getReadableDatabase();
userCursor = db.rawQuery("select * from " + dbelper.TABLE, null);
String[] headers = new String[]{dbelper.COLUMN_NOTE, dbelper.COLUMN_DATE, dbelper.ID_TABLITSY};
userAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, userCursor, headers, new int[]{android.R.id.text1, android.R.id.text2}, 0);
listView.setAdapter(userAdapter);
}
cursor.close();
}
Error code says that there is no such column but i definitely :
E/SQLiteLog: (1) no such column: ID_TABLITSY
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kp_orginizer, PID: 24010
java.lang.RuntimeException: Unable to resume activity
{com.example.kp_orginizer/com.example.kp_orginizer.MainActivity}:
android.database.sqlite.SQLiteException: no such column: ID_TABLITSY (code 1
SQLITE_ERROR): , while compiling: select * from mytable where ID_TABLITSY = 1;
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4205)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: android.database.sqlite.SQLiteException: no such column: ID_TABLITSY (code 1 SQLITE_ERROR): , while compiling: select * from mytable where ID_TABLITSY = 1;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
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:1443)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)
at com.example.kp_orginizer.dbelper.getid(dbelper.java:76)
at com.example.kp_orginizer.MainActivity.onResume(MainActivity.java:250)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1446)
at android.app.Activity.performResume(Activity.java:7939)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4195)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
ID_TABLITSY is the name of the variable containing the column's name, not the name of the column:
String sqlQuery =
"select * from mytable where " + ID_TABLITSY + " = " + ID_TABLITS + ";";
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 5 years ago.
I am trying to create two tables in SQLite database in my Android application but it shows the following errors. Basically, the second table that I am trying to create won't be created. Any help would be appreciated.
This is the error that I got:
02-22 09:16:33.005 22404-22404/proed.hotelbooking E/SQLiteLog: (1) no such table: room 02-22 09:16:33.007 22404-22404/proed.hotelbooking
E/SQLiteDatabase: Error inserting room_id=1 room_price=1000 room_type=Single hotel_id=1
android.database.sqlite.SQLiteException: no such table: room (code 1): ,
while compiling: INSERT INTO room(room_id,room_price,room_type,hotel_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 proed.hotelbooking.HotelDatabaseHelper.insertRoom(HotelDatabaseHelper.java:70)
at proed.hotelbooking.RoomInfoActivity.onRoomButtonClick(RoomInfoActivity.java:42)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
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)
This is my database helper class. Am I missing something?
public class HotelDatabaseHelper extends SQLiteOpenHelper {
private static int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "hotels";
private static final String TABLE_NAME = "hotel";
private static final String TABLE_ROOM = "room";
private static final String col_id = "id";
private static final String col_name = "hotelName";
private static final String col_location = "location";
private static final String room_id = "room_id";
private static final String room_type = "room_type";
private static final String room_price = "room_price";
private static final String hotel_id = "hotel_id";
private static final String hotel_table = "CREATE TABLE `hotel` ( `id` INTEGER primary key not null, `hotelName` VARCHAR not null, `location` VARCHAR not null )";
private static final String room_table ="CREATE TABLE `room` ( `room_id` INTEGER primary key not null, `room_type` VARCHAR not null, `room_price` VARCHAR not null, `hotel_id` VARCHAR not null )";
SQLiteDatabase db;
private static final String info = "DATABASE";
public HotelDatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(hotel_table);
db.execSQL(room_table);
Log.i(info, "Created!!!!!!!!!");
}
public void insertHotel(Hotels h)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(col_id, h.getId());
values.put(col_name, h.getHotelName());
values.put(col_location, h.getLocation());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void insertRoom(Hotels hotel)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(room_id, hotel.getRoom_id());
values.put(room_price, hotel.getRoom_price());
values.put(room_type, hotel.getRoom_type());
values.put(hotel_id, hotel.getHotel_id());
db.insert(TABLE_ROOM, null, values);
db.close();
}
public Cursor getListContents()
{
db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ROOM);
onCreate(db);
}
}
This is my class to insert data:
public class RoomInfoActivity extends AppCompatActivity {
HotelDatabaseHelper helper = new HotelDatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_info);
}
public void onRoomButtonClick(View v)
{
if (v.getId()==R.id.addRoom) {
EditText id = findViewById(R.id.roomId);
EditText type = findViewById(R.id.roomType);
EditText price = findViewById(R.id.roomPrice);
EditText hotel_id = findViewById(R.id.hotelID);
String room_id = id.getText().toString();
String room_type = type.getText().toString();
String room_price = price.getText().toString();
String hotelID = hotel_id.getText().toString();
if (TextUtils.isEmpty(room_id) || TextUtils.isEmpty(room_type) || TextUtils.isEmpty(room_price) || TextUtils.isEmpty(hotelID)) {
Toast.makeText(this, "Please do not leave any field blank! ", Toast.LENGTH_SHORT).show();
return;
} else {
Hotels hotels = new Hotels();
hotels.setRoom_id(room_id);
hotels.setRoom_price(room_price);
hotels.setRoom_type(room_type);
hotels.setHotel_id(hotelID);
helper.insertRoom(hotels);
//Toast.makeText(this, "Data Added To The Database", Toast.LENGTH_SHORT).show();
}
}
}
public void onViewRoomButtonClick(View view)
{
if (view.getId()==R.id.viewRoom)
{
Intent intent = new Intent(RoomInfoActivity.this, ViewRoomContents.class);
startActivity(intent);
}
}
}
If you modified the database, for example add/remove table/column, you need to
uninstall the app from the emulator/device and then reinstall it.
If that not works, just go to File and click on Invalidate Caches/Restart
I've checked your DatabaseHelper and it has no problem.
Could you show the code for init database and insert data?
Maybe the issue come from initial steps.
enter code hereAm making an application that displays a list of items in a listview and a button to add more items to the listview , and I want to insert those new items to the SQLite database using the same button .
I created a table with 2 Colons (ID , ITEM1 ) Like this :
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1 TEXT) ";
db.execSQL(createTable);
}
but when i added 3 more Colons to the table , i could not insert any data to the database !!
I tried to search for solutions but didn't get any chance Well Am a Beginner in SQLite and its Confusing me, how can I solve this?
here is the
Database.java
package com.example.bilel.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="foodlist.db";
public static final String TABLE_NAME="foodlist_data";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM1";
public static final String COL3 = "CAL1";
public static final String COL4 = "PRO1";
public static final String COL5 = "CARB1";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1 TEXT) ";*/
String createTable = "CREATE TABLE" + TABLE_NAME + " (" +
COL1 + "ID INTEGER PRIMARY KEY AUTOINCREMENT," +
COL2 + "TEXT NOT NULL,"+
COL3 + "INTEGER NOT NULL,"+
COL4 + "INTEGER NOT NULL,"+
COL5 + "INTEGER NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS"+TABLE_NAME);
onCreate(db);
}
///Add new row to the database
public boolean additems (String item,int C,int P,int R){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL2,item);
values.put(COL3,C );
values.put(COL4,P);
values.put(COL5,R);
long result = db.insert(TABLE_NAME,null,values);
if (result==-1){
return false;
}else{
return true;
}
}
public void clearDatabase(String TABLE_NAME) {
String clearDBQuery = "DELETE FROM "+TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(clearDBQuery);
}
public int LastInsert() {
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "SELECT MAX(" + COL1 + ") FROM " + TABLE_NAME;
Cursor cur = db.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
public void LastDelete(){
//String clearROW = "DELETE FROM "+TABLE_NAME "WHERE " = "(SELECT MAX(id) FROM notes)";
SQLiteDatabase db = this.getWritableDatabase();
long id = LastInsert();
db.delete(TABLE_NAME,COL1+"=?",new String[]{Long.toString(id)});
db.close();
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
Crash Log
11-23 13:56:02.746 3926-3926/com.example.bilel.myapplication E/SQLiteLog: (1) near "TABLEfoodlist_data": syntax error
11-23 13:56:02.746 3926-3926/com.example.bilel.myapplication D/AndroidRuntime: Shutting down VM
11-23 13:56:02.747 3926-3926/com.example.bilel.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bilel.myapplication, PID: 3926
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bilel.myapplication/com.example.bilel.myapplication.CalculatorActivity}: android.database.sqlite.SQLiteException: near "TABLEfoodlist_data": syntax error (code 1): , while compiling: CREATE TABLEfoodlist_data (ID ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM1 TEXT NOT NULL,CAL1 INTEGER NOT NULL,PRO1 INTEGER NOT NULL,CARB1 INTEGER NOT NULL);
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: near "TABLEfoodlist_data": syntax error (code 1): , while compiling: CREATE TABLEfoodlist_data (ID ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM1 TEXT NOT NULL,CAL1 INTEGER NOT NULL,PRO1 INTEGER NOT NULL,CARB1 INTEGER NOT NULL);
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.bilel.myapplication.DatabaseHelper.onCreate(DatabaseHelper.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.bilel.myapplication.DatabaseHelper.getListContents(DatabaseHelper.java:94)
at com.example.bilel.myapplication.CalculatorActivity.onCreate(CalculatorActivity.java:78)
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)
You have to add spaces here before each type:
String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL2 + " TEXT NOT NULL,"+
COL3 + " INTEGER NOT NULL,"+
COL4 + " INTEGER NOT NULL,"+
COL5 + " INTEGER NOT NULL);";
And Remove ID
Have you upgrade your db version ??
private static final int DATABASE_VERSION = 2;//from 1 to 2
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) // constructor
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//Changes in db mentioned here
}
}
Try writing the actual SQL until you get comfortable with String concatenation.
CREATE TABLEfoodlist_data (ID ID INTEGER
You need spaces around the table name, and you put ID twice. (You should name it as _id anyway)
What is the use of BaseColumns in Android
I have a game in which I want to make a top 10 results and the results are going to be made of 2 things - difficulty (easy, medium, hard) and score(integer). So far I am trying for sometime now to understand how this SQLite works in Android studio and I am still confused but after reading several tutorials here is what I managed to put together: DBHandler class
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "highscores";
private static final String TABLE_DETAIL = "scores";
private static final String KEY_ID = "id";
private static final String KEY_TIME = "time";
private static final String KEY_DIFFICULTY = "difficutly";
public DBHandler(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HIGHSCORES_TABLE = "CREATE TABLE" + TABLE_DETAIL + "("
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_TIME + " TEXT, "
+ KEY_DIFFICULTY + " TEXT, ";
db.execSQL(CREATE_HIGHSCORES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAIL); // tova maha starata tablica ako s16testvuva
onCreate(db); // tova q pravi nanovo
}
// Adding new score
public void addScore(int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TIME, score); // score value
// Inserting Values
db.insert(TABLE_DETAIL, null, values);
db.close();
}
// Getting All Scores
public String[] getAllScores() {
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DETAIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
int i = 0;
String[] data = new String[cursor.getCount()];
while (cursor.moveToNext()) {
data[i] = cursor.getString(1);
i = i++;
}
cursor.close();
db.close();
// return score array
return data;
}
}
This class below, I don't know why it is even required but I saw it in every tutorial so I copy it...
public class Contact {
//private variables
int _id;
String difficulty;
String time;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String name, String _phone_number){
this._id = id;
this.difficulty = name;
this.time = _phone_number;
}
// constructor
public Contact(String name, String _phone_number){
this.difficulty = name;
this.time = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this.difficulty;
}
// setting name
public void setName(String name){
this.difficulty = name;
}
and the last class
public class highscores extends Activity {
private ListView scorebox;
#Override
protected void onCreate(Bundle savedInstanceState) {
DBHandler db = new DBHandler(this);
scorebox = (ListView) findViewById(R.id.scorebox);
super.onCreate(savedInstanceState);
setContentView(R.layout.highscores);
Log.d("Insert: ", "Inserting ..");
db.addScore(9000);
Log.d("Reading: ", "Reading all contacts..");
}
}
I tried in the last class to put some data just to test the database but application crashes as soon as I click the button to open the database and this is where I gave up and decided to ask for help.
The error is a very long one:
FATAL EXCEPTION: main
Process: com.example.user.myapplication, PID: 24731
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.myapplication/com.example.user.myapplication.highscores}: android.database.sqlite.SQLiteException: near "TABLEscores": syntax error (code 1): , while compiling: CREATE TABLEscores(id INTEGER PRIMARY KEY, time TEXT, difficutly TEXT,
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: near "TABLEscores": syntax error (code 1): , while compiling: CREATE TABLEscores(id INTEGER PRIMARY KEY, time TEXT, difficutly TEXT,
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.user.myapplication.DBHandler.onCreate(DBHandler.java:34)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.user.myapplication.DBHandler.addScore(DBHandler.java:46)
at com.example.user.myapplication.highscores.onCreate(highscores.java:25)
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)
There is syntax error in your sql.
android.database.sqlite.SQLiteException: near "TABLEscores": syntax error (code 1): , while compiling: CREATE TABLEscores(id INTEGER PRIMARY KEY, time TEXT, difficutly TEXT,
It should be space after TABLE.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I have looked through SO and found many people having this same error, but they seem to be forgetting to add the column into the create statement or missing whitespace, neither of which I believe I did.
My logcat is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmd.referenceapplication, PID: 31988
android.database.sqlite.SQLiteException: no such column: QUANTITY (code 1): , while compiling: SELECT * FROM FTS WHERE (QUANTITY MATCH ?)
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.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.gmd.referenceapplication.DatabaseTable.query(DatabaseTable.java:187)
at com.gmd.referenceapplication.DatabaseTable.getWordMatches(DatabaseTable.java:179)
at com.gmd.referenceapplication.SearchableActivity$1.onQueryTextChange(SearchableActivity.java:70)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7991)
at android.widget.TextView.handleTextChanged(TextView.java:8053)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10157)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1033)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:559)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:491)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
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)
DatabaseTable class:
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTITY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
public static final String _id = "_id";
//name, tbale name, version
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
private final Context mcontext;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
mcontext = context;
}
private class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private final MyDataProvider dp = new MyDataProvider(mcontext);
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +_id+ " INTEGER PRIMARY KEY,"+
COL_QUANTITY + " TEXT, " +
COL_VALUE + " TEXT," +
COL_UNCERTAINTY + " TEXT," +
COL_UNIT + " TEXT " + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
loadConstants();
Log.e("Database Operation", "DatabaseOpenHelper constructor called, constants loaded?");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#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 " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
public SQLiteDatabase getmDatabase(){
return mDatabase;
}
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
HashMap map = dp.getAllMap();
Iterator<Map.Entry<String, ListViewItem>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, ListViewItem> entry = entries.next();
Log.d("thing:", entry.getKey());
//addConstant(entry.getKey(), entry.getValue(), entry.getUncertainty(), entry.getUnit());
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
return db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
//database openhelper ends
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
public Cursor getAllTitles(){
return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
COL_QUANTITY,
COL_UNCERTAINTY,
COL_UNIT,
COL_VALUE},
null,
null,
null,
null,
null);
}
Thank you to anyone who can tell me why it is telling me the column "QUANTITY" is not being created, I really don't know.
If you change the schema you should increment DATABASE_VERSION so the database is upgraded.