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

Server Models Example

Adrián Rivero edited this page Mar 16, 2017 · 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",
    load = {
        @ServerRequest(
            name = "info",
            action = "/user/{query}"
        ),
        @ServerRequest(
            name = "friends",
            action = "/friends/{query}"
        )
    } 
    post="/user"
)
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 //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 add also the annotation @UseModel, with this we indicate what action to use to inject the Model, since our class can be inferred in blank @UseModel, or from the server @ServerModel.

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 with the action equals to "info"
    @Model(async=true, query="{user_id}", orderBy="info") 
    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 with the action equals to "friends"
    @Model(async=true, query="{user_id}", orderBy="friends") 
    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.