Tuesday 28 March 2017

Retrofit Library with OkHTTP - Fetch Json



Step -1 :  Add to app level gradle

compile ('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'}
compile 'com.google.code.gson:gson:2.6.2'compile 'com.squareup.retrofit2:converter-gson:2.1.0'compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'compile 'com.squareup.okhttp3:okhttp:3.4.1'

Step - 2 : Add internet permission to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Step - 3 : activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.journaldev.retrofitintro.MainActivity">
    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        android:id="@+id/responseText"/></RelativeLayout>

Step - 4 : MainActivity.java

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.TextView;import android.widget.Toast;
import java.util.List;
import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {

    TextView responseText;    APIInterface apiInterface;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        responseText = (TextView) findViewById(R.id.responseText);        apiInterface = APIClient.getClient().create(APIInterface.class);

        /**         GET List Resources         **/        Call<MultipleResource> call = apiInterface.doGetListResources();        call.enqueue(new Callback<MultipleResource>() {
            @Override            public void onResponse(Call<MultipleResource> call, Response<MultipleResource> response) {


                Log.d("TAG",response.code()+"");
                String displayResponse = "";
                MultipleResource resource = response.body();                Integer text = resource.page;                Integer total = resource.total;                Integer totalPages = resource.totalPages;                List<MultipleResource.Datum> datumList = resource.data;
                displayResponse += text + " Page\n" + total + " Total\n" + totalPages + " Total Pages\n";
                for (MultipleResource.Datum datum : datumList) {
                    displayResponse += datum.id + " " + datum.name + " " + datum.pantoneValue + " " + datum.year + "\n";                }

                responseText.setText(displayResponse);
            }

            @Override            public void onFailure(Call<MultipleResource> call, Throwable t) {
                call.cancel();            }
        });
        /**         Create new user         **/        User user = new User("morpheus", "leader");        Call<User> call1 = apiInterface.createUser(user);        call1.enqueue(new Callback<User>() {
            @Override            public void onResponse(Call<User> call, Response<User> response) {
                User user1 = response.body();
                Toast.makeText(getApplicationContext(), user1.name + " " + user1.job + " " + user1.id + " " + user1.createdAt, Toast.LENGTH_SHORT).show();
            }

            @Override            public void onFailure(Call<User> call, Throwable t) {
                call.cancel();            }
        });
        /**         GET List Users         **/        Call<UserList> call2 = apiInterface.doGetUserList("2");        call2.enqueue(new Callback<UserList>() {
            @Override            public void onResponse(Call<UserList> call, Response<UserList> response) {

                UserList userList = response.body();                Integer text = userList.page;                Integer total = userList.total;                Integer totalPages = userList.totalPages;                List<UserList.Datum> datumList = userList.data;                Toast.makeText(getApplicationContext(), text + " page\n" + total + " total\n" + totalPages + " totalPages\n", Toast.LENGTH_SHORT).show();
                for (UserList.Datum datum : datumList) {
                    Toast.makeText(getApplicationContext(), "id : " + datum.id + " name: " + datum.first_name + " " + datum.last_name + " avatar: " + datum.avatar, Toast.LENGTH_SHORT).show();                }


            }

            @Override            public void onFailure(Call<UserList> call, Throwable t) {
                call.cancel();            }
        });

        /**         POST name and job Url encoded.         **/        Call<UserList> call3 = apiInterface.doCreateUserWithField("morpheus","leader");        call3.enqueue(new Callback<UserList>() {
            @Override            public void onResponse(Call<UserList> call, Response<UserList> response) {
                UserList userList = response.body();                Integer text = userList.page;                Integer total = userList.total;                Integer totalPages = userList.totalPages;                List<UserList.Datum> datumList = userList.data;                Toast.makeText(getApplicationContext(), text + " page\n" + total + " total\n" + totalPages + " totalPages\n", Toast.LENGTH_SHORT).show();
                for (UserList.Datum datum : datumList) {
                    Toast.makeText(getApplicationContext(), "id : " + datum.id + " name: " + datum.first_name + " " + datum.last_name + " avatar: " + datum.avatar, Toast.LENGTH_SHORT).show();                }

            }

            @Override            public void onFailure(Call<UserList> call, Throwable t) {
                call.cancel();            }
        });
    }
}

Step - 5 :   APIClient

import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {

    private static Retrofit retrofit = null;
    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        retrofit = new Retrofit.Builder()
                .baseUrl("https://reqres.in")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();


        return retrofit;    }

}


Step - 6 : Create Interface 'APIInterface'

import retrofit2.Call;import retrofit2.http.Body;import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.Query;
interface APIInterface {

    @GET("/api/unknown")
    Call<MultipleResource> doGetListResources();
    @POST("/api/users")
    Call<User> createUser(@Body User user);
    @GET("/api/users?")
    Call<UserList> doGetUserList(@Query("page") String page);
    @FormUrlEncoded    @POST("/api/users?")
    Call<UserList> doCreateUserWithField(@Field("name") String name, @Field("job") String job);}

Step - 7 : UserList.java

import com.google.gson.annotations.SerializedName;import java.util.ArrayList;import java.util.List;

public class UserList {

    @SerializedName("page")
    public Integer page;    @SerializedName("per_page")
    public Integer perPage;    @SerializedName("total")
    public Integer total;    @SerializedName("total_pages")
    public Integer totalPages;    @SerializedName("data")
    public List<Datum> data = new ArrayList<>();
    public class Datum {

        @SerializedName("id")
        public Integer id;        @SerializedName("first_name")
        public String first_name;        @SerializedName("last_name")
        public String last_name;        @SerializedName("avatar")
        public String avatar;
    }
}


Step - 8 : User.java

import com.google.gson.annotations.SerializedName;
public class User {


    @SerializedName("name")
    public String name;    @SerializedName("job")
    public String job;    @SerializedName("id")
    public String id;    @SerializedName("createdAt")
    public String createdAt;
    public User(String name, String job) {
        this.name = name;        this.job = job;    }


}

Step - 9 : MultipleResource.java

import com.google.gson.annotations.SerializedName;import java.util.ArrayList;import java.util.List;
public class MultipleResource {

    @SerializedName("page")
    public Integer page;    @SerializedName("per_page")
    public Integer perPage;    @SerializedName("total")
    public Integer total;    @SerializedName("total_pages")
    public Integer totalPages;    @SerializedName("data")
    public List<Datum> data = new ArrayList<>();
    public class Datum {

        @SerializedName("id")
        public Integer id;        @SerializedName("name")
        public String name;        @SerializedName("year")
        public Integer year;        @SerializedName("pantone_value")
        public String pantoneValue;
    }
}





22.

No comments:

Post a Comment