codepath/android-rest-client-template

Name: android-rest-client-template

Owner: CodePath

Description: Template Creating an Android OAuth REST Client

Created: 2013-05-25 20:27:10.0

Updated: 2018-01-18 15:41:43.0

Pushed: 2018-01-08 02:18:31.0

Homepage: https://github.com/codepath/android-rest-client-template

Size: 3120

Language: Java

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

RestClientTemplate Build Status

Overview

RestClientTemplate is a skeleton Android project that makes writing Android apps sourced from OAuth JSON REST APIs as easy as possible. This skeleton project combines the best libraries and structure to enable quick development of rich API clients. The following things are supported out of the box:

The following libraries are used to make this possible:

Usage
1. Configure the REST client

Open src/com.codepath.apps.restclienttemplate/RestClient.java. Configure the REST_API_INSTANCE, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET based on the values needed to connect to your particular API. The REST_URL should be the base URL used for connecting to the API (i.e https://api.twitter.com). The REST_API_INSTANCE should be the class defining the service you wish to connect to. Check out the full list of services you can select (i.e FlickrApi.instance()).

For example if I wanted to connect to Twitter:

estClient.java
ic class RestClient extends OAuthBaseClient {
public static final BaseApi REST_API_INSTANCE = TwitterApi.instance();
public static final String REST_URL = "https://api.twitter.com/1.1";
public static final String REST_CONSUMER_KEY = "57fdgdfh345195e071f9a761d763ca0";
public static final String REST_CONSUMER_SECRET = "d657sdsg34435435";
// ...constructor and endpoints

Next, change the intent_scheme and intent_host in strings.xml to a unique name that is special for this application. This is used for the OAuth authentication flow for launching the app through web pages through an Android intent.

ing name="intent_scheme">oauth</string>
ing name="intent_host">codepathtweets</string>

Next, you want to define the endpoints which you want to retrieve data from or send data to within your client:

estClient.java
ic void getHomeTimeline(int page, AsyncHttpResponseHandler handler) {
ring apiUrl = getApiUrl("statuses/home_timeline.json");
questParams params = new RequestParams();
rams.put("page", String.valueOf(page));
tClient().get(apiUrl, params, handler);

Note we are using getApiUrl to get the full URL from the relative fragment and RequestParams to control the request parameters. You can easily send post requests (or put or delete) using a similar approach:

estClient.java
ic void postTweet(String body, AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("statuses/update.json");
RequestParams params = new RequestParams();
params.put("status", body);
getClient().post(apiUrl, params, handler);

These endpoint methods will automatically execute asynchronous requests signed with the authenticated access token. To use JSON endpoints, simply invoke the method with a JsonHttpResponseHandler handler:

omeActivity.java
Client client = RestApplication.getRestClient();
nt.getHomeTimeline(1, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray json) {
// Response is automatically parsed into a JSONArray
// json.getJSONObject(0).getLong("id");


Based on the JSON response (array or object), you need to declare the expected type inside the OnSuccess signature i.e public void onSuccess(JSONObject json). If the endpoint does not return JSON, then you can use the AsyncHttpResponseHandler:

Client client = RestApplication.getRestClient();
nt.getSomething(new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
    System.out.println(response);
}

Check out Android Async HTTP Docs for more request creation details.

2. Define the Models

In the src/com.codepath.apps.restclienttemplate.models, create the models that represent the key data to be parsed and persisted within your application. For example, if you were connecting to Twitter, you would want a Tweet model as follows:

odels/Tweet.java
age com.codepath.apps.restclienttemplate.models;

rt org.json.JSONException;
rt org.json.JSONObject;

rt com.raizlabs.android.dbflow.structure.BaseModel;
rt com.raizlabs.android.dbflow.annotation.Column;
rt com.raizlabs.android.dbflow.annotation.ForeignKey;
rt com.raizlabs.android.dbflow.annotation.PrimaryKey;
rt com.raizlabs.android.dbflow.annotation.Table;


le(database = MyDatabase.class)
ic class Tweet extends BaseModel {
 Define database columns and associated fields
rimaryKey @Column
ng id;
olumn
ring userId;
olumn
ring userHandle;
olumn
ring timestamp;
olumn
ring body;

Notice here we specify the SQLite table for a resource, the columns for that table, and a constructor for turning the JSON object fetched from the API into this object. For more information on creating a model, check out the DBFlow Wiki.

In addition, we can also add functions into the model to support parsing JSON attributes in order to instantiate the model based on API data. This might look like:

odels/Tweet.java
le(database = MyDatabase.class)
ic class Tweet extends BaseModel {
 ...existing code from above...

 Add a constructor that creates an object from the JSON response
blic Tweet(JSONObject object){
super();

try {
  this.userId = object.getString("user_id");
  this.userHandle = object.getString("user_username");
  this.timestamp = object.getString("timestamp");
  this.body = object.getString("body");
} catch (JSONException e) {
  e.printStackTrace();
}


blic static ArrayList<Tweet> fromJson(JSONArray jsonArray) {
ArrayList<Tweet> tweets = new ArrayList<Tweet>(jsonArray.length());

for (int i=0; i < jsonArray.length(); i++) {
    JSONObject tweetJson = null;
    try {
        tweetJson = jsonArray.getJSONObject(i);
    } catch (Exception e) {
        e.printStackTrace();
        continue;
    }

    Tweet tweet = new Tweet(tweetJson);
    tweet.save();
    tweets.add(tweet);
}

return tweets;


Now you have a model that supports proper creation based on JSON. Create models for all the resources necessary for your mobile client.

3. Setup Your Authenticated Activities

Open src/com.codepath.apps.restclienttemplate/LoginActivity.java and configure the onLoginSuccess method which fires once your app has access to the authenticated API. Launch an activity and begin using your REST client:

oginActivity.java
rride
ic void onLoginSuccess() {
tent i = new Intent(this, TimelineActivity.class);
artActivity(i);

In your new authenticated activity, you can access your client anywhere with:

Client client = RestApplication.getRestClient();
nt.getHomeTimeline(1, new JsonHttpResponseHandler() {
blic void onSuccess(int statusCode, Header[] headers, JSONArray jsonArray) {
Log.d("DEBUG", "timeline: " + jsonArray.toString());
// Load json array into model classes


You can then load the data into your models from a JSONArray using:

yList<Tweet> tweets = Tweet.fromJSON(jsonArray);

or load the data from a single JSONObject with:

t t = new Tweet(json);
.body = "foo"
ve();

That's all you need to get started. From here, hook up your activities and their behavior, adjust your models and add more REST endpoints.

Extras
Loading Images with Glide

If you want to load a remote image url into a particular ImageView, you can use Glide to do that with:

e.with(this).load(imageUrl)
 .into(imageView);

This will load an image into the specified ImageView and resize the image to fit.

Logging Out

You can log out by clearing the access token at any time through the client object:

Client client = RestApplication.getRestClient();
nt.clearAccessToken();
Troubleshooting

This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.