Android SQLite Couldn't Found Declared Column - java

Okay, here's the situation: I've created a class extending Android's SQLOpenHelper class. I've also implemented the required methods, onCreate and onUpgrade, to initialize tables and to drop the current tables and then re-create new ones respectively.
The tables were successfully created but when I tried to call a method to insert a new record to the database LogCat gave me this instead:
06-17 21:31:19.907: I/SqliteDatabaseCpp(561): sqlite returned: error code = 1, msg = table calendarEvents has no column named colour, db=/data/data/stub.binusitdirectorate.calendar/databases/calendarSQLite
I've done some search regarding this problem. Most of the answers suggested to re-install the app and repeat the process. Done, but still no success.
Here's my SQLiteOpenHelper onCreate method:
public void onCreate(SQLiteDatabase db) {
String CREATE_EVENTS_TABLE = "CREATE TABLE " + EVENTS_TABLE + "("
+ KEY_EVENTS_TYPE_ID + " TEXT PRIMARY KEY,"
+ KEY_EVENTS_TYPE_NAME + " TEXT," + KEY_EVENTS_NAME + " TEXT,"
+ KEY_EVENTS_COLOR + "TEXT," + KEY_EVENTS_START_DATE + "DATE,"
+ KEY_EVENTS_END_DATE + "TEXT" + ")"
db.execSQL(CREATE_EVENTS_TABLE);
}
And here's my method for inserting new records:
public void addEventsList(ArrayList<CalendarEventData> lstCalendarEvents) {
SQLiteDatabase db = this.getWritableDatabase();
if (lstCalendarEvents != null && db != null) {
for (int i = 0; i < lstCalendarEvents.size(); i++) {
ContentValues values = new ContentValues();
values.put(KEY_EVENTS_TYPE_ID, lstCalendarEvents.get(i)
.getEventTypeId());
values.put(KEY_EVENTS_TYPE_NAME, lstCalendarEvents.get(i)
.getEventTypeName());
values.put(KEY_EVENTS_NAME, lstCalendarEvents.get(i)
.getEventName());
values.put(KEY_EVENTS_COLOR, lstCalendarEvents.get(i)
.getColour());
values.put(KEY_EVENTS_START_DATE, DateUtils
.getFormattedDateString(lstCalendarEvents.get(i)
.getStartDateTime(), dateFormat));
values.put(KEY_EVENTS_END_DATE, DateUtils
.getFormattedDateString(lstCalendarEvents.get(i)
.getEndDateTime(), dateFormat));
db.insert(EVENTS_TABLE, null, values);
}
db.close();
}
}
I'm fairly new to Android and was using this tutorial as a guide.
Thanks in advance! :)

This part of your create statement might cause problems
KEY_EVENTS_COLOR + "TEXT," + KEY_EVENTS_START_DATE + "DATE,"
+ KEY_EVENTS_END_DATE + "TEXT" + ")"
You are missing a space before TEXT everywhere :)

Related

Database does not store data. I get the "SQLiteLog: (1) near "Name": syntax error" from Android Studio log

I get from "SQLiteLog: (1) near "Name": syntax error" after the addPatient() method is called and the data given by addPatient() method is not stored in the database.
At first, I suspect that something might be wrong with my "CREATE TABLE" query but I have tried everything and I couldn't figure out what was wrong.
#Override
public void onCreate(SQLiteDatabase db)
{
//===============Create a table for Patient
String query = "CREATE TABLE TABLE_PATIENT (COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"COLUMN_USERNAME TEXT, " +
"COLUMN_PASSWORD TEXT, " +
"COLUMN_FIRSTNAME TEXT, " +
"COLUMN_LASTNAME TEXT, " +
"COLUMN_AGE TEXT, " +
"COLUMN_GENDER TEXT, " +
"COLUMN_PHONE TEXT, " +
"COLUMN_ADDRESS TEXT);";
db.execSQL(query);
}//End of onCreate()
//Add a new Patient Row to the database
public void addPatient(Patient patient)
{
Log.i(TAG, "addPatient("+patient.getUserName()+")");
ContentValues values = new ContentValues();
values.put(COLUMN_ID, patient.getU_Id());
values.put(COLUMN_USERNAME, patient.getUserName());
values.put(COLUMN_PASSWORD, patient.getPassword());
values.put(COLUMN_FIRSTNAME, patient.getFirstName());
values.put(COLUMN_LASTNAME,patient.getLastName());
values.put(COLUMN_AGE, patient.getAge());
values.put(COLUMN_GENDER,patient.getGender());
values.put(COLUMN_PHONE,patient.getPhoneNumber());
values.put(COLUMN_ADDRESS, patient.getAddress());
SQLiteDatabase db = getWritableDatabase();
try
{
db.insert(TABLE_PATIENT, null, values);
db.close();
}catch (Exception e)
{
Log.i(TAG, e.getMessage());
}
}//End of addPatient()
I guess you have defined these variables:
String COLUMN_ID = "id";
String COLUMN_USERNAME = "username";
....................................
or something like that.
If you have spaces in the names of the columns you must use square brackets or backticks around them, like:
String COLUMN_USERNAME = "[user name]";
In your CREATE TABLE statement you define the column names as:
"COLUMN_ID", "COLUMN_USERNAME", ....
because you use the variable names and not their values.
But in addPatient() method you are putting values to the ContentValues object by using their actual names.
To solve your problem, 1st uninstall the app from the device you are testing it, so the database is deleted.
Then change the CREATE TABLE statement like this:
String query = "CREATE TABLE " + TABLE_PATIENT +" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_AGE + " TEXT, " +
COLUMN_GENDER + " TEXT, " +
COLUMN_PHONE + " TEXT, " +
COLUMN_ADDRESS + " TEXT)";
and rerun to recreate the database with the correct column names.

Android SQLITE DB update table not working

contactid = 123;
SYNC_SUCCESS = 1;
db.updateSyncStatus(contactid, SYNC_SUCCESS);
I have tried the 3 possible ways to update the table in SQLite DB. But its not working. INSERT and DELETE process are working good. Only I am facing problem in the UPDATE. Did I missed anything?
public void updateSyncStatus(String contactid, int syncSuccess) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put(CONTACTS_SYNC_STATUS, syncSuccess);
try {
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + "='" + contactid + "'", null); // Tried, Not working
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID +" = ?", new String[] {contactid}); // Tried, Not Working
db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + " = ?", new String[]{contactid});
}
catch (Exception e){
String error = e.getMessage().toString();
Log.e(TAG, "UpdateError: " + error);
}
db.close();
}
Table Structure:
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
+ CONTACTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ CONTACTS_NUMBER + " VARCHAR,"
+ CONTACTS_CONTACTID + " VARCHAR,"
+ CONTACTS_SYNC_STATUS + " TINYINT DEFAULT 0" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
Actually the problem is not with the update query. The problem is , before executing the updateSyncStatus method, next statement ran and I am getting the output before updating the rows. So I have used the Handler to wait for 10 seconds before showing the output.

Cursor returns with no result after SQLite query (passes unit test but fails at run time) -- android

i have this method:
public Note getNoteById(long id) {
Cursor cursor = database.query(Config.NOTES_TABLE, Config.NOTES_COLUMNS, Config.ROW_ID+"="+id, null, null, null, Config.ROW_ID + " DESC");
//no match found
if(cursor.getCount() == 0)
return null;
cursor.moveToFirst();
Note result = new Note();
result.setId(cursor.getLong(cursor.getColumnIndex(Config.ROW_ID)));
result.setTitle(cursor.getString(cursor.getColumnIndex(Config.TITLE)));
result.setText(cursor.getString(cursor.getColumnIndex(Config.TEXT)));
result.setViewOrder(cursor.getLong(cursor.getColumnIndex(Config.VIEW_ORDER)));
result.setCreated(cursor.getString(cursor.getColumnIndex(Config.CREATED)));
result.createTagsFromString(cursor.getString(cursor.getColumnIndex(Config.TAGS)));
return result;
}
My problem is in the first few lines. The cursor at the beginning always returns with a count of 0 therefore making the function always returns null -- ONLY AT RUNTIME! -- i have written a test case for this method and it passes so i cant figure out why it would only fail at runtime?
heres the relevant part of the test case. i basically insert new data to the table and try to get it back by its id and compare attributes to confirm its the same:
#Test
public void testGetNoteByIdMatch(){
testTable.load();
Assert.assertEquals(0, testTable.getAllNotes().getCount());
testTable.newEntry(note1);
testTable.newEntry(note2);
Cursor cursor = testTable.getAllNotes();
Assert.assertEquals(2, testTable.getAllNotes().getCount());
cursor.moveToFirst();
Note result = new Note();
result.setId(cursor.getLong(cursor.getColumnIndex(Config.ROW_ID)));
result.setTitle(cursor.getString(cursor.getColumnIndex(Config.TITLE)));
result.setText(cursor.getString(cursor.getColumnIndex(Config.TEXT)));
Note checker = testTable.getNoteById(result.getId());
Assert.assertEquals(result.getId(), checker.getId());
Assert.assertEquals(result.getTitle(), checker.getTitle());
//move and try another search
cursor.moveToNext();
result = new Note();
result.setId(cursor.getLong(cursor.getColumnIndex(Config.ROW_ID)));
result.setTitle(cursor.getString(cursor.getColumnIndex(Config.TITLE)));
result.setText(cursor.getString(cursor.getColumnIndex(Config.TEXT)));
checker = testTable.getNoteById(result.getId());
Assert.assertEquals(result.getId(), checker.getId());
Assert.assertEquals(result.getTitle(), checker.getTitle());
}
this is the table structure in the onCreate method for the database:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Config.NOTES_TABLE + " (" +
Config.ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
Config.TITLE + " TEXT NOT NULL, " +
Config.TEXT + " TEXT NOT NULL, " +
Config.CREATED + " TEXT NOT NULL, " +
Config.VIEW_ORDER + " INTEGER NOT NULL, " +
Config.TAGS + " TEXT NOT NULL)"
);
}
Your test checks that the values can be read out in the same order they were inserted, but does not actually verify the data is going in as expected. It's possible that the result and checker objects both have null values for all properties. Verify that the object properties have the expected values once read out of the db.

Sqlite insert and update values of other columns

I have two tables; a 'parent' and a 'child' table. (not SQLite defitinions, just something i call them)
Everytime a child-object is created, it is assigned the value 0 in one of its columns.
When a new parent-object is created, every unassigned child-object, has to update the value mentioned before, to the parent-object's ID. My code looks like this:
public long createWorkout(String workoutName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, workoutName);
//Creates a new parent-object (a workout - the childs are exercises)
//the generated ID is returned as a long (workout_pk_id)
long workout_pk_id = db.insert(TABLE_WORKOUT, null, values);
//Selects all objects in the child-table with KEY_WORKOUT_ID = 0 (the column mentioned before)
String selectQuery = "SELECT * FROM " + TABLE_EXERCISE + " WHERE " + KEY_WORKOUT_ID + " == " + 0;
Cursor cursor = db.rawQuery(selectQuery, null);
//Takes each found object with value 0, and updates the value to the returned parent-ID from before.
if (cursor.moveToFirst()) {
do {
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
db.execSQL(k);
} while (cursor.moveToNext());
}
return workout_pk_id;
}
But for some reason this doesn't work. The ID the childs/exercises remains 0. Can you help me?
I don't know if the error is somewhere in the setup of my tables, in that case i could provide some more information.
Thanks in advance. /Jeppe
EDIT: This is used in android, and I have debugged and verified that the workout_pk_id is returned, 45 objects are found in the selectQuery and yet it doesn't work. I also tried ContentValues to update the values, didn't work.
Edited the " == " to " = ", but the value is still not updated.
This is from eclipse - I've created a workout called "test", with the ID 160.
The exercise "test1" has the ID 430 (unique) but the workout_id is still 0.
It's been awhile since I did any Android stuff but I believe the "==" operator is incorrect:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
The operator you're using is a comparative operator, "=" is the assignment operator.
I also believe there is a better way to do what you are trying to do, currently refreshing my memory on Android so I'll get back to you. In the meantime tell me if replacing the operator works
Yeah so another way you can do this is by using subqueries. So it would look something like:
UPDATE TABLE_EXCERCISE SET KEY_WORKOUT_ID = WORKOUT_PK_ID WHERE KEY_WORKOUT_ID =
(
*subquery here to select parent object ids*
)
Here's a link to help:
http://www.tutorialspoint.com/sqlite/sqlite_sub_queries.htm
Let me know how this works for you.
I think you have to look to your update query.
It has to be:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " = " + workout_pk_id;
Look at the "=" between KEY_WORKOUT_ID and workout_pk_id.

FTS3 | rowid problems | delete dont work

I recently updated my database to FTS3 due to that I implented search functionality.
My FTS3 table:
db.execSQL("CREATE VIRTUAL TABLE " + TABLE_FTS + " USING fts3(" + COL_ID + ", " + COL_KEY_NAME + ", "
+ COL_KEY_WEBURL + " , " + COL_KEY_MAINURL + ", " + COL_KEY_CODEC + " " + ");");
I always deletet entrys from my listview with the ContextMenu. I used a method like this:
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
delete(info.id);
updateList();
public void delete(long id) {
int numDeleted = database.delete("stations" , "_ID = ?", new String[] { Long.toString(id) } );
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
public void updateList() {
data.requery();
dataSource.notifyDataSetChanged();
}
The method, info.id don't get me the position, so I'am changed it to info.position. Position is right, but delet dont work. Ok, than I tried a simple delete instead of via Android Method.
database.execSQL("DELETE FROM " + DatabaseHelper.TABLE_FTS + " WHERE " + DatabaseHelper.COL_ID + "='" + id + "'");
Don't work, too. It seems that the column, COL_KEY_ID = BaseColumns._ID with an autoincrementing number don't exists in FTS3 anymore? I figured out, that I could use rowid but its not working as intended. If I delete my first entry, the entrys below get weird deleted.
How I can get this back working like before?
Edit: Found now fix ..
Found fix. Don't delete by ID, delete now by name.
I assume the problem comes from
_ID = ?
_ID is an integer yet ? is replaced by a String. Same for your second not working approach.

Categories