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 + ";";
Related
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 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.
Can anyone see what is wrong with this code please, this is the error given:
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE scores(_id INTEGER PRIMARY KEY AUTOINCREMENT , scoreName TEXT , );
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "scores.db";
public static final String TABLE_SCORES = "scores";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCORENAME = "scoreName";
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 query = "CREATE TABLE " + TABLE_SCORES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_SCORENAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score) {
ContentValues values = new ContentValues();
values.put(COLUMN_SCORENAME, score.get_scoreName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public void deleteScore(String scoreName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SCORES + "WHERE " + COLUMN_SCORENAME + "=\"" + scoreName + "\";");
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SCORES + "WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//move to first row in your results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("scoreName")) != null) {
dbString += c.getString(c.getColumnIndex("scoreName"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Seems problem in Query for creating table (comma is missing after AUTOINCREMENT). Try this
db.execSQL("CREATE TABLE " + TABLE_SCORES + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_SCORENAME + " TEXT" + ");");
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