Android SQLITE DB update table not working - java

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.

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.

IllegalStateException on Cursor

I am getting this error when trying to read from the SQLite DB
IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = dbHelper.readNumber(database);
String ItemId;
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//getting the ERROR here
ItemId = cursor.getString(cursor.getColumnIndex(DbContract.ITEMID));
number = cursor.getString(cursor.getColumnIndex(DbContract.PHONE_NUMBER));
callType = cursor.getString(cursor.getColumnIndex(DbContract.CALL_TYPE));
callDate = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DATE));
callDuration = cursor.getString(cursor.getColumnIndex(DbContract.CALL_DURATION));
arrayList.add(new PhNumber(ItemId, number, callType, callDate, callDuration));
if (debug) {
Log.i(TAG, "DATA FOUND IN DB:\n" + "\t ID: " + ItemId + ", Number: " + number + "\n");
}
}
cursor.close();
dbHelper.close();
result = true;
if (debug) {
Log.d(TAG, " Number of items in DB: " + arrayList.size());
}
}
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {"id", DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
This is my DB
private static final String CREATE = "create table " + DbContract.TABLE_NAME +
"(id integer primary key autoincrement,"
+ DbContract.ITEMID + " text, "
+ DbContract.PHONE_NUMBER + " text, "
+ DbContract.CALL_TYPE + " text, "
+ DbContract.CALL_DATE + " text, "
+ DbContract.CALL_DURATION + " text, "
+ DbContract.SYNC_STATUS + " text)";
In your projection, created by readNumber call, you have only the id and PHONE_NUMBER columns returned. Probably DbContract.ITEMID is not equal to id and when trying to lookup the DbContract.ITEMID in the cursor it is not found. To fix this you need to use ITEMID in readNumber method, something like:
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {DbContract.ITEMID, DbContract.PHONE_NUMBER};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}
Another issue is that you are trying to access other fields too, like: CALL_TYPE, CALL_DATE, etc.
So, in order to fix the issue you either:
Do not try to retrieve the fields that are not part of the result.
Add the needed fields in the projection too.
Found the issue:
I was trying to access the columns that were not added in the projects in readNumber method adding those projections solved the issue.
readNumber
public Cursor readNumber(SQLiteDatabase database) {
String[] projections = {
DbContract.ITEMID,
DbContract.PHONE_NUMBER,
DbContract.CALL_TYPE,
DbContract.CALL_DATE,
DbContract.CALL_DURATION};
return (database.query(DbContract.TABLE_NAME, projections, null, null, null, null, null));
}

SQLite Delete Query Error: no such column: ID (code 1)

I'm trying to delete a row in my SQLite db in my app. It keeps on crashing with
no such column: ID (code 1)
I've tried
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
but I still end up with the same
DB Structure:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +
" (ITEM_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NAME TEXT, " +
"PRICE INTEGER, " +
"DATE TEXT);");
}
Deletion query:
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + ITEM_ID + " = '" + Integer.toString(numID ) + "'";
db.execSQL(query);
My other select queries work perfectly fine so any help would be appreciated
You are trying to delete by ID, but your table uses ITEM_ID
change
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
to
db.delete(TABLE_NAME, "ITEM_ID=?", new String[]{Integer.toString(numID)});
Wouldn't ITEM_ID need to be within the "", rather than a variable??
String query = "DELETE FROM " + TABLE_NAME + " WHERE ITEM_ID='" + Integer.toString(numID) + "'";

can not add or update table

Trying to add a new record to a data table in MySQL fails with an error message:
can not add or update a child row
I can do the same command manually in xampp and it works fine, but not when it runs under my app.
here is the Code, starting with the table "users" and then "transactions"
public void CreateUsersTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Users ("
+ "Username varchar(80) NOT NULL,"
+ "Userpassword varchar(80) ,"
+ "User_GSM VARCHAR(30),"
+ "User_Tel_Home VARCHAR(30),"
+ "User_Address Varchar(100), "
+ "User_City Varchar(20), "
+ "User_Position Varchar(100), "
+ "PRIMARY KEY(Username))";
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
and the second table
public void CreateTransactionsTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Transactions ("
+ "TransactionsNum INT(18) NOT NULL AUTO_INCREMENT,"
+ "TransactionsDate DATE,"
+ "TransactionsAmount float(8), "
+ "TransactionsUsername varchar(80) ,"
+ "PRIMARY KEY(TransactionsNum) , "
+ "FOREIGN KEY(TransactionsUsername) REFERENCES Users(Username) )"; // foregign key is the key in this table to accessed from main calling
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
and finally, this the statement to update the DB
String addTRansSQL = "insert into transactions ( TransactionsDate , TransactionsAmount , TransactionsUsername ) "
+ " values( '" + sqlDate + "' , '" + tramount + "' , ' " + loggeduser + "' )";
Simply, you're trying to add a transaction row with a user that doesn't exists in the Users table, try these line "SET FOREIGN_KEY_CHECKS=0"

Android SQLite Couldn't Found Declared Column

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 :)

Categories