Android How to Delete an android sqlite Database entry - android

This works to Insert a Row
public long insertRows(Double lat, Double log, String mdate,
String mycomment, String name) {
ContentValues value=new ContentValues();
value.put(COLUMN2,lat);
//System.out.println(COLUMN2+lat);
value.put(COLUMN3, log);
//System.out.println(COLUMN3+log);
value.put(COLUMN4, mdate);
//System.out.println(COLUMN4+mdate);
value.put(COLUMN5, mycomment);
//String mycomment = null;
//System.out.println(COLUMN5+mycomment);
value.put(COLUMN6, name);
return db.insert(TABLENAME,null,value);}
But I am unable to Delete a row programmatically.
I can provide more code or info if needed any help is greatly appreciated
this is what Im useing so far seems intemitant though
and Im still haveing issues updateing the listactivity
public boolean deleteEntry(long Id) {Id = GpsListactivity.rowid;
System.out.println("GPSDATABASE "+ TABLENAME + KEY_ROWID + "=" +Id);
return db.delete(TABLENAME,KEY_ROWID + "="+Id,null) > 0;}
// this is the update method
public boolean update(long Id, Double lat, Double log,
String mdate,String mycomment, String name) {
ContentValues updateValues = createContentValues(
lat,log,mdate,mycomment,name);
return db.update(TABLENAME, updateValues,"locationId=?" +Id,null) > 0;

You can use the method delete(String table, String whereClause, String[] whereArgs). For example:
String whereClause = "COLUMN4 = 'value'";
db.delete(TABLENAME, whereClause, null);
To delete a specific row, you will have to know information about that row which makes it unique (for example the row's primary key or a combination of data in its columns).
You can also reference the SQLiteDatabase documentation for more information.

Related

How to search for integer in a row at SqlDatabase with rawQuery?

here is my code:
public String getFriendName(int aFindexnum){
String sql = "SELECT * FROM peopleTable WHERE "+KEY_CBINDEX+"="+aFindexnum;
Cursor cursor = ourDatabase2.rawQuery(sql, null);
String Fname = cursor.getString(1);
cursor.close();
return Fname;
}
I am trying to search for an integer and than return other Value that is String in my sqldatabase
So i am passing in that aFindexnum which is the integer value in the Db and i want to find it
my problem was when i tried to do something like that:
public String getFriendName(int aFindexnum){
String aFindex = getString(aFindexnum);
String sql = "SELECT * FROM peopleTable WHERE "+KEY_CBINDEX+"=?";
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] {aFindex});
String Fname = cursor.getString(1);
cursor.close();
return Fname;
}
String aFindex = getString(aFindexnum); <<if i will turn this with
parse into String will it work ?
public long createEntry( String name, String phonenum ,int phoneindex) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PHONENUM, phonenum);
cv.put(KEY_CBINDEX, phoneindex);
return ourDatabase2.insert(DATABASE_TABLE, null, cv);
}
this is the entry of the sql Db, so u can see in the third column i am putting an int and i want to search for it and get the name and the phone.
thanks.
getString() in an activity gets a string from resources. Referring to a resource id with the name of an index number looks suspicious. If I understood your code and question, this
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] {aFindex});
should be
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] { String.valueOf(aFindexnum) });
and you can remove the first problematic getString().
When you query and get a Cursor, you'll have to move it to a valid row before accessing column data. Add
if (cursor.moveToFirst()) { ... }
If I understood your code and question,
By reading your sql String code you want row which matches KEY_CBINDEX value
If in your database data type of KEY_CBINDEX column is int then you can get integer value
By replacing
cursor.getString(1);
with
int intValue = cursor.getInt(cursor.getColumnIndex(KEY_CBINDEX));
or if is string, then replace with
int intValue = Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_CBINDEX)));
You have to replace it in your second code block.

How to update table in sqlite android

In my app i want to update my database table based on two column.Means update salary where firstname="ekant" and last name="kancha".So can any body plz tell me what will be the query i have to write.
public int updateStatus(int salary,String fname,String lName)
{
ContentValues cv=new ContentValues();
String where = fname+ "=" + "ekanta";
cv.put("salary",salary);
return sdb.update(DATABASE_TABLENAME, cv, where, null);
}
this code works only when i want to update based on first name..But i want to update based on firstname and lastname.
plz help me.thanx
Use placeholders. This makes it easier to read the SQL query and protects against SQL Injection (accidental or otherwise).
public int updateSalary (int salary, String fname, String lName)
{
ContentValues cv = new ContentValues();
cv.put("salary", salary);
/* use COLUMN NAMES here */
String where = "firstname = ? and lastname = ?";
/* bind VALUES here */
String[] whereArgs = new { fname, lname };
return sdb.update(DATABASE_TABLENAME, cv, where, whereArgs);
}
If you have constants (e.g. private final static COLUMN_FNAME = "firstname") for the COLUMN NAMES, then you can build where using these constants.
However, do not put VALUES in the where string. Instead, use ? and supply any VALUES via the whereArgs array as per the above example.
Also, it is possible for people (even within the same organization) to share the same first name and last name. Basing the database queries/updates around such a pairing will break in such cases so it may be prudent to work on designing the API to work with a better record identifier.
use this...
String where = fname+ "=" + "ekanta" + " and " + lname + "=" + "your lastname";

How can I update my EditText values?

I am new to android , as I am trying to update data using context menu item "EDIT". Using EDIT I will go to EditText layout then I will press update Note, But it's not updating the EditText Data.
My Code Database:
public void updateNote(String filename, String filedata, String duedate){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues updatenote = new ContentValues();
updatenote.put(Col_File_Name, filename);
updatenote.put(Col_File_Data, filedata);
updatenote.put(Col_Due_Date, duedate);
db.update(Table_Notepad, updatenote, Col_ID + "=?", null);
db.close();
}
Activity:
case R.id.Save:
String get_title = Title_Edit.getText().toString();
String get_content = Content_Edit.getText().toString();
String get_duedate = duedatetext.getText().toString();
if(!get_title.equals("") || !get_content.equals(""))
{
if (!isEdit) {
//if it isn't edit mode we just add a new note to db
Database_Notepad db = new Database_Notepad(Add_Task.this);
db.Create_Note(get_title, get_content, get_duedate);
} else {
//if this is edit mode, we just update the old note
Database_Notepad db = new Database_Notepad(Add_Task.this);
db.updateNote(get_title, get_content, get_duedate);
db.close();
}
}
Please Suggest, I think I need to correct database code. Please suggest. Thanks
Your function updateNote need Record ID which you want to update.
Like
public void updateNote(int id, String filename, String filedata, String duedate){
instead
public void updateNote(String filename, String filedata, String duedate){
and compare that id which your entire record, it will check and update your particular record, change your function function something like below:
public void updateNote(int id, String filename, String filedata, String duedate){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues updatenote = new ContentValues();
updatenote.put(Col_File_Name, filename);
updatenote.put(Col_File_Data, filedata);
updatenote.put(Col_Due_Date, duedate);
db.update(Table_Notepad, updatenote, "rowid= "+id,, null);// rowid or name of your id column
db.close();
}
and pass the id too along with others parameter.
Use
db.updateNote(id, get_title, get_content, get_duedate);
instead
db.updateNote(get_title, get_content, get_duedate);
In updateNode(), you need to change this update or insert values:
public void updateNote(long rowId, String filename, String filedata, String duedate){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues updatenote = new ContentValues();
updatenote.put(Col_File_Name, filename);
updatenote.put(Col_File_Data, filedata);
updatenote.put(Col_Due_Date, duedate);
if (rowId >=0)
db.update(Table_Notepad, updatenote, Col_ID + "=?", new String[] {""+rowId});
else
db.insert(Table_Notepad, null, updatenote);
db.close();
}
Then, if you are creating a new note you can call:
updateNote(-1, filename, filedata, duedate);
and if you are updating an existing one, you will have to pass in the ID:
updateNote(noteRowId, filename, filedata, duedate);.
Source: check these Android docs.
Need to pass row id to update in last argument
db.update(Table_Notepad, updatenote, Col_ID + "=?", new String[]{id});
Happy coding

How to update a row in Android database

Hi all I want to update a row on clicking on update button,but its doesn't work.
I have used following code.
public void btnUpdate(View v) {
handeler.updateData(updateName.getText().toString(), updatePhone .getText().toString(), updateEmail.getText().toString(),id);
}
public void updateData(String name, String phone, String email, String id) {
ContentValues values = new ContentValues();
values.put(COLUMN_FIRST, name);
values.put(COLUMN_SECOND, phone); values.put(COLUMN_THIRD, email); database.update(TABLE_NAME, values, id, null);
}
public void search() {
Cursor cursor = handeler.getData();
if (cursor.moveToFirst()) {
String phoneNo;
phoneNo = updateByPhone.getText().toString();
do {
String s1 = cursor.getString(2);
if (phoneNo.compareTo(s1) == 0) {
id = cursor.getString(0);
updateName.setText(cursor.getString(1));
updateEmail.setText(cursor.getString(3));
updatePhone.setText(cursor.getString(2));
}
} while (cursor.moveToNext());
}
}
So if any know please suggest me how to solve it.
Thanks
I see a couple possible issues:
1) You have an extra space updatePhone .getText().toString() should be updatePhone.getText().toString()
2) you are passing a variable id from btnUpdate to updateData but it is not clear where it is coming from (or even if it actually exists)
My bet is that #2 is your issue. You probably need to pass the id (I assume that's meant to be the RowId you want to modify in the db) in to the btnUpdate method:
public void btnUpdate(View v, long id)
There are other possibilities... you haven't shown your DB structure, so it could be that some constraint is causing the update to fail.
EDIT
The update method docs show this:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Note the part String whereClause. That's supposed to be a SQL WHERE statement (without the WHERE). You are only passing in the id, not a WHERE clause. Change your call to update to make that a WHERE clause and it should work. A couple of examples:
database.update(TABLE_NAME, values, "_id = " + id, null);
database.update(TABLE_NAME, values, "_id = '" + id + "'", null);
Both examples assume your row id column is labeled _id.
The first example is if id is an integer value. The issue there is that you are setting id as a string, so I'm unsure if this is the case or not. If it is supposed to be an int, you should get it using id = cursor.getInt(0); instead of id = cursor.getString(0);.
If it truly is a string and not an int, use the second version, which encloses id in single quotes to indicate it is a string.
Hope this helps!
Finally I got solution ,It was minor mistake,Using following code we can perform update operation
database.update(TABLE_NAME, values, BaseColumns._ID + "=" + id, null);
change the code
database.update(TABLE_NAME, values, "_id='?'", new String[]{id});
Edit
database.update(TABLE_NAME, values, "_id=?", new String[]{id});

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