Android database can't update - android

I'll try update database but it can't update. It insert correctly but don't change rows with new ones.
mydatabase = getMydatabase();// this.getWritableDatabase();
ContentValues devices = new ContentValues();
devices.put(KEY_NAME, name);
devices.put(KEY_ADDRESS, address);
devices.put(KEY_GRADE, grade);
devices.put(KEY_ARRAY,gradeArray);
try{
mydatabase.insertOrThrow(DATABASE_TABLE, null, devices);
} catch (SQLiteConstraintException e) {
String where = "'"+address+"'='"+KEY_ADDRESS+"'";
mydatabase.update(DATABASE_TABLE, devices, where,null);
}
mydatabase.close();
This code in function which take different grade and gradeArray values. They are strings.
Database create statement:
String create = String.format("CREATE TABLE %s ( %s INTEGER PRIMARY KEY AUTOINCREMENT,"+
" %s TEXT ,%s TEXT NOT NULL UNIQUE , %s TEXT NOT NULL, %s TEXT);",
DATABASE_TABLE, KEY_ROW_ID, KEY_NAME, KEY_ADDRESS, KEY_GRADE, KEY_ARRAY);

String where = "'"+address+"'='"+KEY_ADDRESS+"'";
You're comparing a literal to a literal here. Remove the '' from the column name, e.g.
String where = KEY_ADDRESS + "='"+address+"'";
To avoid SQL injection as such, use parameters:
String where = KEY_ADDRESS + "=?";
mydatabase.update(DATABASE_TABLE, devices, where, new String[] { address });

Related

SQLITE: Display difference between three table difference with two condition

I have 2 tables naming labels5,labels.
i would like to compare the difference between this two column data and display.
same like below i need it in sqlite query.
current codings.
public Cursor getLotsPerCustomer1(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[] {
String.valueOf(name)
};
return db.query(TABLE_LABELS, null, whereclause, whereargs, null, null, ROUTE);
}
i want same as below in sqlite format. please advise.
select t1.route from labels t1
left
join labels5 t2 on t1.route = t2.number
where t2.number is null
There is two condition is involved.
First condition is check the table "customer" and search the matching result from table labels which is working fine this query.
public Cursor getLotsPerCustomer1(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[] {
String.valueOf(name)
};
return db.query(TABLE_LABELS, null, whereclause, whereargs, null, null, ROUTE);
}
Second condition is ,
After passing the first condition then it should also compare with table "labels5" thats where i struck .Appreciate your advise.
TABLE CUSTOMER:
CREATE TABLE "customer" (
"_id"
TEXT,
"customer_name"
TEXT
);
TABLE LABELS
CREATE TABLE "labels" (
"sno" INTEGER,
"route" TEXT,
"id" TEXT,
"_id" TEXT
);
TABLE LABELS5
CREATE TABLE "labels5" (
"id3" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"number" TEXT NOT NULL UNIQUE,
"outletname" TEXT,
"sunday" INTEGER,
"monday" INTEGER,
"tuesday" INTEGER,
"wednesday" INTEGER,
"thursday" INTEGER,
"saturday" INTEGER,
"closed" INTEGER,
"calling" TEXT,
"week" INTEGER
);
You can do it with rawQuery():
public Cursor getRoutes(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String sql = "select t1.route from labels t1 left join labels5 t2 on t1.route = t2.number where t2.number is null";
return db.rawQuery(sql, null);
}
A better way to get the values from one table that aren't in another is to use EXCEPT:
SELECT route FROM labels
EXCEPT
SELECT number FROM labels5;
select customer_name as FirstTable,route as SecondTale,number as ThirdTable
from customer,labels,labels5
where customer._id=labels._id AND labels.route=labels5.number

Strange bug with sqlite android

I'm facing BIG and strange problem , i have sqlite android database app on many mobile phones what is works perfectly , but when uses my app on lenovo or asus 7 inch tablet I'm facing no records stored in database , so i think maybe there some problems with getting current data with local.getdefualt()
here is my code :
INSERT statment :
public long addCheckPoint(String fleetNumber, String NoOFStudents,String Location_Longitude,String Location_Latitude){
SQLiteDatabase db = this.getWritableDatabase();
String ActionDate = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss",Locale.getDefault()).format(new Date());
ContentValues values = new ContentValues();
values.put("FleetNumber", fleetNumber);
values.put("CheckPointID", CheckPoint(fleetNumber));
values.put("NoOFStudents", NoOFStudents);
values.put("Location_Longitude", Location_Longitude);
values.put("Location_Latitude", Location_Latitude);
values.put("ActionDate", ActionDate);
values.put("PathStatus", "Open");
return db.insert("CheckPoints",null, values);
}
getting result statment :
public Cursor getCheckPointRows(String fleetNumber){
SQLiteDatabase db = this.getWritableDatabase();
String ActionDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String qq = "select CheckPointID , FleetNumber, NoOFStudents , ActionDate from CheckPoints where FleetNumber = "+ fleetNumber +" and date(ActionDate)='"+ActionDate+"'" ;
Cursor cursor = db.rawQuery(qq, null);
if(cursor != null && cursor.moveToFirst()){
return cursor;
}
db.close();
return cursor;
}
table strc
// SQL statement to create CheckPoints table
String CREATE_CheckPoints_TABLE = "CREATE TABLE CheckPoints ( " +
"ID INTEGER PRIMARY KEY AUTOINCREMENT , " +
"FleetNumber INTEGER, "+
"CheckPointID INTEGER,"+
"NoOFStudents INTEGER,"+
"Location_Longitude TEXT,"+
"Location_Latitude TEXT,"+
"PathStatus TEXT,"+
"ActionDate TEXT)" ;

how to check if a value already exist in db, and if so how to get the id of that row? android sql

i have created the next db file -
String sql = ""
+ "CREATE TABLE "+ Constants.TABLE_NAME + " ("
+ Constants.NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constants.NAME_PERSON + " TEXT"
+ ")";
db.execSQL(sql);
Now what I would like to know is, how to be able to run on the db and to know if a name already exist sin the db, and if so i would like to get the id of that row.
all i can understand is that i should use the
Cursor c= db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
but I don't have a clue what I should do next -
so thanks for any kind of help
you can add this in your DB and call the function passing "to be searched key" as an argument
public boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
if (cursor.moveToFirst()) {
return true;
}else{
return false;
}
}
Where KEY_TITLE is the column name in your table.
Take more example on this:
AndroidSQLite
AndroidSQLite with multi tables
Make a SELECT request. Then check with if(cursor.moveToFirst()) if your name is already existing. (moveToFirst() return true if there is at least 1 value).
So if your value is existing, juste get its id with cursor.getString(cursor.getColumnIndex("_id"));

Cannot update last row on SQLite

public public udpateNoteInfo(String text){
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val,"ORDER_BY("+KEY_ID+") DESC LIMIT 0,1", new String[]{text});
}
I try to update the last row of the KEY_CONTENT5 column in my SQLite, but it's error.
I guess its mistake at "ORDER_BY("+KEY_ID+") DESC LIMIT 0,1" but I don't know how to make it correct. Please tell me if you know that. Thank you.
ERROR:
09-05 11:47:54.769 E/Database( 4386): Error updating note=Test using UPDATE PERSONAL_TABLE SET note=? WHERE _id = (SELECT max(_id) FROM PERSONAL_TABLE)
Activity class:
public void updateNote(String txt) {
mySQLiteAdapter = new PersonalSQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
if (cursor != null) {
mySQLiteAdapter.udpateNoteInfo(txt);
}
mySQLiteAdapter.close();
}
SQLiteAdapter class (not activity):
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID + " = (SELECT max("
+ KEY_ID + ") FROM " + MYDATABASE_TABLE + ")",
new String[] { text });
}
You can't put an order by in an update.
You can try something like this:
WHERE id=(SELECT max(id) FROM TABLE) if you want to update the last id, assuming your sequences aren't modified.
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID+" = (SELECT max("+KEY_ID+") FROM "+MYDATABASE_TABLE+")", null);
}
My final answer.
You can query the ID, and then, update this row... if your key_id values are not unique, you'll need to use your primary key column(s) instead of this one...
Cursor cLast = db.query(MYDATABASE_TABLE, [KEY_ID], null, null, null, "ORDER_BY("+KEY_ID+") DESC", "LIMIT 0,1");
if (cLast.moveToFirst()) {
long lastKey = cLast.getLong(0); // if it's not a long, use the appropriate getter
sqLiteDatabase.update(MYDATABASE_TABLE, val, "WHERE KEY_ID=?", lastKey);
}
UPDATE table set col = 1 WHERE id = (SELECT MAX(id) FROM table)

update sql database with ContentValues and the update-method

I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
String error = e.getMessage().toString();
}
but I get following error:
android.database.sqlite.SQLiteException: near "15": syntax error: ,
while compiling: UPDATE mytable SET location=?, name=? WHERE
id=2010-09-21 15:05:36.995
I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.
You're using the update function wrong. It should be like this:
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(id)};
db.update(DATABASE_TABLE, dataToInsert, where, whereArgs);
The Strings in the whereArgs array gets substituted in for each '?' in the where variable.
ie. if you had where = "name=? AND type=? then the first '?' would get replaced by whereArgs[0] and the second by whereArgs[1].
Actually, you just need to add apostrophes to your where clause. So it ought to be:
String where = "id='" + id + "'"
(note: however, this is not best practice, as it theoretically leaves open to injection attacks)
I have an other approach
public boolean updateEmployee(TalebeDataUser fav) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUMN_ID, fav.getId());
contentValues.put(DBHelper.COLUM_AD, fav.getAd());
contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());
String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
return affectedRows > 0;
}
Actually what exactly you written is correct. The syntax is correct.
But you have to check these.
String where = "id" + "=" + id;
In the above declaration "id" should be type number and id should be int.
And if id is a type of TEXT then follow #Adam javin answer.

Categories

Resources