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));
Related
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;
I wrote a rssFeedReader Application and use directly sqliteSyntax to modify database.
this is my code:
database.execSQL database= openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
database.execSQL("Create TABLE IF NOT EXISTS Press (press_name
VARCHAR, press_url VARCHAR");
database.execSQL("INSERT INTO Press VALUES ('Tasnim',
'http://www.tasnimnews.com/english/rss/feed/?d=2&c=1&m=6&alt=Recent%20News');");
database.execSQL("UPDATE Press press_name ='Tasnim',
press_url ='http://www.tasnimnews.com/english/rss/feed/?
d=2&c=1&m=6&alt=Recent%20News');");
Cursor cursor = database.rawQuery("SELECT * FROM MyTable", null);
database.close();
and now my question is how can I migrate to SQLiteOpenHelper and ConentValues method to modify database.
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
FeedEntry.COLUMN_NAME_NULLABLE,
values);
You can find it here http://developer.android.com/training/basics/data-storage/databases.html
I am using sqlite
i want to print the query executed in db to insert
here is my code
// for SAving Ocean/Air sales
public int saveOrder(Order odr) throws SQLException {
SQLiteDatabase db = con.getWritableDatabase();
int ordrId = 0;
ContentValues values = new ContentValues();
values.put("cr_usr", odr.getCrUsr());
values.put("cr_ts", odr.getCrTs().toString());
values.put("eat_mst_cust_id", odr.getEatMstCustId());
values.put("ordr_dt", odr.getOrdrDt().toString());
String selectQuery = "SELECT last_insert_rowid()";
try {
// Inserting Row
db.insertOrThrow("eat_ordr", null, values);---getting error here for constraint failed
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
ordrId = cursor.getInt(0);
db.close();
} finally {
db.close();
}
return ordrId;
}
I am not getting any error but row is failed to insert bcz it returns 0 for idvalue
so i want to see executed query how to get that query?
here is my table structure
CREATE TABLE "eat_ordr" ("eat_ordr_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"eat_mst_cust_id" VARCHAR NOT NULL REFERENCES "eat_mst_cust"("eat_mst_cust_id"),
"ordr_no" VARCHAR NOT NULL UNIQUE ,
"ordr_dt" DATETIME NOT NULL ,
"ordr_stat" VARCHAR NOT NULL ,
"last_sync_ts" DATETIME,
"cr_ts" DATETIME DEFAULT CURRENT_TIMESTAMP, "md_ts" DATETIME, "cr_usr" VARCHAR, "md_usr" VARCHAR)
The insertOrThrow documentation says:
Returns
the row ID of the newly inserted row
So this can be done much easier:
ordrId = db.insertOrThrow("eat_ordr", null, values);
I have a little Problem with an insert-Statement in my Android-App.
Here is the code:
public void addNote(Note noteItem, int modulNummer){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NOTE, noteItem.getNote());
cv.put(COLUMN_NOTEBESCHREIBUNG, noteItem.getBeschreibung());
cv.put(COLUMN_MODULID_FK, modulNummer);
db.insert(NOTETABLE, null, cv);
}
Now my problem. The first column in my table is an auto increment pk. And so i want to skip the first column and i want to begin the insert in the second column. How can i skip this first column?
Update
I've already deleted the .put for the first column. "COLUMN_NOTE" is my second column.
My table-structure looks like this:
id INTEGER AUTO INCREMENT
note double
beschreibung TEXT
modul_id INTEGER
UPDATE 2
I don't know why, but now it works. Thx for your help guys.
If you have a table like the following one:
private final String TAB_GROUP_ADD = "CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL);";
And you use the following insert command:
ContentValues values = new ContentValues();
values.put(K_TITLE, title);
values.put(K_DESCRIPTION, description);
db.insert(TAB_GROUP, null, values);
Everything should go fine. The primary key field "id" will no be filled in by Java and the SQLite Database will do it for you.
I want to enter name and phone number from two edit text.i use two buttons to save and show it in emulator using list view.After entering name and when i click save button how to check whether i have already entered the same name. i am new to android explanation will be really helpful.
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbname+"("+Key_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Key_name+" TEXT,"+Key_mobile+" TEXT)");
}
public void n(String aa, String bb) {
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(Key_name, aa);
cv.put(Key_mobile, bb);
db.insert(tbname, Key_name, cv);
db.close();
}
public Cursor cr()
{
SQLiteDatabase db=getReadableDatabase();
String [] colms=new String[]{Key_id+" as _id",Key_name,Key_mobile};
Cursor cur=db.query(tbname, colms, null, null, null, null, null);
cur.moveToFirst();
return cur;
}
I would start with changing your table definition by adding the NOT NULL and UNIQUE constraints.
db.execSQL("CREATE TABLE "+tbname+"("+Key_id+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Key_name+" TEXT NOT NULL UNIQUE,"+Key_mobile+" TEXT)");
Then you have a choice of methods to use for your insert. You can use:
insertOrThrow will return the id of your new record, or -1 on an error (and a constraint failure of not having a unique name would be an error).
insertWithOnConflict will return the id of the new record OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any error.
Personally, I would use insertWithOnConflict with the CONFLICT_IGNORE flag set. That way you can get the row id back for the duplicate record (as well as not letting the duplicate get entered).
Put UNIQUE in your table field definition an then use insertOrThrow. If you insert the same, insertOrThrow will cause an exception, you can intercept it.