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

Server Models Example

Adrián Rivero edited this page Feb 18, 2016 · 10 revisions

In this Example, let's use @ServerModel to save an User Model to our server, and download a list of friends. Let's say we implemented in our server at "http://app.user-friends.com" an API to save information about an user, and download that information at any moment, or a list of friends of this user. Our methods will be a REST JSON based API:

API

Let's declare our user model:

@ServerModel(
    baseUrl="http://app.user-friends.com",
    get={"/user/%s; query", "/friends/%s; query"}
    post="/user"
)
@UseModel
@EBean
public class User extends Model {
    @Column int id;  //Id of the user in the server

    @Column String name;
    @Column String email;
    @Column int age;
}

Let's create the user and send it to the back-end when the user clicks a button with id "btnSaveUser":

@EActivity(R.layout.activity_save_user)
public class SaveUserActivity extends Activity {
    @Model(useModel=UseModel.class) //This will instantiate an empty user
    @PutOnAction(R.id.btnSaveUser)
    User_ user;

    @AfterInject
    void setUser() {
        user.setName("Alice");
        user.setEmail("alice@example.com");
        user.setAge(22);
    }
}

See that we pass to our @Model annotation a parameter "useModel", with this we indicate what action to use to inject the Model, since our class can be inferred in blank useModel=UseModel.class, or from the server userModel=ServerModel.class. See also "useModel" parameter

Let's say that we have an activity that shows the information of an user, when we open the activity we pass to it an extra argument, the user_id, so we can load the user information from the server easily:

@EActivity(R.layout.activity_user_profile)
public class UserProfileActivity extends Activity {
    @Extra
    int user_id;

    //OrderBy will select the API url at index 0 ("/user/%s; query")
    @Model(async=true, query="%s; user_id", orderBy="0") 
    User_ user;
}

Important! when loading a model from a server, you should set "async" parameter to true, in order to avoid a network operation in the Main Thread of an application

And to load a list of all the friends of the user that was passed also as an extra parameter to the activity

@EActivity(R.layout.activity_user_profile)
public class UserProfileActivity extends Activity {
    @Extra
    int user_id;

    //OrderBy will select the API url at index 1 ("/friends/%s; query")
    @Model(async=true, query="%s; user_id", orderBy="1") 
    List<User_> friends;
}

See that we use constantly the [Formatted Syntax](Formatted Syntax) for the query parameter, in order to use the field "user_id" inside the query.

Clone this wiki locally