I want to change a single column inside a row. I'm trying to update the value inside "remindOnDate" field to "reminder" in the "tasks" table.
I tried a few things but they all work only when remindOnDate is null. Once it has a value stored in it, update won't work on it. I don't know why. What am I doing wrong? If the statement is wrong then it shouldn't work even when remindOnDate is null.
I tried this:
ContentValues editTask = new ContentValues();
editTask.put("remindOnDate", reminder);
database.update("tasks", editTask, "_id = ?", new String[]{id+""});
I also tried the following instead of the last line:
database.update("tasks", editTask, "_id = " + id, null);
Here is another thing I tried:
String createQuery = "UPDATE tasks SET remindOnDate = '" + reminder + "' WHERE _id = " + id + ";";
database.execSQL(createQuery);
Related
I am going nuts over here. I have been trying to update one column in one row inside of my SQLite Database but its just not happening regardless of what I try.The value is never updated and there are no exceptions in my log.
The below code might summarise my problem best.
the updateLatestMessage() function is part of a Database Controller Class.
public void updateLatestMessage(int messageID, int chatID){
Log.d("DB", "message ID =" + messageID); //example output = 125
Log.d("DB", "chat ID =" + chatID); //example output = 2
SQLiteDatabase db = this.getWritableDatabase();
try {
ContentValues cv = new ContentValues();
cv.put("latest_message_id", messageID);
db.update("chat", cv, "chat_id = ?" + chatID, null);
db.close();
//db.update(tableChat.TABLE_NAME, cv, tableChat.getChatId() + " = ?", new String[]{String.valueOf(chatID)}); // tried this before didn't work either
}
catch(Exception e) {
Log.d("DB", "Error: "+e.toString());
}
}
currently latest message has the ID of 5
myDB.chat.updateLatestMessage((int) messageID, globalChatID);//calling the above DB update code
after running this code the latest message still has the id of 5 instead of 125
I am expecting the messageID to be updated inside of the the latest_message_id column inside my already existing chat row.
If the name of the table is "chat", the name of the column in the WHERE clause is "chat_id" and the argument of WHERE clause is chatID, then the recommended way for the update is this:
int result = db.update("chat", cv, "chat_id = ?", new String[]{String.ValueOf(chatID)});
Check the value of result after the statement.
If its value is greater than 0 then the update was successful.
I have an xml file as shown in the picture. I want two things, first, I want to insert pre-defined values in my sqlite database on onCreate method using an arraylist (or any method). Then secondly, I want to use those values from the arraylist, now in my database, to populate the two spinners(Producer and Product).
I have a database file that handles the db connections and methods and this is what I have done so far. This code is inside my onCreate method
db.execSQL("CREATE TABLE " + TABLE_PRODUCT + "("
+ PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + PRODUCT_NAME + " TEXT,"
+ PRODUCER_FK + " INTEGER" + " FOREIGN KEY(PRODUCER_FK) REFERENCES TABLE_PRODUCER(PRODUCER_ID))");
ContentValues contentv=new ContentValues();
contentv.put("name", "Soya Seed");
getWritableDatabase().insert("TABLE_PRODUCT", null, contentv);
db.execSQL("CREATE TABLE " + TABLE_PRODUCER + "("
+ PRODUCER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + PRODUCER_NAME + " TEXT,"
+ PRODUCER_ADDRESS + " TEXT,"
+ PRODUCER_PHONE + " TEXT UNIQUE," + PRODUCER_EMAIL + " TEXT,"
+ CONTACT_PERSON + " TEXT" + ")");
ContentValues cv=new ContentValues();
cv.put("name", "ZamSEED");
cv.put("address", "Luanda");
cv.put("phone", "+244977654321");
cv.put("email", "demo#zamseed.com");
cv.put("contact_name", "Mr. Tembo");
getWritableDatabase().insert("TABLE_PRODUCER", null, cv);
Then I have an inventory file that reads from the database to get values from the product and producers tables to populate the spinners.
My challenge is how can I tell if my db.execSQL is actually successful?
And how would I use an arraylist to insert values in the database?
NOTE: the app runs fine when I ran it but I am not sure if the tables are created and values inserted. Am a newbie to Android programming, thanks.
After some time of research into this, I found this article here that led me to see the actual tables of my db.execSQL command and the data contained. In Ubuntu:
cd /path/to/my/sdk/platform-tools
./adb shell
run-as <app package name>
cd /data/data/<app package name>/databases
ls
chmod 666 <database file name>
sqlite3 <database file name>
> (semi-colon terminated commands can be run here to query the data)
> .exit
(copy full database path)
exit
Then use sqlite3 commands to work on database > (semi-colon terminated commands can be run here to query the data)
DatabaseHelper.java
public ArrayList<String>getProductList(){
ArrayList<String>products = new ArrayList<String>();
SQLiteDatabase qDB = getReadableDatabase();
String columns[]=new String[]{PRODUCT_NAME};
Cursor cursor = qDB.query(TABLE_PRODUCT,columns,null,null,null,null,null);
while (cursor.moveToNext()){
String produectName = cursor.getString(1);
products.add(productName);
Log.e("e",products);
}
return products;
}
SomeActivity.java
spinnerProducts = (Spinner) findViewById(R.id.spinnerProducts);
ArrayList<String>productsList = new DatabaseHelper(context).getProductsList();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,productsList);
spinnerProducts.setAdapter(arrayAdapter);
...
//same logic for Producers list
My challenge is how can I tell if my db.execSQL is actually successful?
It was successful if it did not throw an exception.
However calling getWritableDatabase() in onCreate() is an error since that results in recursion: getWritableDatabase() triggers a call to onCreate() in the first place. You should use the SQLiteDatabase passed to you as a param instead.
If you did not see an exception about the recursive call then you already had a database file with the correct version. You can uninstall your app to clean up its data and then install and run it again to make onCreate() run again.
And how would I use an arraylist to insert values in the database?
Use a loop to iterate the list and insert values one by one.
I have two tables; a 'parent' and a 'child' table. (not SQLite defitinions, just something i call them)
Everytime a child-object is created, it is assigned the value 0 in one of its columns.
When a new parent-object is created, every unassigned child-object, has to update the value mentioned before, to the parent-object's ID. My code looks like this:
public long createWorkout(String workoutName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, workoutName);
//Creates a new parent-object (a workout - the childs are exercises)
//the generated ID is returned as a long (workout_pk_id)
long workout_pk_id = db.insert(TABLE_WORKOUT, null, values);
//Selects all objects in the child-table with KEY_WORKOUT_ID = 0 (the column mentioned before)
String selectQuery = "SELECT * FROM " + TABLE_EXERCISE + " WHERE " + KEY_WORKOUT_ID + " == " + 0;
Cursor cursor = db.rawQuery(selectQuery, null);
//Takes each found object with value 0, and updates the value to the returned parent-ID from before.
if (cursor.moveToFirst()) {
do {
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
db.execSQL(k);
} while (cursor.moveToNext());
}
return workout_pk_id;
}
But for some reason this doesn't work. The ID the childs/exercises remains 0. Can you help me?
I don't know if the error is somewhere in the setup of my tables, in that case i could provide some more information.
Thanks in advance. /Jeppe
EDIT: This is used in android, and I have debugged and verified that the workout_pk_id is returned, 45 objects are found in the selectQuery and yet it doesn't work. I also tried ContentValues to update the values, didn't work.
Edited the " == " to " = ", but the value is still not updated.
This is from eclipse - I've created a workout called "test", with the ID 160.
The exercise "test1" has the ID 430 (unique) but the workout_id is still 0.
It's been awhile since I did any Android stuff but I believe the "==" operator is incorrect:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " == " + workout_pk_id;
The operator you're using is a comparative operator, "=" is the assignment operator.
I also believe there is a better way to do what you are trying to do, currently refreshing my memory on Android so I'll get back to you. In the meantime tell me if replacing the operator works
Yeah so another way you can do this is by using subqueries. So it would look something like:
UPDATE TABLE_EXCERCISE SET KEY_WORKOUT_ID = WORKOUT_PK_ID WHERE KEY_WORKOUT_ID =
(
*subquery here to select parent object ids*
)
Here's a link to help:
http://www.tutorialspoint.com/sqlite/sqlite_sub_queries.htm
Let me know how this works for you.
I think you have to look to your update query.
It has to be:
String k = "UPDATE " + TABLE_EXERCISE + " SET " + KEY_WORKOUT_ID + " = " + workout_pk_id;
Look at the "=" between KEY_WORKOUT_ID and workout_pk_id.
I try to change status for one of attendees for specific Event.
The following example demonstrates how to update event title:
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.TITLE, "Some new title");
String selectedEventId = "123";
String[] selArgs = new String[]{selectedEventId};
int updated = cr.update(
Events.CONTENT_URI,
values,
Events._ID + " =? ",
selArgs);
But I need update information for specific attendee. SO I need somehow to change Where part of query.
Right now I have Events._ID + " =? that mean where eventID=123
and this line will set new type:
values.put(Attendees.ATTENDEE_STATUS, "1"); // 1 - ACCEPTED
How to write where statement to update specific attendee with email (lets say) aaa.bbb#gmail.com
[EDIT]
I tried:
String selectedEventId = eventStructure.getString("mEventId");
String selectedEmail = "aaa.bbb#gmail.com";
String[] selArgs = new String[]{selectedEventId, selectedEmail};
int updated =
cr.
update(
Events.CONTENT_URI,
values,
Events._ID + " =? AND " + Attendees.ATTENDEE_EMAIL + " =?",
selArgs);
but get Exception:
android.database.sqlite.SQLiteException: no such column: attendeeEmail (code 1): ,
while compiling: SELECT * FROM Events WHERE _id =? AND attendeeEmail =?
Thank you for help,
Since you want to update attendee information you need to change Uri from Events.CONTENT_URI to Attendees.CONTENT_URI.
In addition instead Events._ID write Attendees.CONTENT_URI.
So the snippets of code should be something like:
values.put(Attendees.ATTENDEE_STATUS, "1");
String selectedEventId = eventStructure.getString("mEventId");
String selectedEmail = "aaa.bbb#gmail.com";
String[] selArgs = new String[]{selectedEventId, selectedEmail};
int updated = cr.update(
Attendees.CONTENT_URI,
values,
Attendees.EVENT_ID + " =? AND " + Attendees.ATTENDEE_EMAIL + " =?",
selArgs);
Log.d(TAG, "sendAcceptEvent :: updated row count: "+ updated);
Didn't test it, but should work
I currently I have my database set up like the following:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER, " + KEY_PIN
+ " INTEGER);");
And I am trying to write a method to get the pin code from the column for a specific locker number. Any ideas? I am very new I would like think I would need to use the query function and a cursor. I just one to get the integer value and store it into an int variable so I can compare the pin codes from what the user types in to the one in the database.
Queries to database returns in a Cursor object. You should use the db.query() method to get a row(s). Pass the table name, an array of columns you want to get (or null if you want all of them), pass a selection string that should be like "id = ?" or "key > ?", etc, then pass a String array containing the value for those ? inside the previous string,
and finally pass null for having, groupBy and orderBy unless you want to use them.
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ROWID }, "id = ?", new String[] { Integer.toString(id) }, null, null, null);
After you get the Cursor, do cursor.moveToFirst() or cursor.moveToPosition(0) (can't remember the exact method, but the point is to move the cursor to the first retrieved row)
then you're going to iterate through the cursor with
while(cursor.moveToNext()) {
int keyRowIdColumnIndex = cursor.getColumnIndex(KEY_ROWID);
int yourValue = cursor.getInt(keyRowIdColumnIndex);
int keyLockNumberColumnIndex = cursor.getColumnIndex(KEY_LOCKNUMBER);
int pin = cursor.getInt(keyLockNumberColumnIndex);
}
This is a pretty straight forward task and there is a bunch of tutorials, examples, similar questions on SO:
How to perform an SQLite query within an Android application?
In general - you need to query the database passing your search arguments. See the documentation.
It will return you a Cursor with the matching results, which you can then iterate over and manipulate as you wish.
Fyi - storing password in a database table is a bad idea. On Android databases can be accessed and easily read. You either need to encrypt your data or think of another way to store it if it's important.
//Try This code
public String getLabeId(String LockNo)
{
ArrayList<String> Key_Pin_array = new ArrayList<String>();
Cursor cur = db.rawQuery("SELECT * FROM DATABASE_TABLE where KEY_LOCKERNUMBER = '" + LockNo + "'", null);
try {
while (cur.moveToNext())
{
System.out.println("Key_Pin" + cur.getString(3));
Key_Pin_array.add(cur.getString(3));
}
}
catch (Exception e)
{
System.out.println("error in getLabelID in DB() :" + e);
}
finally
{
cur.close();
}
return id;
}