Android Sqlite database is not updating the data?? - android

i am using this code to update the values
this Code is working properly without an error there is no error in query but when i show data after updating its showing the old data??
this is the code i am using for updating the data in sqlite.
#Override
public void onClick(View v) {
if (v == Update) {
try {
ContentValues CV = new ContentValues();
CV.put("cname", EditName.getText().toString());
CV.put("mobileno", EditMobile.getText().toString());
CV.put("phone", EditLandline.getText().toString());
CV.put("address", EditAddress.getText().toString());
CV.put("email", EditEmail.getText().toString());
CV.put("picture", Editbytes);
DB.update("contacts", CV, "cname=" + V,null);
Intent I = new Intent(ctx, ContactList.class);
ctx.startActivity(I);
// DB.execSQL("insert into contacts values('" + Name.getText() + "','" + Mobile.getText() + "','" + Phone.getText() + "','" + Add.getText() + "','" + Email.getText() + "')");
Toast.makeText(ctx, "Contact Updated...",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(ctx, "Fail to Update Contact.." + e, Toast.LENGTH_LONG).show();
}
} else if (v == Delete) {
}
}

Can you please try this,
DB.update("contacts", CV, "cname=" + V,null);
What is the V, is that particular name , I thingk, you may try to udapte using id, which is more effective.
Change to
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.update("contacts", CV, "cid=" + "=" + id, null);
db.close(); // Closing database connection
However, if you don't update, please clean your project and rebuild, that might work.If this will not help, please post you logcat.

Is there any chance WHERE clause is not matching any rows?
You can test your condition on console with:
Log.i(db.execSQL("SELECT * FROM contacts WHERE cname=" + V));
But I think the best way to test this is connect directly to database:
Open a terminal on Android Studio (View > Tool Windows > Terminal)
Enter adb shell (if command fails, add your adb installation into PATH variable)
The database file is usually stored in /data/data/com.your.package/database/
Run sqlite3 /data/data/com.your.package/database/YourAPP.db to open a prompt where you can run all SQL commands
Another good answer

Related

Android to MS Sql query

my application was working fine but then i changed something and its not inserting records in the database. when ever i press the submit button it show me toast "Record not inserted"
here is the code
connect=connn.ConnHelper(username, password, db, ipaddress);
if (connect == null){
Toast.makeText(getBaseContext(),"Connection Unsuccessfull",Toast.LENGTH_LONG).show();
}
else {
//inserting records in database
//is se nechy nechy
try {
st = connect.createStatement();
String query = "insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) values('" + name + "','" + city + "','" + add + "','"+spec+"','"+ph+"','"+cn+"','"+img+"','pending');";
preStatement = connect.prepareStatement(query);
int k=preStatement.executeUpdate();
if(k==1){
Toast.makeText(getBaseContext(),"Record Inserted Successfully",Toast.LENGTH_LONG).show();
Intent imageIntent = new Intent("com.androsoft.application.Profile");
imageIntent.putExtra("Id",Cnic.getText().toString());
startActivity(imageIntent);
}
else{
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
} catch (SQLException e) {
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
here its returning zero to k.
mydatabase entities are.
database entities
Try to run this application in debug mode, and get the String query value on runtime (like insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) value('dav','city','new york',null,'33','f');, then try to execute the query directly in sql server. If there is no problem in your query so this is something in the connection to the data base or problem in the application.

Android Sqlite insertion of a single quote ex. "O'Connor"

For some reason I can't get the single quote with apostrophes in a name field to submit to my sqlite database.
Here's where I get the input and call the database function
if(fnamelabel.contains("'") || fnamelabel.contains("-")){
fnamelabel = DatabaseUtils.sqlEscapeString(fnamelabel);
}else if(lnamelabel.contains("'") || lnamelabel.contains("-")){
lnamelabel = DatabaseUtils.sqlEscapeString(lnamelabel);
}
Log.w("myApp", "fname " + fnamelabel + ".");
Log.w("myApp", "lname " + lnamelabel + ".");
try{
//if all fields are filled and has a number between 0 and 99
LiteHandlerPlayers db = new LiteHandlerPlayers(getApplicationContext());
if(db.insertLabel(fnamelabel, lnamelabel, pnumlabel)){
db.getWritableDatabase();
db.insertLabel(fnamelabel, lnamelabel, pnumlabel);
Toast.makeText(getApplicationContext(), "#" + pnumlabel + " " + fnamelabel + " " + lnamelabel + " has been added to your team.", Toast.LENGTH_SHORT).show();
db.close();
}else{
Toast.makeText(getApplicationContext(), "That player is already on your team!", Toast.LENGTH_SHORT).show();
}
Here's my function within the db
if(flag){
//no player in db with name
ContentValues values = new ContentValues();
values.put(Player_fname, label);
values.put(Player_lname, label2);
values.put(Player_num , label3);
values.put(Player_gplay, 0);
values.put(Player_assist, 0);
values.put(Player_shots, 0);
values.put(Player_goals, 0);
values.put(Player_shagn, 0);
values.put(Player_gallw, 0);
values.put(Player_assist, 0);
db.insert(Table_labels, null, values);
db.close();//close db
return true;
}else{
db.close();
return false;
}
and eventually gets displayed on a spinner on a different screen but the error that i keep getting for an example name like Bob O'Connor (O'Connor is changed to O''Connor at this point) is that there is a syntax error near the O in O''Connor which is pretty vague. ((1) near "O": syntax error , is exactly what it says) If anyone can enlighten me I would be much obliged.

Android sqlite update not done in table

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.

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);

Android: Having trouble updating a row in a database after determining what row I need to update

I have a table that contains a list of devices with catagories like type, manufacturer and model and a device ID. Another table called system uses the device id to point to the table with the devices. I have a edit system function that I am trying to get working where I can edit the device id field in a record on the system table to change which device in the devices table I am pointing too. I run the update command and it looks like it should work but the row does not get updated. Does anyone know what I am doing wrong?
Here is my update code routine.
SQLiteDatabase db = dbHelper.getWritableDatabase();
String UpdateDeviceName = txtEditDeviceName.getText().toString();
String UpdateDeviceIP = txtEditDeviceIP.getText().toString();
//get the new device id based off of the three spinner values
String dbQuery = "SELECT * FROM " + dbHelper.Devices_Table + ";";
Cursor c = db.rawQuery(dbQuery, null);
if (c.getCount() > 0)
{
while (c.moveToNext())
{
int iColumnID = c.getColumnIndex(dbHelper.Attribute_Device_ID);
int iColumnDeviceType = c.getColumnIndex(dbHelper.Attribute_Device_Type);
int iColumnDeviceManufacturer = c.getColumnIndex(dbHelper.Attribute_Device_Manufacturer);
int iColumnDeviceModel = c.getColumnIndex(dbHelper.Attribute_Device_Model);
String CheckDeviceType = c.getString(iColumnDeviceType);
if (CheckDeviceType.equals(DeviceType))
{
String CheckDeviceManufacturer = c.getString(iColumnDeviceManufacturer);
if (CheckDeviceManufacturer.equals(DeviceManufacturer))
{
String CheckDeviceModel = c.getString(iColumnDeviceModel);
if (CheckDeviceModel.equals(DeviceModel))
{
DeviceID = c.getString(iColumnID);
}
}
}
}
}
db.close();
c.close();
db = dbHelper.getWritableDatabase();
//with the device ID update the system
dbQuery = "UPDATE " + dbHelper.System_Table + " SET " + dbHelper.Attribute_Device_ID + " = " + DeviceID + ", " +
dbHelper.Attribute_Device_Name + " = '" + UpdateDeviceName + "', " +
dbHelper.Attribute_Device_IP + " = '" +
UpdateDeviceIP + "' WHERE " + dbHelper.Attribute_Device_ID + " = " + OrginalDeviceID + ";";
c = db.rawQuery(dbQuery, null);
Log.d("Database Dump", "Edit Device Query: " + dbQuery);
c.close();
db.close();
You closed the DB after the search:
db.close();
leave out this line, since the DB helper code prefers to keep the DB open until it is no longer used (use dbHelper.close() to close the DB when you are done with it).
The same applies after the update.
First of all any rawQuery statement must not contain the trailing semicolon! See the documentation of SQLiteDatabase.
Also you always must close cursors before closing the database. And you have to close the db when you get a new one for each query. Otherwise the system at some point later on will throw exceptions. While those only will be logged and do not cause a Force Close, you should still care about proper resource management.
Finally you should use the updateWithOnConflict method instead with using CONFLICT_REPLACE as the conflictAlgorithm. This simply ignores any UNIQUE constraints and overwrites conflicting rows. So be careful. If you do not want to overwrite existing rows you have to make sure that a constarint violation isn't causing your problem.
I found the answer. FIrst off I want to thank Henry and Wolfram Rittmeyer. You guys where very helpful. :)
For whatever reason the android SQLite does not like to use the update statement in raw sql query form. In researching what Wolfram Rittmeyer said about updateWithConflict I found the update method in the SQLiteOpenHelper object which my dbHelper extends. When I switched to that method I was able to update the database. My where conditions have been expanded on to include the device name as well in the event that the system has more then one device make and model of the same type and only one has to change.
For reference the working code to update the database is the following. I'm only posting the changed portion of the code. Everything in the if (c.getCount() > 0) block and above is unchanged.
c.close();
dbHelper.close();
db = dbHelper.getWritableDatabase();
//with the device ID update the system
ContentValues values = new ContentValues();
values.put(dbHelper.Attribute_Device_ID, DeviceID);
values.put(dbHelper.Attribute_Device_Name, UpdateDeviceName);
values.put(dbHelper.Attribute_Device_IP, UpdateDeviceIP);
String Where = dbHelper.Attribute_Device_ID + " = " + OrginalDeviceID + " AND " + dbHelper.Attribute_Device_Name + " = '" + OrginalDeviceName + "'";
db.update(dbHelper.System_Table, values, Where, null);
c.close();
dbHelper.close();
finish(); //this exits the activity and goes back to the calling activity

Categories

Resources