How to use Retrofit to get data from stackoverflow API and GitHub Demo in android studio

Retrofit is a type-safe REST client for Android developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp. See this guide to understand how OkHttp works.

This library makes downloading JSON or XML data from a web API fairly straightforward. Once the data is downloaded then it is parsed into a Plain Old Java Object (POJO) which must be defined for each "resource" in the response.

Setup
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Must be defined on internet permission on AndroidManifest.xml .


Dependencies
Add following dependencies on app/build.gradle file:

dependencies {
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
view raw build.gradle hosted with ❤ by GitHub


Converter:
Here is the different type of  Gson converter, we can use them:

Converter Library
Gson com.squareup.retrofit2:converter-gson:2.1.0
Jackson com.squareup.retrofit2:converter-jackson:2.1.0
Moshi com.squareup.retrofit2:converter-moshi:2.1.0
Protobuf com.squareup.retrofit2:converter-protobuf:2.1.0
Wire com.squareup.retrofit2:converter-wire:2.1.0
Simple XML com.squareup.retrofit2:converter-simplexml:2.1.0
view raw gson conveter hosted with ❤ by GitHub


How to create retrofit instance, 
package co.apidemos.rest;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by dharma kshetri on 12/27/16.
*/
public class APIClient {
public static final String STACKOVERFLOW_BASE_URL="https://api.stackexchange.com" ;
public static Retrofit retrofit=null;
// get stackoverflow client
public static Retrofit getStackOverFLowClient(){
if(retrofit == null){
retrofit=new Retrofit.Builder()
.baseUrl(STACKOVERFLOW_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
view raw APIClient.java hosted with ❤ by GitHub
then we have to define, the userendpoint:
package co.apidemos.rest;
import co.apidemos.model.StackOverFlowData;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by dharma kshetri on 12/27/16.
*/
public interface UserEndPoints {
@GET("/2.2/users?pagesize=10&order=desc&sort=reputation&site=stackoverflow")
Call<StackOverFlowData> getUsers(@Query("sort") String sort);
}
Now, create model class, user variables,
package co.apidemos.model;
import com.google.gson.annotations.SerializedName;
import java.util.HashMap;
/**
* Created by dharma kshetri on 12/27/16.
*/
public class StackOverFlowUser {
@SerializedName("location")
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getReputation() {
return reputation;
}
public void setReputation(String reputation) {
this.reputation = reputation;
}
public HashMap<String, Integer> getBadges() {
return badges;
}
public void setBadges(HashMap<String, Integer> badges) {
this.badges = badges;
}
@SerializedName("display_name")
private String userName;
@SerializedName("reputation")
private String reputation;
@SerializedName("badge_counts")
private HashMap<String, Integer> badges= new HashMap<>();
}
In MainActivity.java, we have to create instance of APIClient and call the users.

package co.apidemos.activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import co.apidemos.BaseActivity;
import co.apidemos.R;
import co.apidemos.adapter.StackOverFlowAdapter;
import co.apidemos.model.StackOverFlowData;
import co.apidemos.model.StackOverFlowUser;
import co.apidemos.rest.APIClient;
import co.apidemos.rest.UserEndPoints;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by dharma kshetri on 12/27/16.
*/
public class StackOverFlowActivity extends BaseActivity {
@BindView(R.id.emptyTextView)
TextView emptyTextView;
//@BindView(R.id.recyclerView)
RecyclerView recyclerView;
List<StackOverFlowUser> myDataSource= new ArrayList<>();
RecyclerView.Adapter myAdater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getApplicationContext().getResources().getString(R.string.stackoverflow));
creatingLayouts();
ButterKnife.bind(this);
loadUsers();
}
private void loadUsers() {
UserEndPoints apiService= APIClient.getStackOverFLowClient().create(UserEndPoints.class);
Call<StackOverFlowData> call= apiService.getUsers("reputation");
showProgressDialog();
call.enqueue(new Callback<StackOverFlowData>() {
@Override
public void onResponse(Call<StackOverFlowData> call, Response<StackOverFlowData> response) {
List<StackOverFlowUser> users=response.body().getUsers();
myDataSource.clear();
myDataSource.addAll(response.body().getUsers());
myAdater.notifyDataSetChanged();
hideProgressDialog();
}
@Override
public void onFailure(Call<StackOverFlowData> call, Throwable t) {
t.printStackTrace();
emptyTextView.setText(t.toString());
}
});
}
private void creatingLayouts() {
setContentView(R.layout.activity_stackoverflow);
recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdater=new StackOverFlowAdapter(getApplicationContext(),myDataSource, R.layout.stackoverflow_list_items);
recyclerView.setAdapter(myAdater);
}
}
Download Full code: https://github.com/dharmakshetri/Android-API-Demos
and you can find out Awesome Retrofit Article: Retrofit Tutorial With Example In Android Studio [Step by Step]
More details:
https://square.github.io/retrofit/
https://github.com/square/retrofit
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/
http://www.vogella.com/tutorials/Retrofit/article.html


Happy Coding !!!

1 comment: