ActiveAndroid Update() query
Asked Answered
E

3

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.

Earleenearlene answered 10/4, 2014 at 19:30 Comment(3)
Can you add your stack trace?Rushy
@Earleenearlene why should you use .set("Enable = 0") .. P.S: I am new to Active Android ..Prelacy
@Ajay because it's more performant than loading + saving. Specially if you have many items to update.Earleenearlene
E
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.

Earleenearlene answered 23/10, 2015 at 18:18 Comment(2)
is it valid to be .set("Enabled = ?", 0) ?Isreal
@Hamzeh yes, that's valid tooEarleenearlene
C
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();
Crepitate answered 3/7, 2014 at 17:16 Comment(2)
That is highly inefficient, specially if you need to update lots of items.Earleenearlene
@jlhonora: if you wana save lots of items, let use ActiveAndroid transaction from here. By the way, could you give a better solution?Crepitate
R
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();
}
Reade answered 29/7, 2015 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.