SQLite only one column get updated Android - android

I have a Sqlite database that works fine, I can insert rows with no problem, but when I try to do an update only one column get updated. I get a return value of 1, but only the column SCANNED get updated, that is the only column that already had a value of 0 and was change to 1.
public int UpdateScanInvoice(String Invoice, int scanned, String empname,
int empnum) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String formattedDate = df.format(c.getTime());
SimpleDateFormat tf = new SimpleDateFormat("hh:mm:ss",Locale.US);
String formattedTime = tf.format(c.getTime());
String strFilter = MySQLiteHelper.TICKETNR + "='" + Invoice +"'";
ContentValues scanvalues = new ContentValues();
scanvalues.put(MySQLiteHelper.LOADEMPNAME, empname);
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
scanvalues.put(MySQLiteHelper.LOADEMPNUM, empnum);
scanvalues.put(MySQLiteHelper.LOADDATE,formattedDate);
scanvalues.put(MySQLiteHelper.LOADTIME, formattedTime);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
return rowUpdated;
}
Maybe my original insert is wrong?
This is the original insert.
values.put(MySQLiteHelper.SCANNED, 0);
values.put(MySQLiteHelper.LOADDATE, "");
values.put(MySQLiteHelper.LOADTIME, "");
values.put(MySQLiteHelper.LOADEMPNAME, "");
values.put(MySQLiteHelper.LOADEMPNUM, "");
I the file has 19 columns and only the last 4 will not update or take any value when I do an insert.
I deleted the data recreated the database, same result.
Thanks,
KimHJ

Why are you again updating all the values You want to change the SCANNED value for that just update that value only like this..
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
for updating only SCANNED this is enough but you are updating all the values..this will replace your all old data

Related

sqlite database overwrites existing record than inserting new record in physical device

I am facing challenge where i am unable to insert new record into table, rather it overwrites the first record in the table.
This happens in the physical device where as it is working fine in the emulator.
Following is the code used to insert the record:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss", Locale.getDefault());
String strDate = formatter.format(date);
//SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING);
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues values = new ContentValues();
//values.put("UserId",1);
values.put("NoQPassed", scoreValues.get("NoPassed"));
values.put("NoQFailed", scoreValues.get("NoFailed"));
values.put("NoQSkipped", scoreValues.get("NoSkipped"));
values.put("SubjectName", scoreValues.get("strSubjectName"));
values.put("CompletedDateTime", strDate);
intRetVal= db.insert(score_Table_Name, null, values);*/
String strQuery="insert into "+score_Table_Name+" values ('"+strDate+"','"+scoreValues.get("NoPassed")+
"','"+scoreValues.get("NoFailed")+"','"+scoreValues.get("NoSkipped")+"','"+scoreValues.get("strSubjectName")+"')";
db.execSQL(strQuery);
db.close();
Tried inserting using db.insert and db.executeSQL, but none help. Can someone help me where i am going wrong?
I didnt add any primary key or autoincrement key to make sure the conflict is not because of that column. Do we always need to have primary key to insert new record?
you can use below getCount() method to count occurrences. if getCount(name)== 0 then do inserting. otherwise not inserting and try to log.
public int getCount(String name) {
Cursor c = null;
try {
db = Dbhelper.getReadableDatabase();
String query = "select count(*) from TableName where name = ?";
c = db.rawQuery(query, new String[] {name});
if (c.moveToFirst()) {
return c.getInt(0);
}
return 0;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
But this logic may not be valid if you say you override it. I think there is no override possibilities in that android sqlite. Please check you might be drop your database any where before inserting new record. It may seems like override data

Bug in my SQLite based application. using date. Android

All!
My code:
This method needs to check current date and if it is changed it will make new record in db.
public static void updateHintBase(SQLiteOpenHelper database)
{
String currentDate = getDateInString();
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.query("HINTS",
new String[]{"CURRENT_DATE"},
"CURRENT_DATE = ?",
new String[]{currentDate},
null, null, null);
int countRow = cursor.getCount();
cursor.close();
if (countRow==0)
{
ContentValues values = new ContentValues();
values.put("CURRENT_DATE", currentDate);
values.put("SPENT", 0);
values.put("TOTAL", TOTAL_HINTS);
db.insert("HINTS", null, values);
}
db.close();
}
This method transforms date to String :
private static String getDateInString()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
return date;
}
Table structure:
db.execSQL("CREATE TABLE HINTS (CURRENT_DATE TEXT PRIMARY KEY , "
+ "SPENT INTEGER,"
+ "TOTAL INTEGER);");
But my code doesn't work. First time it works, but the second time when date was changed my first method finds element in cursor anyway...
For example:
1) Today 16.01.2017. My application was executed. Everything is all right.
2) Today 18.01.2017. My application was executed and I expect that method cursor.getCount() will return to me 0 and new row with new date will be created. But it returns to me 1. etc.
You may have to set cursor to cursor.MoveToNext() You are also closing the cursor before you get the information which may be the problem. Lastly looping through the cursor is the most efficient way to get more that one piece of information.
Please try this query:
cursor = db.rawQuery("select count(YOUR_ID) from HINTS where CURRENT_DATE = ? ", new String[] {currentDate});
Oh! I found my mistake!
Word "CURRENT_DATE" is reserved by SQL.
https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions037.htm#SQLRF00628
That's why my code works incorrect.
I change "CURRENT_DATE" to "TODAY" an now it works fine.

SQLite extracting day from date issue

I have a DATE field in my database with format 'YYYY-MM-DD'. Now I want to extract only 'day' from that day i.e. 'DD'. My table name is 'date' and the column name where date is stored is 'lastDonated'. How do i do it... please look these codes for more details.
public String day() {
String b = "";
SQLiteDatabase db = getWritableDatabase();
String query = "???(what to place in here?)";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
b = c.getString(c.getColumnIndex("lastDonated"));
c.moveToNext();
return b;
}
I only have one row in the database
Use this query
SELECT strftime('%d', YourDateColumn) AS SomeAlias FROM YourTable
And get the value like this
b = c.getString(c.getColumnIndex("SomeAlias"));
Reference: https://www.sqlite.org/lang_datefunc.html

Need sqlite Query with substring

I want to fetch records from sqlite database table called messages.
I have a column named like Message_dated in the form of following "Jan 20, 2015 10:31:23". But in the cursor it is giving as it is.But now i want only date from message_dated column i dont want time.I am using to call query like following.But it is giving full date and time.
ColumnName = DatabaseHelper.TABLE_MSGS.COL_MESSAGE_DATED,
ColumnId = DatabaseHelper.TABLE_MSGS.COL_MESSAGE_DATED
String[] columns = new String[] {
DatabaseHelper.TABLE_MSGS.COL_MESSAGE_ID + " as _id",
columnName, columnID };
cursor = db.query(DatabaseHelper.TABLE_MESSAGES_NAME,
columns, null, null, columnID, null, null);
Please tell me how can i do it.Thanks in advance.
you can't retrieve it without time because a date object is already found to return that, however you can manipulate it so you can store it in a string and use it in a different format using the code bellow:
String input = "Jan 20, 2015 10:31:23";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
hope this will help you.

Getting an SQLite working within Android and accessing data

I am trying to get an SQLite database to work in Android and have a few questions!
I have put the following in the onCreate method of my database class, which extends SQLiteOpenHelper.
db.execSQL("CREATE TABLE IF NOT EXISTS `challenge` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `date` TEXT )");
I then have the following method.
public void addChallenge(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
ContentValues values = new ContentValues();
values.put("date", fDate);
db.insert("challenge", null, values);
}
And the following would grab the challenge added above back.
public int getChallengeId(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
String countQuery = "SELECT id FROM challenge WHERE date = " + fDate;
Cursor cursor = db.rawQuery(countQuery, null);
int challenge_id = 0;
if(cursor.moveToFirst()){
challenge_id = cursor.getInt(0);
}
return challenge_id;
}
My issue is that the challenge ID is returning as 0.
So I have a few questions.
Where is the database stored by default within Android?
Am I calling this correctly?
The code I use to access the above methods is as follows
Database db_add = new Database(context);
db_add.addChallenge();
db_add.close();
Database db_get = new Database(context);
challenge_id = db_get.getChallengeId();
db_get.close();
Any ideas?
Thanks.
The SQL query is not correct.
2015-02-23 tells the database that you want to subtract the numbers 2 and 23 from the number 2015.
Strings must be 'quoted'.
However, you should avoid such formatting problem by using parameters:
String countQuery = "SELECT id FROM challenge WHERE date = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{ fDate });

Categories

Resources