Android Tutorial: what you need to know about retrofit and how to integrate it for Network calling

0
Shares
Android Tutorial: what you need to know about retrofit and how to integrate it for Network calling
4.5 (90%) 2 votes

Let me guess…

You’re one of those…

Those who are android developers, or those who just recently become interested into android development and exploring different libraries to find the brilliant ones among them.

So today, we’re going to take a deep look into what is Retrofit and how to integrate it into your android application so that you can embrace its benefits.

But, before we get into what is retrofit 2.0 android tutorial, let’s first understand what exactly is retrofit and how it benefits us.

Retrofit is one of the amazing tools that have been released into open source community. And, it is a safe-type HTTP client for applications of java and android both.

However, if you’re wondering that they’re still other options out there such as Volley from Google or AsyncTask, so why not use them? Well then, let me share the main premise behind type-safe HTTP client, which is that you’ll only need to worry about semantics of the queries that you send over the network, rather than the details of how to specify parameters correctly, construct URLs and so forth.

And, another benefit of retrofit 2.0 is that it makes the network calling easy by requiring you to write just a few interfaces and that’s all! Additionally, in retrofit, network calling is far more quicker than the others, which makes it perfect and easy to learn library.

OK now, Enough with the theory part… Let’s begin with the step-by-step guide to understanding how to integrate it into your android app.

We need 3 things to integrate Retrofit to Android Application

  1. Retrofit Library
  2. Interface with networking call method
  3. POJO class to get data from server

Step 1

We need three libraries for retrofit

1.Retrofit Library

2.Gson Converter Library(To Convert Server Incoming Data in POJO)

3.OkHttp Library (For get Log info and set Connection Timeout)

To Add this libraries in application paste following lines into application’s build.gradle in dependencies block.

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'

step1

Step 2

step2

Step 3

Now we will make POJO for JSON data which will coming from server.
 
For our case this data will come from server

{
   "code": "200",
   "status_msg": "Msg found static page",
   "success": true,
   "page_title": "Privacy Policy",
   "page_slug": "Privacy-Policy",
   "page_description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum augue odio, varius ut gravida a, ultrices sit amet nunc. In hac habitasse platea dictumst. Praesent at commodo lorem. Nulla mollis nisi ut lectus volutpat molestie. Donec pretium, nulla id pulvinar tempus, neque ex molestie mi, in pretium leo nulla eu velit. In hac habitasse platea dictumst. Donec cursus sapien et lorem sagittis mollis. Nullam id nisl nec elit sagittis hendrerit. Mauris tristique nec est congue sodales. Praesent eget aliquam leo. Aliquam nec lorem est.\r\n\r\nMaecenas non massa ut turpis aliquet mollis. Nulla neque arcu, faucibus ut mollis a, fringilla non ex. In hac habitasse platea dictumst. Suspendisse turpis odio, feugiat non tortor ac, congue faucibus lacus. Proin vitae feugiat ligula. Donec nec felis ornare, porttitor sapien a, faucibus velit. Phasellus faucibus urna in nulla consectetur congue.\r\n\r\nAenean cursus lacus eu purus porttitor, ut aliquam diam posuere. Curabitur ultricies non justo non scelerisque. Phasellus nunc massa, tempus vitae vestibulum .",
   "added_date": "2016-07-05"
}

Step3

Put your Json data in white box

By Clicking on Preview, you will get the POJO

step4

 

Step 4 Now we will made View to display data from server.

step4 (1)

 

Step 5 Now We will setup retrofit client

Create one new Class called ApiHandler and one interface APIInterface

In ApiHandler we will create retrofit client.

step5

Here we set ConnectionTimeout 30 second and add your BASE URL here.

In APIInterface we add HTTPMethods and parameter here in my case i have POST request to server as per your need you can change it with GET,PUT,DELETE,etc..

public interface APIInterface {
  @FormUrlEncoded
  @POST("api/")
  Call staticPagesApi(@FieldMap HashMap<String, String> requestBody);
}

Step 6 Now we have all things completed, so executing API Call in MainActivity.

public class MainActivity extends AppCompatActivity {
 
  private Toolbar toolbar;
  private TextView tvPage;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
 
      toolbar = (Toolbar) findViewById(R.id.toolbar);
      tvPage = (TextView) findViewById(R.id.tvPage);
 
      Call call = ApiHandler.getApiService().staticPagesApi(getParams());
      call.enqueue(new Callback() {
          @Override
          public void onResponse(Call call, Response response) {
              StaticPages resData = response.body();
                  if (resData.getSuccess()) {
                      toolbar.setTitle(resData.getPageTitle());
                      tvPage.setText(resData.getPageDescription());
                  }else
    {
// Handle your error here
    }
              }
          }
 
          @Override
          public void onFailure(Call call, Throwable t) {
// handle network call failure here
              t.printStackTrace();
          }
      });
  }
 
  private HashMap<String, String> getParams() {
      HashMap<String, String> param = new HashMap<>();
      param.put("action", "static_pages");
      param.put("page_slug", "Privacy-Policy");
 
      return param;
  }
}

Here, we need to pass two params action and page_slug to server.

After run on success we have to handle the UI update.

This is how it looks after calling API

step7

So, by following the above steps, you can now easily use retrofit 2.0 for network calls. Also, the code is available on github, click here to get it.

If you still have any doubts, you can contact our android app developer to resolve your issue or you can hire android developer from Space-O Technologies, which is a leading Android App Development Company and we have helped many young and entrepreneurial minds to make their app ideas come to reality. You can also check out our portfolio here.

This page was last edited on September 24th, 2018, at 8:02.
 
0
Shares
 

Have an App Idea?

Get your free consultation now