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.
Related
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));
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);
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.
I am working on the an application in which I want to update contact of particular person. When I update only contact first and last name then it working fine but I want to update full detail of contact like email address, number, postal addres etc.
Please provide me some useful link. Thanks in advance.
each field (email, name, adress) has its on mime type, which you should use
in order to update the field.
lets try to update the email for instance.
First, you should find the detail you want to update.
we will work with Data table, where each Data.RAW_CONTACT_ID represents a detail
about some contact.
So, we need to find the Data.RAW_CONTACT_ID where the id is the id of the contact you want
to edit.
Now we need to find the mimetype (the specific row which represents the detail) of
email (Email.CONTENT_ITEM_TYPE).
The data of an email is stored in the column Email.DATA - there we put the new email.
if you want a specific email type, you should add it to the query:
for example, if you want to add a home-email, then you should add Email.TYPE_HOME
to the query.
then we build a query and finally apply the change.
Here's an examle:
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String emailParams = Data.RAW_CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?";
String[] emailParamsWhere = new String[] { "contact_id", Email.CONTENT_ITEM_TYPE };
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(emailParams, emailParamsWhere).withValue(Email.DATA, "new email").withValue(Email.TYPE, Email.TYPE_HOME)
.build());
try
{
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null)
{
return true;
}
return false;
}
catch (RemoteException e)
{
Log.d(TAG, e.getMessage());
e.printStackTrace();
}
catch (OperationApplicationException e)
{
Log.d(TAG, e.getMessage());
e.printStackTrace();
}
For updating mobile phone, use this query:
String phoneParams = Data.RAW_CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? AND " + Phone.TYPE + " = " + Phone.TYPE_MOBILE;
String[] phoneParamsWhere = new String[] { "contact_id", Phone.CONTENT_ITEM_TYPE };
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(phoneParams, phoneParamsWhere).withValue(Phone.NUMBER, "mobile_number")
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build());
Hope I helped
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