Reputation: 18875
I'm new to app development using SQLite and Sugar ORM on Android, and have tried to read through the Sugar ORM documentation, but didn't find anything for how to update a saved object in SQLite. Can I still save the object after changing its properties? something like:
Customer myCustomer = (Customer.find(Customer.class, "id = ?", id)).get(0);
myCustomer.setName("new name");
myCustomer.setAddress("new Address");
myCustomer.save(); // is this okay for updating the object?
the save() method won't create another new object while leaving the old entry untouched, right?
Upvotes: 5
Views: 8549
Reputation: 3128
Save and Object methods are completely different and both are really useful. If you have an object and you say:
Object.save();
That will override all of the other fields as well for example:
column1 column2
1 1
if in your object you have only set column1 corresponding field a number like 2 you will get:
Object.save();
column1 column2
2 NULL
Object.update();
column1 column2
2 1
You don't need to use .setId() explicitly to get update working it looks for a unique item if it's found it will update that,if not it will create a new row.By default an auto increment ID column is added to each of your tables and used as unique ids for update.If you need your own fields to be unique use:
@Unique
String MyID
or for multiple of the same thing you can use:
@MultiUnique("MyFirstID,MySecondID")
public class MyClass extends SugarRecord {...
which both are name of your fields in the table.
Upvotes: 0
Reputation: 3322
Updating a saved object is pretty straightforward.
Retrieve the object;
Object object= Object.findById(Object.class, ID);
Set the attributes you need to;
object.setAttr("new value");
Then finally call save;
object.save();
Alternatively, as someone mentioned above one can choose to use update() which works slightly differently and would ideally be used when changing several attributes;
First create the object and set the necessary attributes;
Object object= new Object();
object.setAttr("some data");
Then set an ID for the Object that ideally already exists in the database in order to target that item for replacement;
object.setID(ID);
And finally;
object.update();
Upvotes: 0
Reputation: 9373
Your code should update the row without issue.
From the docs - Update Entity:
Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; // modify the values
book.edition = "3rd edition";
book.save(); // updates the previous entry with new values.
Upvotes: 5
Reputation: 627
It will update your entity. The Sugar ORM overwriting your existing e.g Name and updated it with "new name" after the save() method call.
Upvotes: 3