Android sqlite update not done in table - android

Following is my code for update record done.
try {
String str_edit = edit_note.getText().toString();
Toast.makeText(getApplicationContext(), str_edit,
Toast.LENGTH_LONG).show();
Toast.LENGTH_LONG).show();
String rawQuery="UPDATE " + GlobalVariable.getstr_tbl_name()
+ " SET note = '" + str_edit + "' where name = '"
+ str + "' ";
db.execSQL(rawQuery);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Code for Display:
try {
Cursor note_cursor = db.query(GlobalVariable.getstr_tbl_name(),
new String[] { "note" + " as note" }, "name" + "=?",
new String[] { GlobalVariable.getstr_food_name() }, null,
null, null);
if (note_cursor.moveToFirst()) {
int notecol = note_cursor.getColumnIndex("note");
do {
String str = note_cursor.getString(notecol);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_LONG).show();
edit_note.setText(str);
} while (note_cursor.moveToNext());
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I am getting all variable value i.e global variables and all but update does not reflects on table.
What wrong i am done?

whenever we try to update our database then just clean and uninstall your app then again install may be some changes not take place when we don't uninstall it if u find correct then tell other wise we will see the next

Should
int notecol = note_cursor.getColumnIndex("name");
instead be
int notecol = note_cursor.getColumnIndex("note");
since in the first block of code you are updating note..

The problem is that you try to update your DB using a rawQuery method instead of a execSql. RawQuery is intended to retrieve data from your database, while execSql lets you
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
You can also consider to use public int update (String table, ContentValues values, String whereClause, String[] whereArgs) method.

Related

Android - SQLiteException while deleting record

Currently We have one application in which we are receiving many crash reports while deleting record from database .
Here is method in which app is crashing.
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = '" + nickName + "'", null);
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
but we am getting following exception:
android.database.sqlite.SQLiteException: near "adz": syntax error
(code 1): , while compiling: DELETE FROM groups_map WHERE
gmap_nick_name = ''adz.'
Any help will be appreciated.
Look at delete signature:
int delete (String table, String whereClause, String[] whereArgs)
Third argument is where args:
You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings.
It's automatically escaped, so there is no need to put quotes (', ") manually.
Use where args instead of strings concating:
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = ?", new String[] { nickName });
Try Like This
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
database .execSQL("DELETE FROM "+ TABLE_NAME_GROUP_MAP + " WHERE " + COLUMN_GMAP_NICK_NAME + " = "+nickName+"");
database .close();
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
Try this
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "= ?" , new String[]{Long.toString(nickName)});
You should also use parameter markers because appending values directly is error prone when the source contains special characters.
try following because it will also prevent SQL injections to your app
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "=?", new String[]{String.valueOf(nickName));

Update single data in a coloumn in android sqlite database

I am trying to change a single value in a coloumn in android sqlite.
but i am not getting the result. My db query is given below
public Cursor update_MaxCrAmnt(String maxcramount, String accId){
return db.rawQuery("UPDATE AccMaster SET Max_CrAmt=? WHERE Acc_No=? AND Bal_Type=?", new String[] {maxcramount, accId, "Cr"});
}
This method calling code is given below, amnt and accid are string values.
try {
db.open();
db.update_MaxCrAmnt(amnt,accid);
db.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("Update error", ""+e.getMessage());
}
Need your help.. Thanks in advance.
NB:Please Dont Use this method as there is chance of SQL injection when do like this
String update = "UPDATE AccMaster SET Max_CrAmt = '"+ maxcramount +"' WHERE accId = " + accId +"AND Bal_Type= Cr";
db.execSQL(update);

Error on using REPLACE character manipulation function on query SQLite Android

it gives me an error when I am using this key but when I use LENGTH, it works fine. I hope it is allowed on android sqlite coz it's the best way for this:
I am just trying to remove the spaces after words that will be selected from Database.
public ArrayList<String> getCorrectList() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT REPLACE(Level_1, ' ', '') FROM " + TABLE, null);
ArrayList<String> resultsList = new ArrayList<String>();
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c
.getColumnIndex("Level_1"));
resultsList.add("" + c.getColumnIndex("Level_1"));
} while (c.moveToNext());
}
}
} catch (SQLiteException e) {
Log.e("Database", "Cannot get List (" + e + ")");
}
Log.d("array", "List: " + resultsList);
Collections.shuffle(resultsList);
return resultsList;
}
This works fine in SQLite3 shell:
e$ sqlite3
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t(a,b,c);
sqlite> select replace(a,' ', '') from t;
REPLACE is both a function and a command in SQLite3. Perhaps db.rawQuery is parsing the query and getting confused by REPLACE. Try this:
db.rawQuery("select rtrim(replace(Level_1, ' ', '')) FROM " + TABLE, null);

How to delete a Row from the DB in android

I'm new to android ... i have developed a Database application , were i'm able to insert the textfield details , but i want to delete the specific row , i need to search by name and delete the user.
can someone help me on this :
My DB code is:
public void deleteRow(String firstname)
{
try {db.delete(TABLE_NAME,TABLE_ROW_ONE + "=?" + new String[]{firstname},null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
Activty code is :
deleteButton.setOnClickListener
(
new View.OnClickListener()
{
#Override public void onClick(View v) {deleteRow();}
}
);
private void deleteRow()
{
try
{
db.deleteRow(textFieldOne.getText().toString());
updateTable();
emptyFormFields();
}
catch (Exception e)
{
Log.e("Delete Error", e.toString());
e.printStackTrace();
}
}
textFieldOne is the first name of the user.
can someone help me on this ..
Remove the null Argument from your delete method...
do like this ---->
db.delete(TABLE_NAME,TABLE_ROW_ONE + "=?" + new String[]{ firstname });
It will work fine...
I think you've misunderstood the purpose of ? in Android+sqlite.
the ? are used as a placeholder which are then replaced with the strings you pass as the third argument to delete and other similar database functions on Android.
In your code you're setting the selection argument a combination of the selection string and the selection arguments string array.
Changing the code from
/* ... */ TABLE_ROW_ONE + "=?" + new String[]{firstname},null);
to
/* ... */ TABLE_ROW_ONE + "=?", new String[]{firstname});
should do the trick.
You can also just say
db.delete(TABLE_NAME, TABLE_ROW_ONE + "='" + firstname + "'", null);
if you want to but the purpose of the ? is to do some kind of caching with the queries so they'd be faster next time.

Efficient batch SQL query execution on Android, for upgrade database

As we Android developers know, the SQLiteDatabase execSQL method can execute only one statement.
The doc says:
Execute a single SQL statement that is not a query. For example, CREATE TABLE, DELETE, INSERT, etc. Multiple statements separated by ;s are not supported.
I have to load in a batch of records, 1000 and counting.
How do I insert these efficiently?
And what's the easiest way to deliver these SQLs with your apk?
I mention, there is already a system database and I will run this on the onUpdate event.
I have this code so far:
List<String[]> li = new ArrayList<String[]>();
li.add(new String[] {
"-1", "Stop", "0"
});
li.add(new String[] {
"0", "Start", "0"
});
/* the rest of the assign */
try {
for (String[] elem : li) {
getDb().execSQL(
"INSERT INTO " + TABLENAME + " (" + _ID + "," + NAME + "," + PARSE_ORDER
+ ") VALUES (?,?,?)", elem);
}
} catch (Exception e) {
e.printStackTrace();
}
How do I insert these efficiently?
Use transaction:
db.beginTransaction();
try {
for(;;) {
db.execSQL(...);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
I think what you have is the only way to load those 1000 records, now, as far as deploying that DB with your apk file, check out this post:
http://www.helloandroid.com/tutorials/how-have-default-database

Categories

Resources