Search code examples
androidsqliteactiveandroid

Difference between execute() and executeSIngle() methods in ActiveAndroid library?


I am new to ActiveAndroid and I am stuck with Querying the database. Please help me out with the difference between execute() and executeSingle() methods in ActiveAndroid Library?

Both these methods are used to query the database but I am not getting when to use the former and when to use the later?


Solution

  • The difference between execute() and executeSingle() is somewhat explained in the documentation:

    If we only want to get items from a certain category, we pass in a string for our where class argument. The method would look like this:

    public static Item getRandom(Category category) {
        return new Select()
            .from(Item.class)
            .where("Category = ?", category.getId())
            .orderBy("RANDOM()")
            .executeSingle();
    }
    

    And here's how we get all the items in a category, sorted by name.

    public static List<Item> getAll(Category category) {
        return new Select()
            .from(Item.class)
            .where("Category = ?", category.getId())
            .orderBy("Name ASC")
            .execute();
    }
    

    As you see, execute() returns a list, while executeSingle() returns a single object.

    In the examples above, the first would return a random object matching the query, while the second would return all the objects in an ascending order.

    In other words, use executeSingle() to return the first result, and use execute() to return a list with all objects.