Skip to content
This repository has been archived by the owner on May 4, 2022. It is now read-only.

Locally Stored Models Example

Adrián Rivero edited this page May 7, 2017 · 8 revisions

In this Example, let's use @LocalDBModel to create an User Model, store it in SQLite and reload it.

This is the User Model

@LocalDBModel
public class User extends Model {
    @Column String name;
    @Column String email;
    @Column int age;
}

Now we can inject this model in any Enhanced View, here is an example in an Enhanced Activity.

@EActivity(R.layout.activity_main)
public class EnhancedActivity extends Activity {

    @Model
    User_ user;

    @AfterInject
    void setUser() {
        if (!user.exists()) { //This means the model was not found in the Local DB. Generate it inline
            user.setName("Alice");
            user.setEmail("alice@example.com");
            user.setAge(22);
            user.save();
        } else {
           //The model already exists in the Local DB, do something with it.
        }
    } 
}

Let's query

By default, when an User is injected from the Local DB, the first founded field is used. This is very useful if you want to store only an instance of the current user using the application... But let's say you have in your DB a list of Users and you want to query only one of them satisfying a specific condition, let's do it like

@EActivity(R.layout.activity_main)
public class ImageActivity extends Activity {

    @Model(query="age > 24");
    User_ user;

}

If you want to get a set of users, not only one, you can do it simply using a List:

@EActivity(R.layout.activity_main)
public class ImageActivity extends Activity {

    @Model(query="age > 24");
    List<User_> users;

}

you can order also your elements:

@EActivity(R.layout.activity_main)
public class ImageActivity extends Activity {

    @Model(query="age > 24", orderBy="name DESC");
    List<User_> users;

}

if you want to create a more complex query, you can make a direct select over the table:

@EActivity(R.layout.activity_main)
public class ImageActivity extends Activity {

    @Model(query="SELECT * FROM users WHERE age BETWEEN 24 AND 29 ORDER BY age");
    List<User_> users;

}

And of course, you can use the Formatted Syntax for the query to access to any function or field.

@EActivity(R.layout.activity_main)
public class ImageActivity extends Activity {

    @Model(query="SELECT * FROM users WHERE age BETWEEN {getMinAge()} AND {getMaxAge()} ORDER BY age");
    List<User_> users;

    public int getMinAge() {
        //Returns the minimum age
    }

    public int getMaxAge() {
        //Returns the maximum age
    }

}