11

I'm trying to make a bulk update to a column using ActiveAndroid. Here's my code:

new Update(SomeModel.class).set("Enabled = 0").execute();

But I'm getting a StackOverflowError. (Edit: My bad, the error was somewhere else). Does anyone know how to execute an Update() query? It doesn't say anything in ActiveAndroid's wiki.

Edit:

This syntax is correct:

new Update(SomeModel.class)
  .set("Enabled = 0")
  .where("Account = ?", account.getId())
  .execute();

You can skip the where if not needed.

jlhonora
  • 10,179
  • 10
  • 46
  • 70

3 Answers3

20

This syntax is correct:

new Update(SomeModel.class)
  .set("Enabled = 0")
  .where("Account = ?", account.getId())
  .execute();

You can skip the where if not needed.

jlhonora
  • 10,179
  • 10
  • 46
  • 70
12

Base on AndroidActive's github: "The save method works for both inserting and updating records."
So, if you want to update an item, first, you must read it from database, then modify it, and finally save it again.
For ex:

Foo for = Foo.load(Foo.class, 1);//1 is the id
foo.bar = "new value";
foo.save();
Justin
  • 4,400
  • 2
  • 32
  • 36
  • 1
    That is highly inefficient, specially if you need to update lots of items. – jlhonora Jul 29 '15 at 11:56
  • @jlhonora: if you wana save lots of items, let use `ActiveAndroid transaction` [from here](https://github.com/pardom/ActiveAndroid/wiki/Saving-to-the-database#bulk-insert). By the way, could you give a better solution? – Justin Jul 30 '15 at 01:21
1

You can also use something like this:

SomeModel model = selectField("fieldName", "fieldValue");
model.field = newValue;
model.save();

where selectField()method is:

public static SomeModel selectField(String fieldName, String fieldValue) {
    return new Select().from(SomeModel.class)
            .where(fieldName + " = ?", fieldValue).executeSingle();
}
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78