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
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 + ";";
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 ); ";
So I am making an itinerary type application where the user makes an itinerary and has multiple entries in one itinerary. So i need to be able to retrieve all the data from one itinerary. For example if the Itinerary is called Monday, and the user selected that one to view, i would want all the data from that. I've done this by having the ItineraryName, e.g. Monday, be passed through to another activity, which works but i've only seen through print statements to check the value has passed through correctly.
Currently i can view the data for a specific Itinerary, e.g. Monday, only if i manually input into the selection args variable(see below) but if i try pass it by a variable it wont work and i get an error, also i have tried putting "%" + ItineraryName + "%" into the selection args but i am presented with a blank activity. Error for just variable:
Process: com.example.chiraag.qavel, PID: 10198
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chiraag.qavel/com.example.chiraag.qavel.ItineraryDetails}: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
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.example.chiraag.qavel.DBManager.Query(DBManager.java:101)
at com.example.chiraag.qavel.ItineraryDetails.loadItinerary(ItineraryDetails.java:47)
at com.example.chiraag.qavel.ItineraryDetails.onCreate(ItineraryDetails.java:34)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
Code for ItineraryDetails:
public class ItineraryDetails extends AppCompatActivity {
DBManager db;
myAdapter myAdapter;
ListView ls;
private String ItineraryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_itinerary_details);
db = new DBManager(this);
ls = (ListView)findViewById(R.id.ItineraryDetails_listview);
loadItinerary();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Name");
System.out.println("Name " + ItineraryName);
}
public void loadItinerary(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
String []selectionargs = {ItineraryName};
Cursor cursor = db.Query("Itinerary",null, "ItineraryName like ?", selectionargs , DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
null
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,null,null, null, null
,null
,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_items_itinerary_details, null);
ac = listItem.get(position);
TextView ItineraryName = (TextView) myView.findViewById(R.id.tvItineraryDetailsEntryName);
ItineraryName.setText(ac.Name);
TextView ItineraryLocation = (TextView) myView.findViewById(R.id.tvItineraryDetailsEntryLocation);
ItineraryLocation.setText(ac.Location);
TextView ItineraryTime = (TextView)myView.findViewById(R.id.tvItineraryDetailsEntryTime);
ItineraryTime.setText(ac.Time);
return myView;
}
}
}
Code for DBManager:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
The error points to my query method in my DBManager class, I may have structured it wrong, i'm not sure because i first created it to retrieve all data from a table. Any help with this would be great thank you.
Looks like you're trying to bind the variable ItineraryName before it's been defined. You call loadItinerary before you define ItineraryName but try to use it in the query were you create your cursor. I think this is causing the error you're seeing
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" + ");");