-
Notifications
You must be signed in to change notification settings - Fork 12
Use Retrofit to handle Rest Apis in your App ( Github apis Retrofit Version)
-
This guide shows how you can use Retrofit to fetch the repositories belonging to blikoon from github and display basic info about them in a shiny RecyclerView with ViewCards.
-
A previous guide has demonstrated how to use Gson and an http client to fetch and parse JSON data from a remote server, specificaly using the github apis documented here
-
This example shows how to improve the same app and abstract the http requests and parsing clutter away using Retrofit.If you need another example to get familiar with retrofit, this one should get you covered.
-
Take care of the dependencies first:
compile "com.android.support:design:25.3.1"
compile "com.android.support:recyclerview-v7:25.3.1"
compile "com.android.support:cardview-v7:25.3.1"
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Notice that we are using a gson converter here.
-
We use the exact same POJOs that were used in the GsonRetrofit app.Mainly Repo.java, Permissions.java and Owner.java.
-
Retrofit takes the burden of performing http calls:
client.get(
"https://api.github.com/orgs/blikoon/repos",
new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d(LOGTAG,"request FAILED. ResponseString :"+ responseString + " Error : "+ throwable.getMessage());
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Log.d(LOGTAG,"request SUCCEEDED.");
List<Repo> orgList = RepoResponse.parseJSON(responseString);
Log.d(LOGTAG," We got "+ orgList.size() + "Repos");
for( Repo org :orgList)
{
Log.d(LOGTAG, "Repo :"+ org.getFullName());
}
}
});
and turning JSON into POJO
public class RepoResponse {
public RepoResponse()
{
}
public static List<Repo> parseJSON(String response) {
Gson gson = new GsonBuilder().create();
//Source : http://stackoverflow.com/questions/9598707/gson-throwing-expected-begin-object-but-was-begin-array
Type collectionType = new TypeToken<Collection<Repo>>(){}.getType();
List<Repo> myRepos;
myRepos = gson.fromJson(response, collectionType);
return myRepos;
}
}
- Basicaly after you have the POJO classes , you create a class that maps the Java requests to the web requests:
public interface RepoService {
@GET("orgs/blikoon/repos")
Call<List<Repo>> getRepos();
//You can add other methods as need arises.
}
Note that in @GET we passed "orgs/blikoon/repos" which is the path of the api.This is the part after the base URI.
- You then implement the Callback<List> to have updates on the status of the request ( success or failure) in its overrides
public class MainActivity extends AppCompatActivity implements Callback<List<Repo>> {
private static final String REST_API_BASEURL = "https://api.github.com/";
public static final String LOGTAG = "BLIKOON_REPOS";
private RepoService repoService;
private Call<List<Repo>> listCall;//Use this to send requests to the server
private List<Repo> repos; //This is where you store responses from the server
private RepoAdapter repoAdapter;
We also define the constants and variables we'll need later.
- Retrofit is initialized :
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(REST_API_BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
repoService = retrofit.create(RepoService.class);
Here, do notice that we used a GsonConverterFactory instead of a MoshiConverterFactory as we did in https://github.com/blikoon/Ubufundi/wiki/Use-Retrofit-to-Handle-REST-Apis-in-your-android-app .
- We perform the request when the user clicks on a menu option:
public void doRefresh(MenuItem item) {
if (listCall == null) {
listCall = repoService.getRepos();
listCall.enqueue(this);
} else {
listCall.cancel();
listCall = null;
}
}
- And populate the results in the recyclerView on success or show a Tost with some error message on failure:
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
Log.d(LOGTAG,"Request successful");
if (response.isSuccessful()) {
repos = response.body();
Log.d(LOGTAG," Got "+ repos.size() + " repositories belonging to blikoon");
repoAdapter.notifyDataSetChanged();
}
listCall = null;
}
@Override
public void onFailure(Call<List<Repo>> call, Throwable t) {
Toast.makeText(this, "Failed to fetch repos!", Toast.LENGTH_SHORT).show();
listCall = null;
}
- Relevant files:
- Direct link to app:
- References :