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.
Related
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
I have looked through SO and found many people having this same error, but they seem to be forgetting to add the column into the create statement or missing whitespace, neither of which I believe I did.
My logcat is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmd.referenceapplication, PID: 31988
android.database.sqlite.SQLiteException: no such column: QUANTITY (code 1): , while compiling: SELECT * FROM FTS WHERE (QUANTITY MATCH ?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.gmd.referenceapplication.DatabaseTable.query(DatabaseTable.java:187)
at com.gmd.referenceapplication.DatabaseTable.getWordMatches(DatabaseTable.java:179)
at com.gmd.referenceapplication.SearchableActivity$1.onQueryTextChange(SearchableActivity.java:70)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7991)
at android.widget.TextView.handleTextChanged(TextView.java:8053)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10157)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1033)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:559)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:491)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
DatabaseTable class:
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTITY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
public static final String _id = "_id";
//name, tbale name, version
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
private final Context mcontext;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
mcontext = context;
}
private class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private final MyDataProvider dp = new MyDataProvider(mcontext);
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +_id+ " INTEGER PRIMARY KEY,"+
COL_QUANTITY + " TEXT, " +
COL_VALUE + " TEXT," +
COL_UNCERTAINTY + " TEXT," +
COL_UNIT + " TEXT " + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
loadConstants();
Log.e("Database Operation", "DatabaseOpenHelper constructor called, constants loaded?");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
public SQLiteDatabase getmDatabase(){
return mDatabase;
}
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
HashMap map = dp.getAllMap();
Iterator<Map.Entry<String, ListViewItem>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, ListViewItem> entry = entries.next();
Log.d("thing:", entry.getKey());
//addConstant(entry.getKey(), entry.getValue(), entry.getUncertainty(), entry.getUnit());
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
return db.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
//database openhelper ends
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
public Cursor getAllTitles(){
return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
COL_QUANTITY,
COL_UNCERTAINTY,
COL_UNIT,
COL_VALUE},
null,
null,
null,
null,
null);
}
Thank you to anyone who can tell me why it is telling me the column "QUANTITY" is not being created, I really don't know.
If you change the schema you should increment DATABASE_VERSION so the database is upgraded.
I am having difficulty inserting image in my sqlite database. There are no syntax errors in my code. After I run it, the app automatically force stops. The logcat shows:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at com.synergy88studios.catalogapp.DatabaseHandler.getAllItemsInList(DatabaseHandler.java:86)
at com.synergy88studios.catalogapp.MainActivity.onCreate(MainActivity.java:56)
Here is my method in getAllItemsInList in my DatabaseHandler.class
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
In my MainActivity, I simply call the method.
items = db.getAllItemsInList();
EDIT
DatabaseHandler.class
public class DatabaseHandler extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CatalogItems";
public static final String TABLE_ITEMS = "Items";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESC = "description";
public static final String KEY_IMAGE = "image";
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_DESC};
//private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "( "
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT, " + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_ITEMS);
onCreate(db);
}
public void addItems(Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
db.insert(TABLE_ITEMS, null ,values);
db.close();
}
Item getItem(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC , KEY_IMAGE}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getBlob(3));
return item;
}
void deleteAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+ TABLE_ITEMS);
}
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
String where = null;
Cursor c = db.query(true, TABLE_ITEMS, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public int getItemsCount(){
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
}
public void deleteContact(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
db.close();
}
}
I hope someone can explain to me what happens. I can post my other classes for reference.
Don't store large data in an Android sqlite table. In particular, the CursorWindow only supports row data up to 2MB. If your row is larger, you can't access it.
Instead, store your blobs as files in the filesystem and store just the path in database.
I am trying to figure out how to populate my listview with data from a sqlite databse. I actually followed the tutorial posted here
My code is posted below:
DatabaseHandler.java
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;
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 = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_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(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// 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 {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Mainactivity.java
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Listview list =(Listview) findviewbyid(R.id.list);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "" + cn.getName() +"";
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
What am I doing wrong?
this is my database, can you please help me with it? i think there is nothing wrong i tried reinstalling the app to update the database initially but still doesnt work. it says that there is no such column _url.
This is my class that creates the database:
MySQLiteHelper.java
public class MySQLiteHelper extends SQLiteOpenHelper {
/**
* table for locations
* | _id | _latitude | _longitude | _time | _provider
*/
public static final String TABLE_LOCATION = "location";
public static final String COLUMN_LOCID = "_id";
public static final String COLUMN_LATITUDE = "_latitude";
public static final String COLUMN_LONGITUDE = "_longitude";
public static final String COLUMN_TIME = "_time";
public static final String COLUMN_ACCURACY = "_accuracy";
public static final String COLUMN_PROVIDER = "_provider";
/**
* table for pictures
* | _id | _url | _latitude | _longitude | _time
*/
public static final String TABLE_PICTURE = "picture";
public static final String COLUMN_PIC_ID = "_id";
public static final String COLUMN_PIC_URL = "_url";
public static final String COLUMN_PIC_LATITUDE = "_latitude";
public static final String COLUMN_PIC_LONGITUDE = "_longitude";
public static final String COLUMN_PIC_TIME = "_time";
public static final String COLUMN_PIC_ACCURACY = "_accuracy";
/**
* table for Accelerometer
* | _id | _x | _y | _z | _time
*/
public static final String TABLE_ACCELEROMETER = "accelerometer";
public static final String COLUMN_ACCELEROMETER_ID = "_id";
public static final String COLUMN_ACCELEROMETER_X = "_x";
public static final String COLUMN_ACCELEROMETER_Y = "_y";
public static final String COLUMN_ACCELEROMETER_Z = "_z";
public static final String COLUMN_ACCELEROMETER_TIME = "_time";
/**
* table for Sound
* | _id | _amplitude | _time
*/
public static final String TABLE_AMPLITUDE = "sound";
public static final String COLUMN_AMPLITUDE_ID = "_id";
public static final String COLUMN_AMPLITUDE_AMPLITUDE = "_amplitude";
public static final String COLUMN_AMPLITUDE_TIME = "_time";
private static final String DATABASE_NAME = "memory.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement for location
private static final String DATABASE_CREATE_LOC = "create table "
+ TABLE_LOCATION + "(" + COLUMN_LOCID
+ " integer primary key autoincrement, " + COLUMN_LATITUDE
+ " double not null, "+ COLUMN_LONGITUDE + " double not null, "
+ COLUMN_TIME + " text not null, " + COLUMN_ACCURACY + " text not null, " +
COLUMN_PROVIDER + " text not null " +");";
// Database creation sql statement for picture
private static final String DATABASE_CREATE_PIC = "create table "
+ TABLE_PICTURE + "(" + COLUMN_PIC_ID
+ " integer primary key autoincrement, " + COLUMN_PIC_URL
+ " text not null, " + COLUMN_LATITUDE
+ " double, "+ COLUMN_LONGITUDE + " double, "
+ COLUMN_TIME + " text, " + COLUMN_PIC_ACCURACY + " text " + ");";
// Database creation sql statement for accelerometer
private static final String DATABASE_CREATE_ACCELEROMETER = "create table "
+ TABLE_ACCELEROMETER + "(" + COLUMN_ACCELEROMETER_ID
+ " integer primary key autoincrement, " + COLUMN_ACCELEROMETER_X
+ " float not null, " + COLUMN_ACCELEROMETER_Y
+ " float not null, "+ COLUMN_ACCELEROMETER_Z + " float not null, "
+ COLUMN_ACCELEROMETER_TIME + " text " +");";
// Database creation sql statement for sound
private static final String DATABASE_CREATE_AMPLITUDE = "create table "
+ TABLE_AMPLITUDE + "(" + COLUMN_AMPLITUDE_ID
+ " integer primary key autoincrement, " + COLUMN_AMPLITUDE_AMPLITUDE
+ " double not null, "
+ COLUMN_AMPLITUDE_TIME + " text " +");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_LOC);
database.execSQL(DATABASE_CREATE_PIC);
database.execSQL(DATABASE_CREATE_ACCELEROMETER);
database.execSQL(DATABASE_CREATE_AMPLITUDE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCELEROMETER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_AMPLITUDE);
onCreate(db);
}
}
I dont find anything wrong in my tables. i checked for spaces.
The error i get is:
03-24 17:51:39.851: E/SQLiteLog(18574): (1) no such column: _url
03-24 17:51:39.855: W/dalvikvm(18574): threadid=11: thread exiting with uncaught exception (group=0x40eb0300)
03-24 17:51:39.863: E/AndroidRuntime(18574): FATAL EXCEPTION: Thread-799
03-24 17:51:39.863: E/AndroidRuntime(18574): android.database.sqlite.SQLiteException: no such column: _url (code 1): , while compiling: SELECT _id, _url, _latitude, _longitude, _time, _accuracy FROM picture
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
03-24 17:51:39.863: E/AndroidRuntime(18574): at data.DatabaseInteraction.getAllPictures(DatabaseInteraction.java:191)
03-24 17:51:39.863: E/AndroidRuntime(18574): at main.inSituApp.InSituApp$3.run(InSituApp.java:327)
I have a class that uses the database class to insert and query data to and from the database.
DatabaseInteraction.java
public class DatabaseInteraction {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] locColumns = { MySQLiteHelper.COLUMN_LOCID,
MySQLiteHelper.COLUMN_LATITUDE, MySQLiteHelper.COLUMN_LONGITUDE,
MySQLiteHelper.COLUMN_TIME, MySQLiteHelper.COLUMN_ACCURACY,
MySQLiteHelper.COLUMN_PROVIDER};
private String[] picColumns = { MySQLiteHelper.COLUMN_PIC_ID,
MySQLiteHelper.COLUMN_PIC_URL, MySQLiteHelper.COLUMN_PIC_LATITUDE,
MySQLiteHelper.COLUMN_PIC_LONGITUDE,
MySQLiteHelper.COLUMN_PIC_TIME, MySQLiteHelper.COLUMN_PIC_ACCURACY };
private String[] accColumns = { MySQLiteHelper.COLUMN_ACCELEROMETER_ID,
MySQLiteHelper.COLUMN_ACCELEROMETER_X, MySQLiteHelper.COLUMN_ACCELEROMETER_Y,
MySQLiteHelper.COLUMN_ACCELEROMETER_Z,
MySQLiteHelper.COLUMN_ACCELEROMETER_TIME };
private String[] amplitudeColumns = { MySQLiteHelper.COLUMN_AMPLITUDE_ID,
MySQLiteHelper.COLUMN_AMPLITUDE_AMPLITUDE,
MySQLiteHelper.COLUMN_AMPLITUDE_TIME };
public DatabaseInteraction(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public /*Loc*/ long createLocation(double latitude, double longitude, long time,
double accuracy, String provider) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
values.put(MySQLiteHelper.COLUMN_TIME, time);
values.put(MySQLiteHelper.COLUMN_ACCURACY, accuracy);
values.put(MySQLiteHelper.COLUMN_PROVIDER, provider);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_LOCATION, null,
values);
close();
return insertId;
/*Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
locColumns,
MySQLiteHelper.COLUMN_LOCID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
Loc newLoc = cursorToLocation(cursor);
cursor.close();
return newLoc;*/
}
public long createPic(String url, double latitude, double longitude,
long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_PIC_URL, url);
values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
values.put(MySQLiteHelper.COLUMN_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_PICTURE, null,
values);
close();
return insertId;
/*Cursor cursor = database.query(MySQLiteHelper.TABLE_PICTURE,
picColumns, MySQLiteHelper.COLUMN_PIC_ID + " = " + insertId,
null, null, null, null);
cursor.moveToFirst();
Pic newPic = cursorToPicture(cursor);
cursor.close();
return newPic;*/
}
public long createAccelerometer(float x, float y, float z,
long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_X, x);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_Y, y);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_Z, z);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_ACCELEROMETER, null,
values);
close();
return insertId;
}
public long createSound(double amplitude, long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_AMPLITUDE_AMPLITUDE, amplitude);
values.put(MySQLiteHelper.COLUMN_AMPLITUDE_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_AMPLITUDE, null,
values);
close();
return insertId;
}
public int deleteLocation(long id) {
System.out.println("Location deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_LOCATION,
MySQLiteHelper.COLUMN_LOCID + " = " + id, null);
close();
return value;
}
public int deletePic(long id){
System.out.println("Picture deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_PICTURE,
MySQLiteHelper.COLUMN_PIC_ID + " = " + id, null);
close();
return value;
}
public int deleteAccelerometer(long id){
System.out.println("Accelerometer deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_ACCELEROMETER,
MySQLiteHelper.COLUMN_ACCELEROMETER_ID + " = " + id, null);
return value;
}
public int deleteSound(long id){
System.out.println("Sound deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_AMPLITUDE,
MySQLiteHelper.COLUMN_AMPLITUDE_ID + " = " + id, null);
close();
return value;
}
public List<Loc> getAllLocations() {
List<Loc> allLocations = new ArrayList<Loc>();
open();
Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
locColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Loc oneLoc = cursorToLocation(cursor);
allLocations.add(oneLoc);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
close();
return allLocations;
}
public List<Pic> getAllPictures() {
List<Pic> allPictures = new ArrayList<Pic>();
open();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PICTURE,
picColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Pic onePic = cursorToPicture(cursor);
allPictures.add(onePic);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
close();
return allPictures;
}
public List<Accelerometer> getAllAccelerometerValues() {
List<Accelerometer> allAccelerometerValues = new ArrayList<Accelerometer>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ACCELEROMETER,
accColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Accelerometer oneAcc = cursorToAccelerometer(cursor);
allAccelerometerValues.add(oneAcc);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return allAccelerometerValues;
}
public List<Amplitude> getAllSoundAmpitudes() {
List<Amplitude> allSoundAmplitudes = new ArrayList<Amplitude>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_AMPLITUDE,
amplitudeColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Amplitude oneSound = cursorToAmplitude(cursor);
allSoundAmplitudes.add(oneSound);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return allSoundAmplitudes;
}
private Loc cursorToLocation(Cursor cursor) {
Loc location = new Loc();
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
location.setTime(cursor.getLong(3));
location.setAccuracy(cursor.getDouble(4));
return location;
}
private Pic cursorToPicture(Cursor cursor) {
Pic picture = new Pic();
picture.setLatitude(cursor.getDouble(1));
picture.setLongitude(cursor.getDouble(2));
picture.setTime(cursor.getLong(3));
return picture;
}
private Accelerometer cursorToAccelerometer(Cursor cursor) {
Accelerometer acc = new Accelerometer();
acc.setX(cursor.getFloat(1));
acc.setY(cursor.getFloat(2));
acc.setZ(cursor.getFloat(3));
acc.setTime(cursor.getLong(4));
return acc;
}
private Amplitude cursorToAmplitude(Cursor cursor) {
Amplitude sound = new Amplitude();
sound.setAmplitude(cursor.getDouble(1));
sound.setTime(cursor.getLong(2));
return sound;
}
}
Please any hint is appreciated. ty very much in advance.
Probably you have a different "picture" table structure, try deleting the current application,
then the onCreate(SQLiteDatabase database) method will create the correct structure.
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);