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.
Related
I have got stuck in the above-mentioned error message in Android Studio. My Database is a simple one
1st column: Name TEXT PRIMARY KEY
2nd column: Price TEXT
I have already gone through the answers to the same question in StackOverflow but couldn't resolve the error.
I am quoting my DataBaseHelper class and insertActivity here:
private static final String DATABASE_NAME = "ItemDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "Items";
private static final String COLUMN_NAME = "Name";
private static final String COLUMN_PRICE = "Price";
DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "(" + COLUMN_NAME + " TEXT NOT NULL PRIMARY KEY, " + COLUMN_PRICE + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
boolean addItem(String itemName, String itemPrice) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, itemName);
contentValues.put(COLUMN_PRICE, itemPrice);
SQLiteDatabase db = this.getWritableDatabase();
boolean b = db.insert(TABLE_NAME, null, contentValues) != -1;
db.close();
return b;
}
Cursor getPrice(String itemName) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" SELECT Price FROM Items WHERE Name= ? ", new String[]{itemName});
}
Cursor updatePrice(String itemName, String itemPrice)
{
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" UPDATE Items SET Price= ? WHERE Name= ? ", new String[]{itemPrice,itemName});
}
public List<String> getName(){
List<String> list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
}
public class insertActivity extends AppCompatActivity {
EditText itemName,itemPrice;
Button buttonInsert;
boolean b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
itemName= findViewById(R.id.itemName);
itemPrice= findViewById(R.id.itemPrice);
buttonInsert=findViewById(R.id.buttonInsert);
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
final DataBaseHelper dataBaseHelper =new DataBaseHelper(getApplicationContext());
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
b = dataBaseHelper.addItem(Name,Price);
}catch (Exception e)
{
e.printStackTrace();
}
if( b )
{
Toast.makeText(getApplicationContext(),"Item Inserted Successfully ",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(),"Item Insertion Failed ",Toast.LENGTH_SHORT).show();
}
});
}
}
error:
W/System.err: at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:746)
W/System.err: at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.anirbit.anirbitadak.nirman.DataBaseHelper.addItem(DataBaseHelper.java:45)
W/System.err: at com.anirbit.anirbitadak.nirman.insertActivity$1.onClick(insertActivity.java:39)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25881)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)```
These lines:
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
assign to the variables Name and Price the text of the EditTexts itemName and itemPrice when the insertActivity loads (maybe they are just empty strings) and they are never changed.
So when you click the button the listener by calling dataBaseHelper.addItem(Name,Price) tries to insert the same values in the table and this results to the error you get because since the column Name is the Primary Key of the table it must be unique.
What you must do is move these lines inside the listener:
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
try {
................................................
}
so when you click the button the correct values are retrieved from the EditTexts and then inserted in the table.
i'm trying to make simple signup/login app which uses SQLite database, so far i got this code. This is my "registration" activity which should implement users name and pin(password) to database after pushing register button i guess, sadly the app crashes.
EditText reName, rePin;
Button reRegister;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
reName = (EditText)findViewById(R.id.reName);
rePin = (EditText)findViewById(R.id.rePin);
reRegister = (Button)findViewById(R.id.reRegister);
reRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Imie = reName.getText().toString();
String Haslo = rePin.getText().toString();
Contacts c =new Contacts();
c.setName(Imie);
c.setPass(Haslo);
helper.insertContacts(c);
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
}
});
}
Here's also my DatabaseHelper code, i guess that the problem is somewhere in this code, but i cant really find it. What should i do or where should i find solution for this? :)
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null, pass text not null);";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertContacts(Contacts c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select + from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String name) {
db = this.getReadableDatabase();
String query = "select * from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b = "not found";
if (cursor.moveToFirst()){
do {
a =cursor.getString(2);
if (a.equals(name)){
b= cursor.getString(3);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
#edit - Logcat errors
12-16 13:08:14.316 3541-3541/com.example.mateusz.sqllogowanie E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mateusz.sqllogowanie, PID: 3541
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at com.example.mateusz.sqllogowanie.DatabaseHelper.onCreate(DatabaseHelper.java:36)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:333)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:238)
at com.example.mateusz.sqllogowanie.DatabaseHelper.insertContacts(DatabaseHelper.java:42)
at com.example.mateusz.sqllogowanie.SignUp$1.onClick(SignUp.java:36)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Your SqliteDatabase object is null.
Change this:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE); //db is null here
this.db = db;
}
to:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
this.db = sqLiteDatabase;
db.execSQL(TABLE_CREATE);
}
Also for in your insertContacts() method change query to:
String query = "select * from contacts";
Just look into you query string insertContacts you are using + instead of *
just change query to
String query = "select * from contacts";
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.
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.