Android app crashes when saving data to database
This is the class where I am capturing data from the user. The first button is working as expected but the second causes crash.
public class ActualSalesTracker extends Activity implements OnClickListener {
DbAdapter db = new DbAdapter(this);
Button BtnSalesCal, BtnAddRecordDB, BtnViewRecordsDB;
EditText item_name, item_cost, item_price_value, item_postage, actual_pl;
SalesProfitLossCal actSalesCal = new SalesProfitLossCal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actual_sales_tracker);
Button salesCalBtn = (Button) findViewById(R.id.BtnSalesCal);
// register the click event with the sales calculating profit/loss button
salesCalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get EditText by id to represent the value of the item stock
// cost and store it as a double
EditText itemCostString = (EditText) findViewById(R.id.item_cost);
String ic = itemCostString.getText().toString();
double itemCost = Double.valueOf(ic).doubleValue();
// get EditText by id to represent the value of the post and
// packaging cost and store it as a double
EditText itemPostageString = (EditText) findViewById(R.id.item_postage);
String ipapc = itemPostageString.getText().toString();
double itemPostage = Double.valueOf(ipapc).doubleValue();
// get EditText by id to represent the value of the selling
// price and store it as a double
EditText itemPriceValueString = (EditText) findViewById(R.id.item_price_value);
String sp = itemPriceValueString.getText().toString();
double itemPriceValue = Double.valueOf(sp).doubleValue();
double actTotalCost = actSalesCal.ActTotalCostCal(itemCost,
itemPostage, itemPriceValue);
double actualProfitLoss = actSalesCal
.calculateProfitLossGenerated(itemPriceValue,
actTotalCost);
String ActualProfitLossString = String.format(
"You made £ %.2f", actualProfitLoss);
TextView ActualProfitLossView = (TextView) findViewById(R.id.yourActualPL);
ActualProfitLossView.setText(ActualProfitLossString);
}
});
//activate the add record button
Button addRecordDB = (Button) findViewById(R.id.BtnAddRecordDB);
// register the click event with the add record button
addRecordDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText nameText= (EditText)findViewById(R.id.item_name);
String name = nameText.getText().toString();
EditText costText=(EditText)findViewById(R.id.item_cost);
String cost=costText.getText().toString();
EditText priceText=(EditText)findViewById(R.id.item_price_value);
String price=priceText.getText().toString();
EditText postageText=(EditText)findViewById(R.id.item_postage);
String postage=postageText.getText().toString();
TextView profitlossText=(TextView)findViewById(R.id.actual_pl);
String profitloss=profitlossText.getText().toString();
db.open();
long id=db.insertRecord(name, cost, price, postage, profitloss);
db.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is my database adapter.
public class DbAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM_NAME = "name";
public static final String KEY_ITEM_COST = "cost";
public static final String KEY_ITEM_PRICE_VALUE = "price";
public static final String KEY_ITEM_POSTAGE = "postage";
public static final String KEY_ACTUAL_PL = "profitloss";
private static final String TAG = "DbAdapter";
private static final String DATABASE_NAME = "eBaySalesDB";
private static final String DATABASE_TABLE = "actualSales";
private static final int DATABASE_VERSION = 1;
private DatabaseHelper mDbHelper;
private SQLiteDatabase db;
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
private final Context mCtx;
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 " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* constructor - takes the context to allow the database to be opened /
* created
*
* #param ctx
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* open up the database. If it cannot be opened it will try to create a new
* instance of the database. if this can't be created it will throw an
* exception
*
* #return this (self reference)
* #throws SQLException
* (if the database can't be opened or closed.
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
db = mDbHelper.getWritableDatabase();
return this;
}
/**
* Method to close the code off to others
*/
public void close() {
mDbHelper.close();
}
/**
* method to insert a record into the database
*/
public long insertRecord(String name, String cost, String price,
String postage, String profitloss) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM_NAME, name);
initialValues.put(KEY_ITEM_COST, cost);
initialValues.put(KEY_ITEM_PRICE_VALUE, price);
initialValues.put(KEY_ITEM_POSTAGE, postage);
initialValues.put(KEY_ACTUAL_PL, profitloss);
return db.insert(DATABASE_TABLE, null, initialValues);
}
/**
* method to delete a record from the database
*/
public boolean deleteRecord(long id) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
}
/**
* method to retrieve all the records
*/
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, null, null, null, null,
null, null);
}
/**
* method to retrieve a particular record
*/
public Cursor getRecord(long id) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, KEY_ROWID + "=" + id, null,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* method to update a record
*/
public boolean updateRecord(long id, String name, String cost,
String price, String postage, String profitloss) {
ContentValues args = new ContentValues();
args.put(KEY_ITEM_NAME, name);
args.put(KEY_ITEM_COST, cost);
args.put(KEY_ITEM_PRICE_VALUE, price);
args.put(KEY_ITEM_POSTAGE, postage);
args.put(KEY_ACTUAL_PL, profitloss);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
Logcat error log:
05-06 03:55:58.690: E/AndroidRuntime(1251): FATAL EXCEPTION: main
05-06 03:55:58.690: E/AndroidRuntime(1251): Process: com.example.eventbuilder, PID: 1251
05-06 03:55:58.690: E/AndroidRuntime(1251): android.database.sqlite.SQLiteException: near "existsactualSales": syntax error (code 1): , while compiling: create table if not existsactualSales(idinteger primary key autoincrement, nametext not null,costtext not null,pricetext not null,postagetext not null,profitlosstext not null);
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1672)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.DbAdapter$DatabaseHelper.onCreate(DbAdapter.java:51)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.DbAdapter.open(DbAdapter.java:85)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.ActualSalesTracker$2.onClick(ActualSalesTracker.java:92)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.view.View.performClick(View.java:4438)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.view.View$PerformClick.run(View.java:18422)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Handler.handleCallback(Handler.java:733)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Handler.dispatchMessage(Handler.java:95)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Looper.loop(Looper.java:136)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 03:55:58.690: E/AndroidRuntime(1251): at java.lang.reflect.Method.invokeNative(Native Method)
05-06 03:55:58.690: E/AndroidRuntime(1251): at java.lang.reflect.Method.invoke(Method.java:515)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 03:55:58.690: E/AndroidRuntime(1251): at dalvik.system.NativeStart.main(Native Method)
You need whitespace between identifiers and keywords here:
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
Change to
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
change this line from
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
to
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
you need space between your table name and Create table name syntax
You are missing spaces in between keywords and identifiers. It should be
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
Also in future, if you get any syntax errors in SQL commands try running them in SQLite. It will help you identify any errors in syntax.
Theres a simple Firefox addon for SQLite manager
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 + ";";
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 local database in my app for storing user profiles from input fields. I have created the database using SQLiteOpenHelper class but after running my app, this error appears. I have been through the DatabaseHelper class but can't find what's wrong with it. I hope someone points out my mistake. Thanks.
my db class file here:
public class DBHelper {
private static final String DATABASE_NAME = "UsersDemo.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
//private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
long result = userDb.insert(TABLE_NAME, null, values);
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(TABLE_NAME, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(TABLE_NAME, null, contentValues);
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
}
The error occurs in my MainActivity when I call saveInputField() method of DBHelper, shown below:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId)){
if (dbHelper.saveInputField(user) == true){ // error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show(); // Toast shows cos save failed, dont know why
}
}
Sorry guys, my mainactivity is too long, only showed what is necessary.
Error message in logcat:
android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization 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:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.billionusers.tingting.db.DBHelper$DatabaseManager.onCreate(DBHelper.java:131)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:53)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:466)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:443)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
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)
From the logcat
near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
and DBHelper.onCreate
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
Your create statement is invalid because you have put into comments the last line so it terminates in + COL_ORGANIZATION + " TEXT, "; which is not correct. The ending should be:
+ COL_ORGANIZATION + " TEXT ); ";
I have seen many times that I can't find the solution of no column named. Can anyone please help me?
Thank you very much in advance :)
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" +
KEY_NAME + " TEXT NOT NULL," +
KEY_CODE + " TEXT NOT NULL," +
KEY_NUMBER + " TEXT NOT NULL," +")";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "LuggageDataCenter";
// Contacts table name
private static final String TABLE_CONTACTS = "luggage";
// Contacts Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_CODE = "code";
private static final String KEY_NUMBER = "number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Luggage luggage) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, luggage.getName()); // Contact Name
values.put(KEY_CODE, luggage.getCode()); // Contact Phone
// values.put(KEY_NUMBER, luggage.getNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Luggage> getAllContacts() {
List<Luggage> contactList = new ArrayList<Luggage>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Luggage luggage = new Luggage();
luggage.setName(cursor.getString(0));
// luggage.setCode(cursor.getString(1));
// luggage.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(luggage);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
Stacktrace
01-07 18:45:43.070: I/Adreno200-EGL(16078): Reconstruct Branch: NOTHING
01-07 18:45:51.950: W/IInputConnectionWrapper(16078): showStatusIcon on inactive InputConnection
01-07 18:45:53.600: E/SQLiteDatabase(16078): Error inserting code=100000HKG name=Lee Chung Ming
01-07 18:45:53.600: E/SQLiteDatabase(16078): android.database.sqlite.SQLiteConstraintException: luggage.number may not be NULL (code 19)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:787)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at com.airportapplication.app.DatabaseHandler.addContact(DatabaseHandler.java:64)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at com.airportapplication.app.LuggageVer.onActivityResult(LuggageVer.java:87)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.Activity.dispatchActivityResult(Activity.java:5197)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.ActivityThread.deliverResults(ActivityThread.java:3160)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3207)
I have already reinstalled the app, but still not work.
you added extra , & + at the end so please format it properly like below:
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL);";
I'm getting and error like the one showed belowe when I try to put a new entry in my database. I search trough it for hours now, but I'm not able to detect whats wrong. Any input would be superb!
Here is the error from LogCat.
02-27 23:02:51.451: E/SQLiteLog(6777): (1) table dager has no column named brutto
02-27 23:02:51.451: E/SQLiteDatabase(6777): Error inserting brutto=0 date=21.03.2013
hours=4
02-27 23:02:51.451: E/SQLiteDatabase(6777): android.database.sqlite.SQLiteException:
table dager has no column named brutto (code 1): , while compiling: INSERT INTO
dager(brutto,date,hours) VALUES (?,?,?)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at com.adev.timelonn.DatabaseHandler.addDay(DatabaseHandler.java:79)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at com.adev.timelonn.AddHours.onClick(AddHours.java:99)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.view.View.performClick(View.java:4084)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.view.View$PerformClick.run(View.java:16966)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Handler.handleCallback(Handler.java:615)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Handler.dispatchMessage(Handler.java:92)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Looper.loop(Looper.java:137)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.app.ActivityThread.main(ActivityThread.java:4931)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at java.lang.reflect.Method.invoke(Method.java:511)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at dalvik.system.NativeStart.main(Native
Method)
My database file.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "timeliste";
// Contacts table name
private static final String TABLE_DAYS = "dager";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_DATE = "date";
private static final String KEY_HOURS = "hours";
private static final String KEY_UB = "ub";
private static final String KEY_BRUTTO = "brutto";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db)
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HOURS + " INTEGER,
"
+ KEY_UB + " INTEGER," + KEY_BRUTTO + "INTEGER," + ")";
db.execSQL(CREATE_DAY_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DAYS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DATE, newday.getDate()); // GetDate
values.put(KEY_BRUTTO, newday.getBrutto()); // GetBruttoLønn
values.put(KEY_HOURS, newday.getHours()); // GetHours
values.put(KEY_UB, newday.getUb()); // GetUBTillegg
// Inserting Row
db.insert(TABLE_DAYS, null, values);
db.close(); // Closing database connection
}
// Get single day
AddNewDay getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DAYS, new String[] { KEY_ID,
KEY_DATE, KEY_HOURS, KEY_BRUTTO, KEY_UB }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
AddNewDay newday = new AddNewDay(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)),
Integer.parseInt(cursor.getString(3)),Integer.parseInt(cursor.getString(4)));
// return contact
return newday;
}
// Getting All Contacts
public List<AddNewDay> getAllContacts() {
List<AddNewDay> contactList = new ArrayList<AddNewDay>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DAYS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AddNewDay days = new AddNewDay();
days.setID(Integer.parseInt(cursor.getString(0)));
days.setDate(cursor.getString(1));
days.setHours(Integer.parseInt(cursor.getString(2)));
days.setUb(Integer.parseInt(cursor.getString(3)));
days.setBrutto(Integer.parseInt(cursor.getString(4)));
// Adding contact to list
contactList.add(days);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, newday.getID());
values.put(KEY_DATE, newday.getDate());
values.put(KEY_HOURS, newday.getHours());
values.put(KEY_UB, newday.getUb());
values.put(KEY_BRUTTO, newday.getUb());
// updating row
return db.update(TABLE_DAYS, values, KEY_ID + " = ?",
new String[] { String.valueOf(newday.getID()) });
}
// Deleting single contact
public void deleteDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DAYS, KEY_ID + " = ?",
new String[] { String.valueOf(newday.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_DAYS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And then my AddNewDay file.
public class AddNewDay {
//private variables
int _id;
String _date;
int _hours;
int _ubtillegg;
int _brutto;
// Empty constructor
public AddNewDay(){
}
// constructor
public AddNewDay(int id, String date, int hours, int ubtillegg, int brutto){
this._id = id;
this._date = date;
this._hours = hours;
this._ubtillegg = ubtillegg;
this._brutto = brutto;
}
// constructor
public AddNewDay(String date, int hours, int brutto){
this._date = date;
this._hours = hours;
this._brutto = brutto;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting date
public String getDate(){
return this._date;
}
// setting date
public void setDate(String date){
this._date = date;
}
// getting hours
public int getHours(){
return this._hours;
}
// setting hours
public void setHours(int hours){
this._hours = hours;
}
// getting ubtillegg
public int getUb(){
return this._ubtillegg;
}
// setting ubtillegg
public void setUb(int ub){
this._ubtillegg = ub;
}
// getting brutto
public int getBrutto(){
return this._brutto;
}
// setting brutto
public void setBrutto(int brutto){
this._brutto = brutto;
}
public String toString() {
return _date + " jobbet du " + _hours + " timer.";
}
}
And this is how I add a new entry in the database.
// # Makes a new object of newday.
AddNewDay newday = new AddNewDay ();
newday._date = "21.03.2013";
newday._id = 1;
newday._hours = 4;
newday._ubtillegg = 1500;
// # Open databse connection and writes new day.
DatabaseHandler connect = new DatabaseHandler (this);
connect.addDay(newday);
// # Updates the dblist with entries.
GlobalVariables.dblist = connect.getAllContacts();
So basicly I found the solution. I'm still confused about how stupid it was. And clearly database work i super-sensitive material! My problem was I forgot a white-space in the last "INTEGER" value. So instead of " INTEGER" i wrote "INTEGER", and that gave me a row called "bruttoINTEGER" instead of "brutto". So a white-space was the error. I rewrote the createTable function to this :
public void onCreate(SQLiteDatabase db) {
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HOURS + " INTEGER, "
+ KEY_UB + " INTEGER," + KEY_BRUTTO + " INTEGER" + ");";
db.execSQL(CREATE_DAY_TABLE);
}
private static final int VERSION = 4;
Change the version it worked fine for me
i agree with iNzzane above. this problem is mainly caused by syntax. for example, previously my code was correct. here it is:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT " + ")";
the above code was running correct but i added another column and it started causing the mentioned error. below is the erroneous code:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT" + COLUMN_MESSAGETIME + " LONG" + ")";
as you can see, when i added the new column i forgot to include a comma after type TEXT. this means that when this code is executed, there will be syntax error as the compiler will read the last part as:
COLUMN_MESSAGEBODY TEXTCOLUMN_MESSAGETIME LONG
as opposed to:
COLUMN_MESSAGEBODY TEXT, COLUMN_MESSAGETIME LONG
solution: ensure that your syntax is correct and you heed to spaces and commas.
I´m not sure but maybe you forgot the " , " in the query before "ub" and "brutto" fields
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT,"
+ KEY_HOURS + " INTEGER PRIMARY KEY, " + KEY_UB + " INTEGER PRIMARY KEY, " + KEY_BRUTTO + "INTEGER PRIMARY KEY" + ")";
db.execSQL(CREATE_DAY_TABLE);