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});
Related
Hy Guys, I am Beginner Android Developer. I need your help. i want to insert data into 2 tables of sqlite tblorder, and orderdtl. on orderdtl i have to insert data from multiple item from listview. i try to toast all variable that i want to inserted. their all appears. but when i try to save it. i get those error.
this is my DBDataSource.java
public order createorder(String orderid, String notes, long outletid) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid); // inserting a string
values.put(DBHelper.NOTES, notes); // inserting an int
values.put(DBHelper.OUTLET_ID, outletid); // inserting an int
long insertId = database.insert(DBHelper.TABLE_ORDER, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
order neworder = cursorToorder(cursor);
cursor.close();
return neworder;}
private order cursorToorder(Cursor cursor) {
order order = new order();
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
order.setorderdate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_DATE)));
order.setnotes(cursor.getString(cursor.getColumnIndex(DBHelper.NOTES)));
order.setoutletid(cursor.getLong(cursor.getColumnIndex(DBHelper.OUTLET_ID)));
return order;
}
The error refer to this code
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
And this code
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
orderid is string, i try to get from yyyyMMddHHmmss.this is the code:
private String orderid(){
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I would be very grateful for any help that you give.Thank You.
The query didn't match any rows. Check the result of moveToFirst() to see whether the operation succeeded and only then access cursor data.
Example:
order neworder = null;
if (cursor.moveToFirst()) {
order neworder = cursorToorder(cursor);
}
cursor.close();
return neworder;
The insertId you get from insert() is the sqlite row id for the row. It's likely not the same as ORDER_ID. To make a column an alias for rowid, declare it as INTEGER PRIMARY KEY.
The error I see in logcat is not about _Player_8, but about the unknown column "KEY_Team_Name"
The problem is in your activity, the line prior to the last one:
String EntryA =String.valueOf( db.getentry("Ravirrrr", "KEY_Team_Name"));
It should be:
String EntryA =String.valueOf( db.getentry("Ravirrrr", DatabaseHandler.KEY_Team_Name));
And the DatabaseHandler should have all column names public, as the getentry method requires a column name.
Edit: adding an answer to the question in the comments below.
After calling db.query, you should check if you got something by calling Cursor.isAfterLast(). If true, the select returned an empty result set.
In your example, you WILL get an empty result set as the code creates an entry with "Ravi" as the team name, then asks for a team named "Ravirrrr".
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";
This is what i am using for insert:
public long insert(String content, Date startAt, Date endAt) {
if (content == null || startAt == null) {
return 0;
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
contentValues.put(KEY_START_AT, startAt.getTime());
if (endAt == null) {
contentValues.putNull(KEY_END_AT);
} else {
contentValues.put(KEY_END_AT, endAt.getTime());
}
return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
now i want to create update method which will update last inserted row. How can i get last inserted row?
If you have an id attribute that works as a primary key, you can do a raw database query on SqlLite.
Cursor cc = this.mDb.rawQuery("SELECT *" + " FROM " + "<Your DATABASE_NAME> " +
"ORDER BY id " + "DESC LIMIT 1", null);
return cc;
Here,
1. It returns a cursor.
2. mDb is a SQLiteDatabase class instance.
3. ORDER BY id allows the query to sort by id number. As I said, if you have an id as primary key in your table, your latest entry will have the maximum id number.
4. DESC allows to sort by descending order.
5. LIMIT 1 allows to return only 1 row.
6. Always be careful when writing raw queries, white spaces inside the query can be a lot of pain when you do not handle them carefully.
For further queries you can see this tutorial. And obviously Divya's answer is also a good one.
You can use a cursor to retrieve rows and say :
cursor.moveToLast();
OR
cursor.moveToPosition(cursor.getCount() - 1);
When you insert a row in to your table the insert query returns the key of the last inserted row. You can now use this key to update this row.
for example
int newInsertedKey = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
update table_name set column_name = 'Change 2' where columnID = newInsertedKey
An efficient method would be to avoid anymore database queries to get the last updated row.
Maybe he should use something like this
public long getLastId() {
Cursor c = mDb.query(currentTableName, new String[] { "MAX(_id)" },
null, null, null, null, null, null);
try{
c.moveToFirst();
long id = c.getLong(0);
return id;
}catch(Exception e){
return 0;
}
}
where _id is column by which you identify rows
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.
working on a content provider and I'm having an issue with it. When I try to update a certain row in the SQLite database through the content provider, it updates the column in all the rows, not just the row I specify. I know the CP is working because I can access it, populate a listview with it, and change the content of column, but never just one column.
Here is the relevant update method
public int update(Uri url, ContentValues values, String where,
String[] whereArgs) {
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
int count;
String segment = "";
switch (URL_MATCHER.match(url)) {
case ITEM:
count = mDB.update(TABLE_NAME, values, where, whereArgs);
break;
case ITEM__ID:
segment = url.getPathSegments().get(1);
count = mDB.update(TABLE_NAME, values,
"_id="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URL " + url);
}
getContext().getContentResolver().notifyChange(url, null);
return count;
}
and here is the code I use to (try to) update it.
ContentValues mUpdateValues = new ContentValues();
mUpdateValues.put(ContentProvider.HAS, "true");
mUpdateValues.put(ContentProvider.WANT, "false");
mRowsUpdated = getContentResolver().update(Uri.parse(ContentProvider._ID_FIELD_CONTENT_URI
+ rowId), mUpdateValues, null, null);
and here is the URI
URL_MATCHER.addURI(AUTHORITY, TABLE_NAME + "/#", ITEM__ID);
Thanks, any help would be appreciated.
EDIT I have also tried
mRowsUpdated = getContentResolver().update(
ContentProvider._ID_FIELD_CONTENT_URI, mUpdateValues,
null, null);
and
mRowsUpdated = getContentResolver().update(
ContentProvider.CONTENT_URI, mUpdateValues,
null, null);
You are not specifying a WHERE clause, which is what is used to update only specific rows. The default behavior of content providers is to update all the rows, unless you specify conditions.
From the docs:
developer.android.com/reference/android/content/ContentResolver.html
Parameters
uri The URI to modify.
values The new field values. The key is the column name for the field. A null value will remove an existing field value.
where A filter to apply to rows before updating, formatted as an SQL WHERE clause (excluding the WHERE itself).