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);
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
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
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 the error Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. Two other people are able to run the code without error but on my machine it throws it. I'm very confused. Here is the code that deals with the SQLite:
Thanks in advance, sorry there's a lot of code
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class FeedSQLiteHelper extends SQLiteOpenHelper {
//Table Name
public static final String TABLE_POSTS = "comments";
//Table Column names
public static final String COLUMN_ID = "_id";
public static final String COLUMN_CAPTION = "caption";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_LIKE="like";
public static final String COLUMN_DISLIKE="dislike";
public static final String COLUMN_COMMENTS = "columns";
public static final String COLUMN_ALL_COMMENTS = "allComments";
public static final String COLUMN_PHOTO = "photo";
public static final String COLUMN_CELEB = "celeb";
public static final String COLUMN_FID = "facebook_id";
public static final String COLUMN_TIME = "timestamp";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 6;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_POSTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_CAPTION
+ " text not null, " + COLUMN_NAME + " text not null, "
+ COLUMN_LIKE + " integer not null, " + COLUMN_DISLIKE + " integer not null, "
+ COLUMN_COMMENTS + " integer not null, " + COLUMN_ALL_COMMENTS + " text, "
+ COLUMN_PHOTO + " text, " + COLUMN_FID + " text, " + COLUMN_TIME + " long);";
public FeedSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(FeedSQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
if(oldVersion <6) {
final String ALTER_TBL = "ALTER TABLE " + TABLE_POSTS + " ADD COLUMN " + COLUMN_TIME + " long;";
db.execSQL(ALTER_TBL);
}
}
//Adding new contact
public void addContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_CAPTION, contact.getDesc());
values.put(COLUMN_LIKE, contact.getUps());
values.put(COLUMN_DISLIKE, contact.getDowns());
values.put(COLUMN_COMMENTS, contact.getComments());
values.put(COLUMN_ALL_COMMENTS, contact.getAllComments());
values.put(COLUMN_PHOTO, contact.getImageId());
values.put(COLUMN_FID, contact.getFID());
values.put(COLUMN_TIME, contact.getTimestamp());
// Inserting Row
db.insert(TABLE_POSTS, null, values);
db.close(); // Closing database connection
}
//Getting single contact
public FeedsModel getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_POSTS, new String[] { COLUMN_ID,
COLUMN_CAPTION, COLUMN_NAME, COLUMN_LIKE, COLUMN_DISLIKE, COLUMN_COMMENTS, COLUMN_ALL_COMMENTS, COLUMN_PHOTO, COLUMN_FID, COLUMN_TIME }, COLUMN_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
FeedsModel contact = new FeedsModel(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
Integer.parseInt(cursor.getString(3)),
Integer.parseInt(cursor.getString(4)),
Integer.parseInt(cursor.getString(5)),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
Long.parseLong(cursor.getString(9)));
// return contact
return contact;
}
//filters the news feed for the 'Me' option
public List<FeedsModel> getMe(String me)
{
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
String selectQuery = "SELECT * FROM " + TABLE_POSTS + " WHERE " + COLUMN_FID + "= "+ me;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//filters the news feed for the 'Me' option
public List<FeedsModel> getMostRecent()
{
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
String selectQuery = "SELECT * FROM " + TABLE_POSTS + " ORDER BY " + COLUMN_TIME + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//Getting All Contacts
public List<FeedsModel> getAllContacts() {
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_POSTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_POSTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
//Updating single contact
public int updateContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_CAPTION, contact.getDesc());
values.put(COLUMN_LIKE, contact.getUps());
values.put(COLUMN_DISLIKE, contact.getDowns());
values.put(COLUMN_COMMENTS, contact.getComments());
values.put(COLUMN_ALL_COMMENTS, contact.getAllComments());
values.put(COLUMN_PHOTO, contact.getImageId());
values.put(COLUMN_FID, contact.getFID());
values.put(COLUMN_TIME, contact.getTimestamp());
// updating row
return db.update(TABLE_POSTS, values, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
}
//Deleting single contact
public void deleteContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_POSTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
Logcat:
E/CursorWindow(841): Failed to read row 0, column 9 from a CursorWindow which has 3 rows, 9 columns.
D/AndroidRuntime(841): Shutting down VM
W/dalvikvm(841): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(841): FATAL EXCEPTION: main
E/AndroidRuntime(841): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.Drake.doppelganger/edu.Drake.doppelganger.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
E/AndroidRuntime(841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
E/AndroidRuntime(841): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(841): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(841): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(841): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(841): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(841): at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime(841): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(841): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(841): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(841): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(841): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(841): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
E/AndroidRuntime(841): at android.database.CursorWindow.nativeGetString(Native Method)
E/AndroidRuntime(841): at android.database.CursorWindow.getString(CursorWindow.java:434)
E/AndroidRuntime(841): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
E/AndroidRuntime(841): at edu.Drake.doppelganger.FeedSQLiteHelper.getAllContacts(FeedSQLiteHelper.java:198)
E/AndroidRuntime(841): at edu.Drake.doppelganger.FeedFragment.onActivityCreated(FeedFragment.java:65)
E/AndroidRuntime(841): at android.app.Fragment.performActivityCreated(Fragment.java:1703)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
E/AndroidRuntime(841): at android.app.BackStackRecord.run(BackStackRecord.java:682)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
E/AndroidRuntime(841): at android.app.Activity.performStart(Activity.java:5113)
E/AndroidRuntime(841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
E/AndroidRuntime(841): ... 11 more
it is because you try to get the data before checking their is data available or not.
if (cursor.moveToFirst()) {
do {
// your content
} while (cursor.moveToNext());
}
Change this block to
while (cursor.moveToNext()) {
// your content
}
Like this.
Surely this will help you.