Skip to content

Saving to the database

Kevin Brey edited this page Oct 7, 2015 · 11 revisions

Now that you have your database model setup, let’s save some records to the database.

Inserting and updating records

To save a new record, just create a new instance of an activeandroid.Model class, assign values to its fields, and call the .save() method. That’s all. The save method works for both inserting and updating records.

Here’s an example

Category restaurants = new Category(); = "Restaurants";;

Now let’s create an Item record, and assign a category to it

Item item = new Item();
item.category = restaurants; = "Outback Steakhouse";;

Let’s add some more items.

item = new Item();
item.category = restaurants; = "Red Robin";;
item = new Item();
item.category = restaurants; = "Olive Garden";;

Bulk insert

To insert multiple records at the same time you can use transactions. Calls wrapped in transactions can be speed up by a factor of around 100. Here's an example:

try {
        for (int i = 0; i < 100; i++) {
            Item item = new Item();
   = "Example " + i;
finally {

This takes about 40 ms wrapped in a transaction, and 4 seconds when it's not.

Deleting records

What about deleting a record? Well, to delete a single record just call the delete() method. In the following example we’ll load an Item object by Id and delete it.

Item item = Item.load(Item.class, 1);

Or you can delete it statically

Item.delete(Item.class, 1);

You can also use the query builder syntax

new Delete().from(Item.class).where("Id = ?", 1).execute();

Next, let's look at Querying the database.