I have got a database table with a column "id INTEGER PRIMARY KEY AUTOINCREMENT". When I try to update an existing row of this table with the primary key, the app exits saying "Unfortunately is stopped."
public int updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, user.getUser_firstName()); // user first name
values.put(KEY_LASTNAME, user.getUser_lastName()); // user first name
values.put(KEY_USERNAME, user.getUsername());
values.put(KEY_PASSWORD, user.getPassword());
values.put(KEY_USERLEVEL, user.getUser_level());
values.put(KEY_DESIGNATION, user.getDesignation());
values.put(KEY_MOBILENO, user.getMobile_no());
values.put(KEY_EMAIL, user.getEmail());
values.put(KEY_NIC, user.getNIC());
values.put(KEY_GENDER, user.getGender());
values.put(KEY_DOB, user.getDOB());
values.put(KEY_AVAILABILITY, user.getAvailability());
db.close();
// updating row
return db.update(TABLE_USERS, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser_id()) });
Logcat :
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projectmanagementsys.com.sasith.project_management/com.projectmanagementsys.com.sasith.project_management.AddUser}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.projectmanagementsys.com.sasith.project_management/databases/ProjectManagement
There is no error in the whole thing and the code works well when I comment the update query. Can someone give a solution please ?
Thank you.
You have the line db.close() followed by db.update() and your error states that you are attempting to open an already-closed object. You haven't closed the db after you've added the data, you've closed it before. You'll need to update the row, close the database, then return your value.
// updating row
int result = db.update(TABLE_USERS, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser_id()) });
db.close();
return result;
Related
This is my code for table creation
database.execSQL("CREATE TABLE IF NOT EXISTS RNOTIFICATIONS(Position VARCHAR PRIMARY KEY NOT NULL,message VARCHAR, title VARCHAR, iconof VARCHAR);");
and insert data function is
public void insert_new_item(String n_message, String n_title,String n_icon) {
SQLiteDatabase database = this.getWritableDatabase();
String rows= String.valueOf((int)DatabaseUtils.queryNumEntries(database, "RNOTIFICATIONS"));
ContentValues values = new ContentValues();
values.put("Position",rows+1);
values.put("message", n_message);
values.put("title", n_title);
values.put("iconof",n_icon);
database.insert("RNOTIFICATIONS", null, values);
database.close();
}
INPUT: insert_new_item(hi,Instagram, 2)
OUTPUT: [{message=1, iconof=Instagram, title=hi}]
EXPECTED OUTPUT: [{Position=1,message=hi,title=Instagram, iconof=2}]
Insert command is inserting values in wrong columns. can anyone help. please
i have tried removing PRIMARY KEY and NOT NULL But still it does the error.
The problem was with wrong cursor position. It was (0)
map.put("message", cursor.getString(0));
It should have been (1)
map.put("message", cursor.getString(1));
Hi in my database i have a string like "computer's" , i am fetching it from database and displaying listview, when i click on the list item it should store to one of my database table. I am doing it as below but it is getting crashed
public void updateFav(String key, int value) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
C_FAV=C_FAV.replaceAll("'","''");
values.put(C_FAV, value);
db.update(tableName, values, C_KEY + "='" + key.trim() + "'", null);
db.close();
}
Below is my trace
12-12 17:55:49.291: E/AndroidRuntime(18184): android.database.sqlite.SQLiteException: near "s":
syntax error (code 1): , while compiling: UPDATE fav SET favorite=? WHERE key='computer's'
You're escaping the apostrophes in C_FAV which seems to be a column name but not in key.
Consider using ? placeholder and bind arguments instead, e.g.
db.update(tableName, values, C_KEY + "=?", new String[] { key.trim() });
I have a table called app_catagory. The problem is, when I try to insert a row into the table, I got this exception:
FATAL EXCEPTION : main java.lang.NullPointerException
The LogCat shows this line as the offending code:
db.insert(DATABASE_TABLE2, null, initialValues);
How can I fix it?
Code
static final String DATABASE_APP_CAT= "create table app_catagory(cat_id interprimary key autoincrement, " +
"name text not null," +
"date_created date , " +
"img_name text);";
//Insert into catagory table
public static void insertContact_app_cat()
{
String[] name={"DOCTOR","PHARMACY","PATHLAB","BLOODBANK"};
for(int i=1;i<=4;i++){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CAT_NAME, name[i]);
initialValues1.put(KEY_CAT_DATE, "05-05-2014");
initialValues2.put(KEY_CAT_IMG,"null");
db.insert(DATABASE_TABLE2, null, initialValues);
}
}
I don't see where you are getting the db when I do an insert I call this piece of code before doing my ContentValues add stuff.
SQLiteDatabase db = this.getWritableDatabase();
Then after the insert I would close the database.
db.close();
I have created a table like Players in onCreate() method which is in MySQLiteHelper.java:
String CREATE_PLAYERS_TABLE = "CREATE TABLE Players
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, password TEXT, score INTEGER)";
db.execSQL(CREATE_PLAYERS_TABLE);
And I have an update method in the same class like:
public int PlayerUpdate(Player PL) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("name", PL.getName());
values.put("password", PL.getPassword());
values.put("score", PL.getScore());
// 3. updating row
int i = db.update(TABLE_Players, // table
values, // column/value
KEY_ID + " = ?", // selections
new String[] { String.valueOf(PL.getId()) }); // selection args
// 4. close
db.close();
return i;
}
and when I call functions to change score variable as:
public void scoreUp() {
helper.PlayerUpdate(new Player(player_name,player_password,player_score+5));
}
public void scoreDown() {
helper.PlayerUpdate(new Player(player_name,player_password,player_score-5));
}
I am getting a logcat error like:
Failed to read row 0, column 1 from a CursorWindow which has 1 rows, 1 columns.
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.
Make sure the Cursor is initialized correctly before accessing data from it.
Thanks.
SOLVED:
There has been another query that causes this specific exception and I found out.
The exception comes from accessing cursor columns and the code you posted doesn't show that.
However, column indexing starts from 0, so to access the first column value as string, use getString(0) instead of getString(1).
I have a table with 2 columns, a numeric id and unique text. Created like this:
String CREATE_MY_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FOO + " TEXT UNIQUE"
+ ")";
db.execSQL(CREATE_MY_TABLE);
I want that when I insert KEY_FOO value and it's already in the db, nothing happens. But what I get is that the id is always incremented. No new row is inserted, that's good, but the id is autoincremented.
What I'm doing to insert is as follows:
db.insertWithOnConflict(TABLE_TEST , null, values, SQLiteDatabase.CONFLICT_NONE);
I tried CONFLICT_IGNORE, CONFLICT_ABORT, CONFLICT_ROLLBACK, all the same.
The reason I need this is because other table has a foreign key on this id, thus if the id is changed, the other table points nowhere.
How I just say to let the existing entry untouched?
Try this way. In your dbhelper class write the method like following to insert.
public int insertData(String desc) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
db.beginTransaction();
cv.put(KEY_FOO, desc);
db.insertOrThrow(TABLE_TEST, null, cv);
db.setTransactionSuccessful();
} catch (Exception ex) {
return 1;
} finally {
db.endTransaction();
db.close();
}
return 0;
}
Then from your actvity you call this method with the parameter value of KEY_FOO. This method will return 1 if the exception is occurs (If you try insert a unique value) and it will return 0 if the transaction is successfull.
I hope this way will help you. Let me know if any problem.