{"id":808,"date":"2018-01-15T05:34:28","date_gmt":"2018-01-15T05:34:28","guid":{"rendered":"http:\/\/abhiandroid.com\/programming\/?page_id=808"},"modified":"2019-06-13T05:51:28","modified_gmt":"2019-06-13T05:51:28","slug":"retrofit","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/programming\/retrofit","title":{"rendered":"Retrofit Tutorial With Example In Android Studio [Step by Step]"},"content":{"rendered":"<p>In Android, Retrofit is a REST Client for Java and Android by Square inc under Apache 2.0 license. Its a simple network library that used for network transactions. By using this library we can seamlessly capture JSON response from web service\/web API. It&#8217;s easy and fast library to retrieve and upload the data(JSON or any other structured data) via a REST based web service.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-829\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-Post-Example-In-Android-Studio.gif\" alt=\"Retrofit Post Example In Android Studio\" width=\"172\" height=\"304\" \/><\/p>\n<hr \/>\n<h4><strong>Need of Retrofit In Android:<\/strong><\/h4>\n<p>We have a lot of network libraries that used to fetch and send the data from\/to server. In our previous article we use Volley library for network transactions but Retrofit is an ultimate replacement of Volley and all other libraries. Retrofit is better alternative of other libraries in terms of performance, ease of use, extensibility and others.<\/p>\n<hr \/>\n<h4><strong>Difference Between Retrofit and other libraries:<\/strong><\/h4>\n<p>In Android, retrofit library is different from other network libraries because it gives us an easy to use platform through which we don&#8217;t need to parse JSON responses as they are done by library itself. It used GSON library in the background to parser the response data. What we need to do is define a POJO (Plain Old Java Object) to parse the response.<\/p>\n<hr \/>\n<h4><strong>Performance benchmarks for Android AsyncTask, Volley and Retrofit (in milliseconds, lower value is better):<\/strong><\/h4>\n<p>Here is the main difference between our three mainly used techniques for implementing API&#8217;s is our android app. You can see the difference in performance that for one discussion means for one network request and response they will take how much time.<\/p>\n<p><span style=\"color: #008000;\"><strong>1. AsyncTask:\u00a0<\/strong><\/span><br \/>\none(1) discussion: 941 ms<br \/>\nSeven(7) discussions: 4539 ms<br \/>\nTwenty Five(25) discussions: 13957 ms<\/p>\n<p><span style=\"color: #008000;\"><strong>2. Volley:\u00a0<\/strong><\/span><br \/>\none(1) discussion: 560 ms<br \/>\nSeven(7) discussions: 2202 ms<br \/>\nTwenty Five(25) discussions: 4275 ms<\/p>\n<p><span style=\"color: #008000;\"><strong>3. Retrofit:\u00a0<\/strong><\/span><br \/>\none(1) discussion: 312 ms<br \/>\nSeven(7) discussions: 889 ms<br \/>\nTwenty Five(25) discussions: 1059 ms<\/p>\n<hr \/>\n<h4><strong>Steps to Integrate Retrofit 1.9 in our Android Studio Project.<\/strong><\/h4>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-830\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-In-Android.png\" alt=\"Retrofit-In-Android\" width=\"575\" height=\"366\" srcset=\"https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-In-Android.png 575w, https:\/\/abhiandroid.com\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-In-Android-300x191.png 300w\" sizes=\"auto, (max-width: 575px) 100vw, 575px\" \/><\/p>\n<p>Here are the main steps to integrate Retrofit in our project.<\/p>\n<p><span style=\"color: #008000;\"><strong>1.Add dependency file in gradle:\u00a0<\/strong><\/span><br \/>\nFirsly add this library in your build.gradle file in app module.<\/p>\n<p>compile &#8216;com.squareup.retrofit:retrofit:1.9.0&#8217;<\/p>\n<p><span style=\"color: #008000;\"><strong>Add Internet Permission in the AndroidManifest.xml:\u00a0<\/strong><\/span><br \/>\nFor network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre>&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\npackage=\"com.abhiandroid.retroiftexample\"&gt;\r\n\r\n&lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n\r\n&lt;application&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>3. POJO\/Model Class:\u00a0<\/strong><\/span><br \/>\nFor fetching response we need create POJO class that automatically parse the JSON data using Gson in background. We just need to create this POJO class. For creating POJO class first method is defining each and every variable by ourself and other best and fast method is using http:\/\/www.jsonschema2pojo.org\/ platform. By using this platform you can easily convert your JSON response to POJO class, for this we need to copy our JSON response and paste it in jsonschema2pojo and it will create setter getter methods as per our requirement.<\/p>\n<pre>Sample POJO class:\r\n\r\npublic class SamplePojo {\r\n\r\nprivate int userId;\r\nprivate String name;\r\n\r\npublic int getUserId() {\r\nreturn userId;\r\n}\r\n\r\npublic String getName() {\r\nreturn name;\r\n}\r\n}<\/pre>\n<p>4. Add downloaded POJO class in your project.<\/p>\n<p><span style=\"color: #008000;\"><strong>5. API Interface :\u00a0<\/strong><\/span><br \/>\nNow we need to create an Interface to define our different methods that will be used for network transactions. Here is the sample of API Interface.<\/p>\n<pre>public interface ApiInterface {\r\n\r\n\r\n\/\/ For POST request\r\n\r\n    @FormUrlEncoded    \/\/ annotation that used with POST type request\r\n    @POST(\"\/demo\/login.php\") \/\/ specify the sub url for our base url\r\n    public void login(\r\n            @Field(\"user_email\") String user_email,\r\n            @Field(\"user_pass\") String user_pass, Callback&lt;SignUpResponse&gt; callback); \r\n\r\n\/\/user_email and user_pass are the post parameters and SignUpResponse is a POJO class which recieves the response of this API\r\n\r\n\r\n\/\/ for GET request\r\n\r\n    @GET(\"\/demo\/countrylist.php\") \/\/ specify the sub url for our base url\r\n    public void getVideoList(Callback&lt;List&lt;CountryResponse&gt;&gt; callback);\r\n\r\n\/\/ CountryResponse is a POJO class which receives the response of this API\r\n\r\n}\r\n\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>6. RestAdapter:\u00a0<\/strong><\/span><\/p>\n<p>We need to define RestAdapter to implement API&#8217;s. Suppose we have to implement login API then we need to build RestAdapter, setting root url and create connection between our adapter and API Interface. For this, its better to create a class in which we have a method that create the connection and then returns the API Interface object. You can create this RestAdapter where you want to implement API but its better to create a common class\/method and use it where you want.<\/p>\n<pre> public class Api {\r\n\r\n    public static ApiInterface getClient() {\r\n\r\n        RestAdapter adapter = new RestAdapter.Builder()\r\n                .setEndpoint(\"http:\/\/healthyblackmen.org\") \/\/Setting the Root URL\r\n                .build(); \/\/Finally building the adapter\r\n\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = adapter.create(ApiInterface.class);\r\n        return api;\r\n    }\r\n}\r\n<\/pre>\n<hr \/>\n<h4>Example Of Retrofit 1.9 For POST Type In Android Studio:<\/h4>\n<p>Below is the example of Retrofit in which we have implement the POST type request. In this we are implementing sign up api. In this example firstly we create sign up page design with 3 EditText name, email and password and one sign up Button. After that in our MainActivity we are getting our EditText and Button and on click of sign up Button the data in EditText is validate and then we are implementing signup api to save the data in our database. After getting response from api we are displaying the message on the screen by using a Toast.<\/p>\n<p>Below you can download code, see final output and step by step explanation of example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/RetrofitExample\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-829\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-Post-Example-In-Android-Studio.gif\" alt=\"Retrofit Post Example In Android Studio\" width=\"172\" height=\"304\" \/><\/p>\n<p><strong>Step 1:<\/strong> Create a new project And Name It RetrofitExample.<\/p>\n<p><strong>Step 2:<\/strong> Open Gradle Scripts &gt; build.gradle and add Retrofit and RecyclerView Library dependency in it.<\/p>\n<pre>apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 26\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.retrofitexample\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 26\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n        testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\r\n    implementation 'com.android.support:appcompat-v7:26.1.0'\r\n    compile 'com.squareup.retrofit:retrofit:1.9.0' \/\/ dependency for Retrofit\r\n}\r\n<\/pre>\n<p><strong>Step 3:<\/strong> Add Internet Permission in the AndroidManifest.xml:<\/p>\n<p>For network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.retrofitexample\"&gt;\r\n\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:roundIcon=\"@mipmap\/ic_launcher_round\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity android:name=\".MainActivity\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;\r\n<\/pre>\n<p><strong>Step 4:<\/strong> Open res -&gt; layout -&gt; activity_main.xml (or) main.xml and add following code:<\/p>\n<p>In this step we create a RecyclerView in our XML file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"&gt;\r\n\r\n\r\n    &lt;ScrollView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:scrollbars=\"none\"&gt;\r\n\r\n\r\n        &lt;LinearLayout\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:layout_gravity=\"center\"\r\n            android:orientation=\"vertical\"\r\n            android:padding=\"20dp\"&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/username\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Full Name\"\r\n                android:imeOptions=\"actionNext\"\r\n                android:inputType=\"text\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/email\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Email Address\"\r\n                android:imeOptions=\"actionNext\"\r\n                android:inputType=\"textEmailAddress\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/password\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Password\"\r\n                android:imeOptions=\"actionDone\"\r\n                android:inputType=\"textPassword\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;Button\r\n                android:id=\"@+id\/signUp\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:layout_marginTop=\"10dp\"\r\n                android:backgroundTint=\"@color\/colorPrimary\"\r\n                android:text=\"Sign Up\"\r\n                android:textColor=\"#fff\"\r\n                android:textSize=\"17sp\" \/&gt;\r\n\r\n        &lt;\/LinearLayout&gt;\r\n    &lt;\/ScrollView&gt;\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><strong>Step 5:<\/strong> Create a new POJO class SignUpResponse.java in which we have setter\/getter method to get the data from API.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\npublic class SignUpResponse {\r\n\r\n    private String success;\r\n    private String message;\r\n    private Integer userid;\r\n    private Map&lt;String, Object&gt; additionalProperties = new HashMap&lt;String, Object&gt;();\r\n\r\n    public String getSuccess() {\r\n        return success;\r\n    }\r\n\r\n    public void setSuccess(String success) {\r\n        this.success = success;\r\n    }\r\n\r\n    public String getMessage() {\r\n        return message;\r\n    }\r\n\r\n    public void setMessage(String message) {\r\n        this.message = message;\r\n    }\r\n\r\n    public Integer getUserid() {\r\n        return userid;\r\n    }\r\n\r\n    public void setUserid(Integer userid) {\r\n        this.userid = userid;\r\n    }\r\n\r\n    public Map&lt;String, Object&gt; getAdditionalProperties() {\r\n        return this.additionalProperties;\r\n    }\r\n\r\n    public void setAdditionalProperty(String name, Object value) {\r\n        this.additionalProperties.put(name, value);\r\n    }\r\n\r\n}\r\n<\/pre>\n<p><strong>Step 6:<\/strong> Create an Interface and name it ApiInterface.java and paste the following code in it.<\/p>\n<p>In this step we create an Interface in which we have registration post request method to send the data using api to our server.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit.Callback;\r\nimport retrofit.http.Field;\r\nimport retrofit.http.FormUrlEncoded;\r\nimport retrofit.http.POST;\r\n\r\npublic interface ApiInterface {\r\n\r\n    @FormUrlEncoded \/\/ annotation used in POST type requests\r\n    @POST(\"\/retrofit\/register.php\")     \/\/ API's endpoints\r\n    public void registration(@Field(\"name\") String name,\r\n                             @Field(\"email\") String email,\r\n                             @Field(\"password\") String password,\r\n                             @Field(\"logintype\") String logintype,\r\n                             Callback&lt;SignUpResponse&gt; callback);\r\n<\/pre>\n<p>\/\/ In registration method @Field used to set the keys and String data type is representing its a string type value and callback is used to get the response from api and it will set it in our POJO class<br \/>\n}<\/p>\n<p><strong>Step 7:<\/strong> Create a new Class Api.java and paste the following code in it.<\/p>\n<p>In this step we create a new class to set the RestAdapter. In this class getClient method returns the Api Interface class object which we are using in our MainActivity.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport retrofit.RestAdapter;\r\n\r\npublic class Api {\r\n\r\n    public static ApiInterface getClient() {\r\n\r\n        \/\/ change your base URL\r\n        RestAdapter adapter = new RestAdapter.Builder()\r\n                .setEndpoint(\"http:\/\/mobileappdatabase.in\/\") \/\/Set the Root URL\r\n                .build(); \/\/Finally building the adapter\r\n\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = adapter.create(ApiInterface.class);\r\n        return api; \/\/ return the APIInterface object\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Step 8:<\/strong> Now open app -&gt; java -&gt; package -&gt; MainActivity.java and add the below code.<\/p>\n<p>In this step Firstly we are getting reference of EditText and Button.After that we implement setOnClickListener event on Button and on click of sign up Button the data in EditText is validate and then we are implementing signup api to save the data in our database. After getting response from api we are displaying the message on the screen by using a Toast.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport android.Manifest;\r\nimport android.app.ProgressDialog;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.View;\r\nimport android.widget.Button;\r\nimport android.widget.EditText;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit.Callback;\r\nimport retrofit.RetrofitError;\r\nimport retrofit.client.Response;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n    SignUpResponse signUpResponsesData;\r\n    EditText email, password, name;\r\n    Button signUp;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        \/\/ init the EditText and Button\r\n        name = (EditText) findViewById(R.id.username);\r\n        email = (EditText) findViewById(R.id.email);\r\n        password = (EditText) findViewById(R.id.password);\r\n        signUp = (Button) findViewById(R.id.signUp);\r\n        \/\/ implement setOnClickListener event on sign up Button\r\n        signUp.setOnClickListener(new View.OnClickListener() {\r\n            @Override\r\n            public void onClick(View view) {\r\n                \/\/ validate the fields and call sign method to implement the api\r\n                if (validate(name) &amp;&amp; validate(email) &amp;&amp; validate(password)) {\r\n                    signUp();\r\n                }\r\n            }\r\n        });\r\n    }\r\n\r\n    private boolean validate(EditText editText) {\r\n        \/\/ check the lenght of the enter data in EditText and give error if its empty\r\n        if (editText.getText().toString().trim().length() &gt; 0) {\r\n            return true; \/\/ returs true if field is not empty\r\n        }\r\n        editText.setError(\"Please Fill This\");\r\n        editText.requestFocus();\r\n        return false;\r\n    }\r\n\r\n    private void signUp() {\r\n        \/\/ display a progress dialog\r\n        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);\r\n        progressDialog.setCancelable(false); \/\/ set cancelable to false\r\n        progressDialog.setMessage(\"Please Wait\"); \/\/ set message\r\n        progressDialog.show(); \/\/ show progress dialog\r\n\r\n        \/\/ Api is a class in which we define a method getClient() that returns the API Interface class object\r\n        \/\/ registration is a POST request type method in which we are sending our field's data\r\n        Api.getClient().registration(name.getText().toString().trim(),\r\n                email.getText().toString().trim(),\r\n                password.getText().toString().trim(),\r\n                \"email\", new Callback&lt;SignUpResponse&gt;() {\r\n                    @Override\r\n                    public void success(SignUpResponse signUpResponse, Response response) {\r\n                        \/\/ in this method we will get the response from API\r\n                        progressDialog.dismiss(); \/\/dismiss progress dialog\r\n                        signUpResponsesData = signUpResponse;\r\n                        \/\/ display the message getting from web api\r\n                        Toast.makeText(MainActivity.this, signUpResponse.getMessage(), Toast.LENGTH_SHORT).show();\r\n                    }\r\n\r\n                    @Override\r\n                    public void failure(RetrofitError error) {\r\n                        \/\/ if error occurs in network transaction then we can get the error in this method.\r\n                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();\r\n                        progressDialog.dismiss(); \/\/dismiss progress dialog\r\n\r\n                    }\r\n                });\r\n    }\r\n}<\/pre>\n<h4><strong>Retrofit 1.9 Example For GET type Request In Android Studio:<\/strong><\/h4>\n<p>Below is the example of Retrofit in which we have implement the GET type request. In this we are displaying a list of items by using RecyclerView. Firstly we declare a RecyclerView in our XML file and then get the reference of it in our Activity. After that we create POJO Class, API Interface, Rest Adapter and then implement the API in our onCreate method of MainActivity. After getting the success response from server we are calling our adapter to set the data in RecyclerView.<\/p>\n<p>Below you can download code, see final output and step by step explanation of example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/RetrofitExample\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-832\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-GET-Example-In-Android-Studio.gif\" alt=\"Retrofit GET Example In Android Studio\" width=\"170\" height=\"302\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create A New Project And Name It RetrofitExample.<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Open Gradle Scripts &gt; build.gradle and add Retrofit and RecyclerView Library dependency in it.<\/p>\n<pre>apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 26\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.retrofitexample\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 26\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n        testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\r\n    implementation 'com.android.support:appcompat-v7:26.1.0'\r\n    compile 'com.android.support:recyclerview-v7:24.1.1' \/\/ dependency for RecyclerView\r\n    compile 'com.squareup.retrofit:retrofit:1.9.0' \/\/ dependency for Retrofit\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Add Internet Permission in the AndroidManifest.xml:<\/p>\n<p>For network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.retrofitexample\"&gt;\r\n\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:roundIcon=\"@mipmap\/ic_launcher_round\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity android:name=\".MainActivity\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Open res -&gt; layout -&gt; activity_main.xml (or) main.xml and add following code:<br \/>\nIn this step we create a RecyclerView in our XML file.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"&gt;\r\n\r\n    &lt;android.support.v7.widget.RecyclerView\r\n        android:id=\"@+id\/recyclerView\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\" \/&gt;\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong><\/span> Create a new XML file user_list_items.xml for item of RecyclerView and paste the following code in it.<\/p>\n<p>In this step we create a new xml file for item row in which we creates two TextView to show the data.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n\r\n&lt;LinearLayout android:layout_width=\"match_parent\"\r\n    android:layout_height=\"wrap_content\"\r\n    android:padding=\"6dp\"\r\n    android:gravity=\"center_vertical\"\r\n    android:background=\"#f2f2f2\"\r\n    android:orientation=\"vertical\"\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"&gt;\r\n        &lt;!--\r\n        create Textview's for user name and email id\r\n        --&gt;\r\n        &lt;TextView\r\n            android:id=\"@+id\/name\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:text=\"Name:\"\r\n            android:textColor=\"@color\/colorPrimary\"\r\n            android:textSize=\"17sp\" \/&gt;\r\n\r\n\r\n        &lt;TextView\r\n            android:id=\"@+id\/email\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:text=\"Email:\"\r\n            android:textColor=\"@color\/colorPrimary\"\r\n            android:textSize=\"16sp\" \/&gt;\r\n    &lt;View\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"1dp\"\r\n        android:layout_marginTop=\"2dp\"\r\n        android:layout_marginBottom=\"2dp\"\r\n        android:background=\"@color\/colorPrimary\"\/&gt;\r\n    &lt;\/LinearLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 6:<\/strong><\/span> Create a new POJO class UserListResponse.java in which we have setter\/getter method to get the data from API.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\npublic class UserListResponse {\r\n\r\n    \/\/ POJO class to get the data from web api\r\nprivate String id;\r\nprivate String name;\r\nprivate String email;\r\nprivate String password;\r\nprivate String com_code;\r\nprivate String status;\r\nprivate String forgot;\r\nprivate Map&lt;String, Object&gt; additionalProperties = new HashMap&lt;String, Object&gt;();\r\n\r\npublic String getId() {\r\nreturn id;\r\n}\r\n\r\npublic void setId(String id) {\r\nthis.id = id;\r\n}\r\n\r\npublic String getName() {\r\nreturn name;\r\n}\r\n\r\npublic void setName(String name) {\r\nthis.name = name;\r\n}\r\n\r\npublic String getEmail() {\r\nreturn email;\r\n}\r\n\r\npublic void setEmail(String email) {\r\nthis.email = email;\r\n}\r\n\r\npublic String getPassword() {\r\nreturn password;\r\n}\r\n\r\npublic void setPassword(String password) {\r\nthis.password = password;\r\n}\r\n\r\npublic String getCom_code() {\r\nreturn com_code;\r\n}\r\n\r\npublic void setCom_code(String com_code) {\r\nthis.com_code = com_code;\r\n}\r\n\r\npublic String getStatus() {\r\nreturn status;\r\n}\r\n\r\npublic void setStatus(String status) {\r\nthis.status = status;\r\n}\r\n\r\npublic String getForgot() {\r\nreturn forgot;\r\n}\r\n\r\npublic void setForgot(String forgot) {\r\nthis.forgot = forgot;\r\n}\r\n\r\npublic Map&lt;String, Object&gt; getAdditionalProperties() {\r\nreturn this.additionalProperties;\r\n}\r\n\r\npublic void setAdditionalProperty(String name, Object value) {\r\nthis.additionalProperties.put(name, value);\r\n}\r\n\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 7:<\/strong><\/span> Create an Interface and name it ApiInterface.java and paste the following code in it.<\/p>\n<p>In this step we create an Interface in which we have getUserList method to get the data from web api.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit.Callback;\r\nimport retrofit.http.GET;\r\n\r\npublic interface ApiInterface {\r\n\r\n    \/\/ API's endpoints\r\n    @GET(\"\/retrofit\/getuser.php\")\r\n    public void getUsersList(\r\n            Callback&lt;List&lt;UserListResponse&gt;&gt; callback);\r\n\r\n\/\/ UserListResponse is POJO class to get the data from API, In above method we use List&lt;UserListResponse&gt; because the data in our API is starting from JSONArray and callback is used to get the response from api and it will set it in our POJO class\r\n\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 8:<\/strong><\/span> Create a new Class Api.java and paste the following code in it.<\/p>\n<p>In this step we create a new class to set the RestAdapter. In this class getClient method returns the Api Interface class object which we are using in our MainActivity.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport retrofit.RestAdapter;\r\n\r\npublic class Api {\r\n\r\n    public static ApiInterface getClient() {\r\n\r\n        \/\/ change your base URL\r\n        RestAdapter adapter = new RestAdapter.Builder()\r\n                .setEndpoint(\"http:\/\/mobileappdatabase.in\/\") \/\/Set the Root URL\r\n                .build(); \/\/Finally building the adapter\r\n\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = adapter.create(ApiInterface.class);\r\n        return api; \/\/ return the APIInterface object\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 9:<\/strong><\/span> Now open app -&gt; java -&gt; package -&gt; MainActivity.java and add the below code.<\/p>\n<p>In this step Firstly we get the reference of RecyclerView in our Activity. After that we implement the API in our onCreate method. Finally After getting the success response from server we are calling our adapter to set the data in RecyclerView. In this step we show a Progress dialog while implementing API and after getting response or error we dismiss it.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport android.Manifest;\r\nimport android.app.ProgressDialog;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.support.v7.widget.LinearLayoutManager;\r\nimport android.support.v7.widget.RecyclerView;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit.Callback;\r\nimport retrofit.RetrofitError;\r\nimport retrofit.client.Response;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n    RecyclerView recyclerView;\r\n    List&lt;UserListResponse&gt; userListResponseData;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);\r\n        getUserListData(); \/\/ call a method in which we have implement our GET type web API\r\n    }\r\n\r\n    private void getUserListData() {\r\n        \/\/ display a progress dialog\r\n        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);\r\n        progressDialog.setCancelable(false); \/\/ set cancelable to false\r\n        progressDialog.setMessage(\"Please Wait\"); \/\/ set message\r\n        progressDialog.show(); \/\/ show progress dialog\r\n\r\n        \/\/ Api is a class in which we define a method getClient() that returns the API Interface class object\r\n        \/\/ getUsersList() is a method in API Interface class, in this method we define our API sub url\r\n        Api.getClient().getUsersList(new Callback&lt;List&lt;UserListResponse&gt;&gt;() {\r\n            @Override\r\n            public void success(List&lt;UserListResponse&gt; userListResponses, Response response) {\r\n                \/\/ in this method we will get the response from API\r\n                progressDialog.dismiss(); \/\/dismiss progress dialog\r\n                userListResponseData = userListResponses;\r\n                setDataInRecyclerView(); \/\/ call this method to set the data in adapter\r\n            }\r\n\r\n            @Override\r\n            public void failure(RetrofitError error) {\r\n                \/\/ if error occurs in network transaction then we can get the error in this method.\r\n                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();\r\n                progressDialog.dismiss(); \/\/dismiss progress dialog\r\n\r\n            }\r\n        });\r\n    }\r\n\r\n    private void setDataInRecyclerView() {\r\n        \/\/ set a LinearLayoutManager with default vertical orientation\r\n        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);\r\n        recyclerView.setLayoutManager(linearLayoutManager);\r\n        \/\/ call the constructor of UsersAdapter to send the reference and data to Adapter\r\n        UsersAdapter usersAdapter = new UsersAdapter(MainActivity.this, userListResponseData);\r\n        recyclerView.setAdapter(usersAdapter); \/\/ set the Adapter to RecyclerView\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 10:<\/strong><\/span> Create a new class UsersAdapter.java inside package and add the following code.<\/p>\n<p>In this step we create a UsersAdapter class and extends RecyclerView.Adapter class with View Holder in it. After that we implement the overrided methods and create a constructor for getting the data from Activity. In this custom Adapter two methods are more important first is onCreateViewHolder in which we inflate the layout item xml and pass it to View Holder and other is onBindViewHolder in which we set the data in the view\u2019s with the help of View Holder. Finally we implement the setOnClickListener event on itemview and on click of item we display the name of the user with the help of Toast.<\/p>\n<pre>package com.abhiandroid.retrofitexample;\r\n\r\nimport android.content.Context;\r\nimport android.support.v7.widget.RecyclerView;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.TextView;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.List;\r\n\r\n\r\n\r\npublic class UsersAdapter extends RecyclerView.Adapter&lt;UsersAdapter.UsersViewHolder&gt; {\r\n\r\n    Context context;\r\n    List&lt;UserListResponse&gt; userListResponseData;\r\n\r\n    public UsersAdapter(Context context, List&lt;UserListResponse&gt; userListResponseData) {\r\n        this.userListResponseData = userListResponseData;\r\n        this.context = context;\r\n    }\r\n\r\n    @Override\r\n    public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n\r\n        View view = LayoutInflater.from(context).inflate(R.layout.users_list_items, null);\r\n        UsersViewHolder usersViewHolder = new UsersViewHolder(view);\r\n        return usersViewHolder;\r\n    }\r\n\r\n    @Override\r\n    public void onBindViewHolder(UsersViewHolder holder, final int position) {\r\n        \/\/ set the data\r\n        holder.name.setText(\"Name: \" + userListResponseData.get(position).getName());\r\n        holder.email.setText(\"Email: \" + userListResponseData.get(position).getEmail());\r\n        \/\/ implement setONCLickListtener on itemView\r\n        holder.itemView.setOnClickListener(new View.OnClickListener() {\r\n            @Override\r\n            public void onClick(View view) {\r\n                \/\/ display a toast with user name\r\n                Toast.makeText(context, userListResponseData.get(position).getName(), Toast.LENGTH_SHORT).show();\r\n            }\r\n        });\r\n    }\r\n\r\n    @Override\r\n    public int getItemCount() {\r\n        return userListResponseData.size(); \/\/ size of the list items\r\n    }\r\n\r\n    class UsersViewHolder extends RecyclerView.ViewHolder {\r\n        \/\/ init the item view's\r\n        TextView name, email;\r\n\r\n        public UsersViewHolder(View itemView) {\r\n            super(itemView);\r\n            \/\/ get the reference of item view's\r\n            name = (TextView) itemView.findViewById(R.id.name);\r\n            email = (TextView) itemView.findViewById(R.id.email);\r\n        }\r\n    }\r\n}\r\n\r\n<\/pre>\n<hr \/>\n<h4><strong>Difference between Retrofit 1.9 and 2.x in android:<\/strong><\/h4>\n<p><strong><span style=\"color: #008000;\">1.<\/span> Gradle Dependencies &#8211;<\/strong> In retrofit 1.9 version we need to import the HTTP client but in 2.x OKHHttp dependency is already defined.<\/p>\n<p><strong><span style=\"color: #008000;\">2.<\/span> RestAdapter and Retrofit &#8211;<\/strong> In retrofit 1.9 we use RestAdapter but in 2.x we use Retrofit. The builder pattern using these two is still same.<\/p>\n<p>Retrofit 1.9<\/p>\n<pre> RestAdapter.Builder builder = new RestAdapter.Builder();<\/pre>\n<p>Retrofit 2.x<\/p>\n<pre>Retrofit.Builder builder = new Retrofit.Builder();<\/pre>\n<p><strong><span style=\"color: #008000;\">3.<\/span> setEndpoint and baseUrl method &#8211;<\/strong> In Retrofit 1.9, the setEndpoint(String url) method defines the API\u2019s base url but in 2.x baseUrl(API_BASE_URL) is used to set the base url.<\/p>\n<p><strong><span style=\"color: #008000;\">4.<\/span> Dynamic Urls &#8211;<\/strong> One of the best feature in retrofit 2.x is dynamic urls. Lets take a use-case, we need to download file from internet source and files will have different urls. The files are either stored on Amazon;s S3 server or somewhere else on the web. So the main problem in 1.9 is we need to create RestAdapter with base url every time we wanted to load a file but in 2.x we can use dynamic urls, for implementing it we can leave the HTTP verb annotation empty and use the @url annotation as a parameter of method. Retrofit will automatically map the provided url string and do the job for us.<\/p>\n<pre> @GET\r\n    public Call&lt;File&gt; getZipFile(@Url String url);\r\n<\/pre>\n<p><strong><span style=\"color: #008000;\">5.<\/span> Synchronous &amp; Asynchronous Requests &#8211;<\/strong> In 1.9 synchronous methods required return type. In contrast asynchronous method required a generic callback as the last method parameter. In 2.x there is no differentiation for synchronous and asynchronous requests. Requests are now wrapped into generic call class using the desired response type.<\/p>\n<p><strong><span style=\"color: #008000;\">6.<\/span> Cancel Requests &#8211;<\/strong> In 1.9 version there was no way to cancel the requests even if they weren\u2019t executed yet but in 2.x we can cancel requests if Http scheduler didn\u2019t executed it already.<\/p>\n<p><strong><span style=\"color: #008000;\">7.<\/span>\u00a0Default Converter &#8211;<\/strong> In previous version GSON is default integrated for JSON converter but in 2.x we don\u2019t have any default converter for JSON. We need to define GSON converter dependency in our project. We can use the following gradle import to define the sibling module:<\/p>\n<pre>compile 'com.squareup.retrofit2:converter-gson:2.1.0\u2019<\/pre>\n<h4><strong>Steps to Integrate Retrofit 2.x in our Android Studio Project<\/strong><\/h4>\n<p>Here are the main steps to integrate Retrofit in our project.<\/p>\n<p><span style=\"color: #008000;\"><strong>1.<\/strong><\/span> Add dependencies file in gradle: Firstly add these libraries in your build.gradle file in app module.<\/p>\n<pre>\/\/ Retrofit\r\ncompile 'com.squareup.retrofit2:retrofit:2.1.0'\r\n<\/pre>\n<pre> \/\/ JSON Parsing\r\ncompile 'com.google.code.gson:gson:2.6.1'\r\ncompile 'com.squareup.retrofit2:converter-gson:2.1.0'\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>2.<\/strong><\/span> Add Internet Permission in the AndroidManifest.xml: For network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre>&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\npackage=\"com.abhiandroid.retroiftexample\"&gt;\r\n\r\n&lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n\r\n&lt;application&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>3.<\/strong><\/span> POJO\/Model Class: For fetching response we need create POJO class that automatically parse the JSON data using Gson in background. We just need to create this POJO class. For creating POJO class first method is defining each and every variable by ourself and other best and fast method is using http:\/\/www.jsonschema2pojo.org\/ platform. By using this platform you can easily convert your JSON response to POJO class, for this we need to copy our JSON response and paste it in jsonschema2pojo and it will create setter getter methods as per our requirement.<br \/>\nSample POJO class:<\/p>\n<pre>public class SamplePojo {  \r\n\r\n    private int userId;\r\n    private String name;\r\n\r\n    public int getUserId() {\r\n        return userId;\r\n    }\r\n\r\n    public String getName() {\r\n        return name;\r\n    }\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>4.<\/strong><\/span> Add downloaded POJO class in your project.<\/p>\n<p><span style=\"color: #008000;\"><strong>5.<\/strong><\/span> API Interface : Now we need to create an Interface to define our different methods that will be used for network transactions. Here is the sample of API Interface.<\/p>\n<pre> public interface ApiInterface {\r\n\r\n\r\n\/\/ For POST request\r\n\r\n   @FormUrlEncoded \/\/ annotation used in POST type requests\r\n    @POST(\"\/retrofit\/register.php\")     \/\/ API's endpoints\r\n    Call&lt;SignUpResponse&gt; registration(@Field(\"name\") String name,\r\n                                      @Field(\"email\") String email);\/\/user_email and user_pass are the post parameters and SignUpResponse is a POJO class which receives the response of this API\r\n\r\n\r\n\/\/ for GET request\r\n\r\n    @GET(\"\/retrofit\/getuser.php\")\r\n        \/\/ API's endpoints\r\n    Call&lt;List&lt;UserListResponse&gt;&gt; getUsersList();\r\n\r\n\/\/ UserListResponse is POJO class to get the data from API, we use List&lt;UserListResponse&gt; in callback because the data in our API is starting from JSONArray\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>6.<\/strong><\/span> Creating the Retrofit Instance: For network requests with Retrofit we need to create instance using retrofit builder class and then configure it with base URL. Suppose we have to implement login API then we need to build retrofit instance, setting base url and create connection between our retrofit instance and API Interface. For this, its better to create a class in which we have a method that create the connection and then returns the API Interface object. You can create this Retrofit instance where you want to implement API but its better to create a common class\/method and use it where you want.<\/p>\n<pre> public class Api {\r\n    private static Retrofit retrofit = null;\r\n    public static ApiInterface getClient() {\r\n\r\n        \/\/ change your base URL\r\n        if (retrofit==null) {\r\n            retrofit = new Retrofit.Builder()\r\n                    .baseUrl(BASE_URL)\r\n                    .addConverterFactory(GsonConverterFactory.create())\r\n                    .build();\r\n        }\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = retrofit.create(ApiInterface.class);\r\n        return api; \/\/ return the APIInterface object\r\n    }\r\n\r\n}<\/pre>\n<h4><strong>Example Of Retrofit 2.x (Post Type) In Android Studio:<\/strong><\/h4>\n<p>Below is the example of Retrofit 2.x in which we have implement the POST type request. In this we are implementing sign up api. In this example firstly we create sign up page design with 3 EditText name, email and password and one sign up Button. After that in our MainActivity we are getting our EditText and Button and on click of sign up Button the data in EditText is validate and then we are implementing signup api to save the data in our database. After getting response from api we are displaying the message on the screen by using a Toast.<\/p>\n<p>Below you can download code, see final output and step by step explanation of example:<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/RetrofitExample\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-829\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-Post-Example-In-Android-Studio.gif\" alt=\"Retrofit Post Example In Android Studio\" width=\"172\" height=\"304\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create A New Project And Name It RetrofitExample.<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Open Gradle Scripts &gt; build.gradle and add Retrofit and RecyclerView Library dependency in it.<\/p>\n<pre> apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 26\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.retrofitexample\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 26\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n        testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    implementation fileTree(include: ['*.jar'], dir: 'libs')\r\n    implementation 'com.android.support:appcompat-v7:26.1.0'\r\n    \/\/ dependency for Retrofit\r\n    compile 'com.squareup.retrofit2:retrofit:2.1.0'\r\n    \/\/ JSON Parsing\r\n    compile 'com.google.code.gson:gson:2.6.1'\r\n    compile 'com.squareup.retrofit2:converter-gson:2.1.0'\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Add Internet Permission in the AndroidManifest.xml:<\/p>\n<p>For network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.retrofitexample\"&gt;\r\n\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:roundIcon=\"@mipmap\/ic_launcher_round\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity android:name=\".MainActivity\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Open res -&gt; layout -&gt; activity_main.xml (or) main.xml and add following code:<\/p>\n<p>In this step we create a RecyclerView in our XML file.<\/p>\n<pre> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"&gt;\r\n\r\n\r\n    &lt;ScrollView\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\"\r\n        android:scrollbars=\"none\"&gt;\r\n\r\n\r\n        &lt;LinearLayout\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:layout_gravity=\"center\"\r\n            android:orientation=\"vertical\"\r\n            android:padding=\"20dp\"&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/username\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Full Name\"\r\n                android:imeOptions=\"actionNext\"\r\n                android:inputType=\"text\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/email\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Email Address\"\r\n                android:imeOptions=\"actionNext\"\r\n                android:inputType=\"textEmailAddress\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;EditText\r\n                android:id=\"@+id\/password\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:backgroundTint=\"#000\"\r\n                android:hint=\"Password\"\r\n                android:imeOptions=\"actionDone\"\r\n                android:inputType=\"textPassword\"\r\n                android:paddingBottom=\"15dp\"\r\n                android:paddingLeft=\"5dp\"\r\n                android:singleLine=\"true\"\r\n                android:textColor=\"#000\"\r\n                android:textColorHint=\"#000\" \/&gt;\r\n\r\n\r\n            &lt;Button\r\n                android:id=\"@+id\/signUp\"\r\n                android:layout_width=\"match_parent\"\r\n                android:layout_height=\"wrap_content\"\r\n                android:layout_marginTop=\"10dp\"\r\n                android:backgroundTint=\"@color\/colorPrimary\"\r\n                android:text=\"Sign Up\"\r\n                android:textColor=\"#fff\"\r\n                android:textSize=\"17sp\" \/&gt;\r\n\r\n        &lt;\/LinearLayout&gt;\r\n    &lt;\/ScrollView&gt;\r\n&lt;\/RelativeLayout&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong><\/span> Create a new POJO class SignUpResponse.java in which we have setter\/getter method to get the data from API.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\npublic class SignUpResponse {\r\n\r\n    private String success;\r\n\r\n    private String message;\r\n    private Integer userid;\r\n\r\n    public String getSuccess() {\r\n        return success;\r\n    }\r\n\r\n    public void setSuccess(String success) {\r\n        this.success = success;\r\n    }\r\n\r\n    public String getMessage() {\r\n        return message;\r\n    }\r\n\r\n    public void setMessage(String message) {\r\n        this.message = message;\r\n    }\r\n\r\n    public Integer getUserid() {\r\n        return userid;\r\n    }\r\n\r\n    public void setUserid(Integer userid) {\r\n        this.userid = userid;\r\n    }\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 6:<\/strong><\/span> Create an Interface and name it ApiInterface.java and paste the following code in it.<\/p>\n<p>In this step we create an Interface in which we have registration post request method to send the data using api to our server.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\n\r\n\r\nimport retrofit2.Call;\r\nimport retrofit2.http.Field;\r\nimport retrofit2.http.FormUrlEncoded;\r\nimport retrofit2.http.POST;\r\n\r\npublic interface ApiInterface {\r\n\r\n    @FormUrlEncoded \/\/ annotation used in POST type requests\r\n    @POST(\"\/retrofit\/register.php\")\r\n        \/\/ API's endpoints\r\n    Call&lt;SignUpResponse&gt; registration(@Field(\"name\") String name,\r\n                                      @Field(\"email\") String email,\r\n                                      @Field(\"password\") String password,\r\n                                      @Field(\"logintype\") String logintype);\r\n\r\n    \/\/ In registration method @Field used to set the keys and String data type is representing its a string type value and callback is used to get the response from api and it will set it in our POJO class\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 7:<\/strong><\/span> Create a new Class Api.java and paste the following code in it.<\/p>\n<p>In this step we create a new class to set the Retrofit. In this class getClient method returns the Api Interface class object which we are using in our MainActivity.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport retrofit2.Retrofit;\r\nimport retrofit2.converter.gson.GsonConverterFactory;\r\n\r\n\r\npublic class Api {\r\n    private static Retrofit retrofit = null;\r\n    public static ApiInterface getClient() {\r\n\r\n        \/\/ change your base URL\r\n        if (retrofit==null) {\r\n            retrofit = new Retrofit.Builder()\r\n                    .baseUrl(\"http:\/\/mobileappdatabase.in\/\")\r\n                    .addConverterFactory(GsonConverterFactory.create())\r\n                    .build();\r\n        }\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = retrofit.create(ApiInterface.class);\r\n        return api; \/\/ return the APIInterface object\r\n    }\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 8:<\/strong><\/span> Now open app -&gt; java -&gt; package -&gt; MainActivity.java and add the below code.<\/p>\n<p>In this step Firstly we are getting reference of EditText and Button.After that we implement setOnClickListener event on Button and on click of sign up Button the data in EditText is validate and then we are implementing signup api to save the data in our database. After getting response from api we are displaying the message on the screen by using a Toast.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport android.Manifest;\r\nimport android.app.ProgressDialog;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.text.TextUtils;\r\nimport android.util.Log;\r\nimport android.view.View;\r\nimport android.widget.Button;\r\nimport android.widget.EditText;\r\nimport android.widget.Toast;\r\n\r\n\r\nimport retrofit2.Call;\r\nimport retrofit2.Callback;\r\nimport retrofit2.Response;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n    SignUpResponse signUpResponsesData;\r\n    EditText emailId, password, name;\r\n    Button signUp;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        \/\/ init the EditText and Button\r\n        name = (EditText) findViewById(R.id.username);\r\n        emailId = (EditText) findViewById(R.id.email);\r\n        password = (EditText) findViewById(R.id.password);\r\n        signUp = (Button) findViewById(R.id.signUp);\r\n        \/\/ implement setOnClickListener event on sign up Button\r\n        signUp.setOnClickListener(new View.OnClickListener() {\r\n            @Override\r\n            public void onClick(View view) {\r\n                \/\/ validate the fields and call sign method to implement the api\r\n                if (validate(name) &amp;&amp; validateEmail() &amp;&amp; validate(password)) {\r\n                    signUp();\r\n                }\r\n            }\r\n        });\r\n    }\r\n\r\n    private boolean validateEmail() {\r\n        String email = emailId.getText().toString().trim();\r\n\r\n        if (email.isEmpty() || !isValidEmail(email)) {\r\n            emailId.setError(\"Email is not valid.\");\r\n            emailId.requestFocus();\r\n            return false;\r\n        }\r\n\r\n        return true;\r\n    }\r\n\r\n    private static boolean isValidEmail(String email) {\r\n        return !TextUtils.isEmpty(email) &amp;&amp; android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();\r\n    }\r\n\r\n    private boolean validate(EditText editText) {\r\n        \/\/ check the lenght of the enter data in EditText and give error if its empty\r\n        if (editText.getText().toString().trim().length() &gt; 0) {\r\n            return true; \/\/ returns true if field is not empty\r\n        }\r\n        editText.setError(\"Please Fill This\");\r\n        editText.requestFocus();\r\n        return false;\r\n    }\r\n\r\n    private void signUp() {\r\n        \/\/ display a progress dialog\r\n        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);\r\n        progressDialog.setCancelable(false); \/\/ set cancelable to false\r\n        progressDialog.setMessage(\"Please Wait\"); \/\/ set message\r\n        progressDialog.show(); \/\/ show progress dialog\r\n\r\n        \/\/ Api is a class in which we define a method getClient() that returns the API Interface class object\r\n        \/\/ registration is a POST request type method in which we are sending our field's data\r\n        \/\/ enqueue is used for callback response and error\r\n        (Api.getClient().registration(name.getText().toString().trim(),\r\n                emailId.getText().toString().trim(),\r\n                password.getText().toString().trim(),\r\n                \"email\")).enqueue(new Callback&lt;SignUpResponse&gt;() {\r\n            @Override\r\n            public void onResponse(Call&lt;SignUpResponse&gt; call, Response&lt;SignUpResponse&gt; response) {\r\n                signUpResponsesData = response.body();\r\n                Toast.makeText(getApplicationContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();\r\n                progressDialog.dismiss();\r\n\r\n            }\r\n\r\n            @Override\r\n            public void onFailure(Call&lt;SignUpResponse&gt; call, Throwable t) {\r\n                Log.d(\"response\", t.getStackTrace().toString());\r\n                progressDialog.dismiss();\r\n\r\n            }\r\n        });\r\n    }\r\n\r\n\r\n}<\/pre>\n<h4><strong>Example Of Retrofit 2.x (GET Type) In Android Studio:<\/strong><\/h4>\n<p>Below is the example of Retrofit 2.x in which we have implement the GET type request. In this we are displaying a list of items by using RecyclerView. Firstly we declare a RecyclerView in our XML file and then get the reference of it in our Activity. After that we create POJO Class, API Interface, Retrofit builder and then implement the API in our onCreate method of MainActivity. After getting the success response from server we are calling our adapter to set the data in RecyclerView.<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/RetrofitExample\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-832\" src=\"\/programming\/wp-content\/uploads\/2018\/01\/Retrofit-GET-Example-In-Android-Studio.gif\" alt=\"Retrofit GET Example In Android Studio\" width=\"170\" height=\"302\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create A New Project And Name It RetrofitExample.<\/p>\n<p><span style=\"color: #008000;\"><strong>Step 2:<\/strong><\/span> Open Gradle Scripts &gt; build.gradle and add Retrofit and RecyclerView Library dependency in it.<\/p>\n<pre> apply plugin: 'com.android.application'\r\n\r\nandroid {\r\n    compileSdkVersion 26\r\n    defaultConfig {\r\n        applicationId \"com.abhiandroid.retrofitexample\"\r\n        minSdkVersion 15\r\n        targetSdkVersion 26\r\n        versionCode 1\r\n        versionName \"1.0\"\r\n        testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\r\n    }\r\n    buildTypes {\r\n        release {\r\n            minifyEnabled false\r\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r\n        }\r\n    }\r\n}\r\n\r\ndependencies {\r\n    implementation fileTree(include: ['*.jar'], dir: 'libs')\r\n    implementation 'com.android.support:appcompat-v7:26.1.0'\r\n    \/\/ dependency for Retrofit\r\n    compile 'com.squareup.retrofit2:retrofit:2.1.0'\r\n    \/\/ JSON Parsing\r\n    compile 'com.google.code.gson:gson:2.6.1'\r\n    compile 'com.squareup.retrofit2:converter-gson:2.1.0'\r\n    \/\/ dependency for RecyclerView\r\n    compile 'com.android.support:recyclerview-v7:24.1.1'\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Add Internet Permission in the AndroidManifest.xml:<\/p>\n<p>For network transactions we need to define Internet permission in our Manifest file.<\/p>\n<pre> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;manifest xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    package=\"com.abhiandroid.retrofitexample\"&gt;\r\n\r\n    &lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;\r\n    &lt;application\r\n        android:allowBackup=\"true\"\r\n        android:icon=\"@mipmap\/ic_launcher\"\r\n        android:label=\"@string\/app_name\"\r\n        android:roundIcon=\"@mipmap\/ic_launcher_round\"\r\n        android:supportsRtl=\"true\"\r\n        android:theme=\"@style\/AppTheme\"&gt;\r\n        &lt;activity android:name=\".MainActivity\"&gt;\r\n            &lt;intent-filter&gt;\r\n                &lt;action android:name=\"android.intent.action.MAIN\" \/&gt;\r\n\r\n                &lt;category android:name=\"android.intent.category.LAUNCHER\" \/&gt;\r\n            &lt;\/intent-filter&gt;\r\n        &lt;\/activity&gt;\r\n    &lt;\/application&gt;\r\n\r\n&lt;\/manifest&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Open res -&gt; layout -&gt; activity_main.xml (or) main.xml and add following code:<\/p>\n<p>In this step we create a RecyclerView in our XML file.<\/p>\n<pre> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"&gt;\r\n\r\n    &lt;android.support.v7.widget.RecyclerView\r\n        android:id=\"@+id\/recyclerView\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"match_parent\" \/&gt;\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong><\/span> Create a new XML file user_list_items.xml for item of RecyclerView and paste the following code in it.<\/p>\n<p>In this step we create a new xml file for item row in which we creates two TextView to show the data.<\/p>\n<pre> &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n\r\n&lt;LinearLayout android:layout_width=\"match_parent\"\r\n    android:layout_height=\"wrap_content\"\r\n    android:padding=\"6dp\"\r\n    android:gravity=\"center_vertical\"\r\n    android:background=\"#f2f2f2\"\r\n    android:orientation=\"vertical\"\r\n    xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"&gt;\r\n        &lt;!--\r\n        create Textview's for user name and email id\r\n        --&gt;\r\n        &lt;TextView\r\n            android:id=\"@+id\/name\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:text=\"Name:\"\r\n            android:textColor=\"@color\/colorPrimary\"\r\n            android:textSize=\"17sp\" \/&gt;\r\n\r\n\r\n        &lt;TextView\r\n            android:id=\"@+id\/email\"\r\n            android:layout_width=\"match_parent\"\r\n            android:layout_height=\"wrap_content\"\r\n            android:text=\"Email:\"\r\n            android:textColor=\"@color\/colorPrimary\"\r\n            android:textSize=\"16sp\" \/&gt;\r\n    &lt;View\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"1dp\"\r\n        android:layout_marginTop=\"2dp\"\r\n        android:layout_marginBottom=\"2dp\"\r\n        android:background=\"@color\/colorPrimary\"\/&gt;\r\n    &lt;\/LinearLayout&gt;<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 6:<\/strong><\/span> Create a new POJO class UserListResponse.java in which we have setter\/getter method to get the data from API.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\npublic class UserListResponse {\r\n\r\n    \/\/ POJO class to get the data from web api\r\nprivate String id;\r\nprivate String name;\r\nprivate String email;\r\nprivate String password;\r\nprivate String com_code;\r\nprivate String status;\r\nprivate String forgot;\r\nprivate Map&lt;String, Object&gt; additionalProperties = new HashMap&lt;String, Object&gt;();\r\n\r\npublic String getId() {\r\nreturn id;\r\n}\r\n\r\npublic void setId(String id) {\r\nthis.id = id;\r\n}\r\n\r\npublic String getName() {\r\nreturn name;\r\n}\r\n\r\npublic void setName(String name) {\r\nthis.name = name;\r\n}\r\n\r\npublic String getEmail() {\r\nreturn email;\r\n}\r\n\r\npublic void setEmail(String email) {\r\nthis.email = email;\r\n}\r\n\r\npublic String getPassword() {\r\nreturn password;\r\n}\r\n\r\npublic void setPassword(String password) {\r\nthis.password = password;\r\n}\r\n\r\npublic String getCom_code() {\r\nreturn com_code;\r\n}\r\n\r\npublic void setCom_code(String com_code) {\r\nthis.com_code = com_code;\r\n}\r\n\r\npublic String getStatus() {\r\nreturn status;\r\n}\r\n\r\npublic void setStatus(String status) {\r\nthis.status = status;\r\n}\r\n\r\npublic String getForgot() {\r\nreturn forgot;\r\n}\r\n\r\npublic void setForgot(String forgot) {\r\nthis.forgot = forgot;\r\n}\r\n\r\npublic Map&lt;String, Object&gt; getAdditionalProperties() {\r\nreturn this.additionalProperties;\r\n}\r\n\r\npublic void setAdditionalProperty(String name, Object value) {\r\nthis.additionalProperties.put(name, value);\r\n}\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 7:<\/strong><\/span> Create an Interface and name it ApiInterface.java and paste the following code in it.<\/p>\n<p>In this step we create an Interface in which we have getUserList method to get the data from web api.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit2.Call;\r\nimport retrofit2.http.GET;\r\n\r\npublic interface ApiInterface {\r\n\r\n    @GET(\"\/retrofit\/getuser.php\")\r\n        \/\/ API's endpoints\r\n    Call&lt;List&lt;UserListResponse&gt;&gt; getUsersList();\r\n\r\n\/\/ UserListResponse is POJO class to get the data from API, we use List&lt;UserListResponse&gt; in callback because the data in our API is starting from JSONArray\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 8:<\/strong><\/span> Create a new Class Api.java and paste the following code in it.<\/p>\n<p>In this step we create a new class to set the Retrofit builder. In this class getClient method returns the Api Interface class object which we are using in our MainActivity.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport retrofit2.Retrofit;\r\nimport retrofit2.converter.gson.GsonConverterFactory;\r\n\r\n\/**\r\n * Created by AbhiAndroid\r\n *\/\r\npublic class Api {\r\n    private static Retrofit retrofit = null;\r\n    public static ApiInterface getClient() {\r\n\r\n        \/\/ change your base URL\r\n        if (retrofit==null) {\r\n            retrofit = new Retrofit.Builder()\r\n                    .baseUrl(\"http:\/\/mobileappdatabase.in\/\")\r\n                    .addConverterFactory(GsonConverterFactory.create())\r\n                    .build();\r\n        }\r\n        \/\/Creating object for our interface\r\n        ApiInterface api = retrofit.create(ApiInterface.class);\r\n        return api; \/\/ return the APIInterface object\r\n    }\r\n\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 9:<\/strong><\/span> Now open app -&gt; java -&gt; package -&gt; MainActivity.java and add the below code.<\/p>\n<p>In this step Firstly we get the reference of RecyclerView in our Activity. After that we implement the API in our onCreate method. Finally After getting the success response from server we are calling our adapter to set the data in RecyclerView. In this step we show a Progress dialog while implementing API and after getting response or error we dismiss it.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport android.app.ProgressDialog;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.support.v7.widget.LinearLayoutManager;\r\nimport android.support.v7.widget.RecyclerView;\r\nimport android.util.Log;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.List;\r\n\r\nimport retrofit2.Call;\r\nimport retrofit2.Callback;\r\nimport retrofit2.Response;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n    RecyclerView recyclerView;\r\n    List&lt;UserListResponse&gt; userListResponseData;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);\r\n        getUserListData(); \/\/ call a method in which we have implement our GET type web API\r\n    }\r\n\r\n    private void getUserListData() {\r\n        \/\/ display a progress dialog\r\n        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);\r\n        progressDialog.setCancelable(false); \/\/ set cancelable to false\r\n        progressDialog.setMessage(\"Please Wait\"); \/\/ set message\r\n        progressDialog.show(); \/\/ show progress dialog\r\n\r\n\r\n        (Api.getClient().getUsersList()).enqueue(new Callback&lt;List&lt;UserListResponse&gt;&gt;() {\r\n            @Override\r\n            public void onResponse(Call&lt;List&lt;UserListResponse&gt;&gt; call, Response&lt;List&lt;UserListResponse&gt;&gt; response) {\r\n                Log.d(\"responseGET\", response.body().get(0).getName());\r\n                progressDialog.dismiss(); \/\/dismiss progress dialog\r\n                userListResponseData = response.body();\r\n                setDataInRecyclerView();\r\n            }\r\n\r\n            @Override\r\n            public void onFailure(Call&lt;List&lt;UserListResponse&gt;&gt; call, Throwable t) {\r\n                \/\/ if error occurs in network transaction then we can get the error in this method.\r\n                Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_LONG).show();\r\n                progressDialog.dismiss(); \/\/dismiss progress dialog\r\n            }\r\n        });\r\n    }\r\n\r\n    private void setDataInRecyclerView() {\r\n        \/\/ set a LinearLayoutManager with default vertical orientation\r\n        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);\r\n        recyclerView.setLayoutManager(linearLayoutManager);\r\n        \/\/ call the constructor of UsersAdapter to send the reference and data to Adapter\r\n        UsersAdapter usersAdapter = new UsersAdapter(MainActivity.this, userListResponseData);\r\n        recyclerView.setAdapter(usersAdapter); \/\/ set the Adapter to RecyclerView\r\n    }\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 10:<\/strong><\/span> Create a new class UsersAdapter.java inside package and add the following code.<\/p>\n<p>In this step we create a UsersAdapter class and extends RecyclerView.Adapter class with View Holder in it. After that we implement the overrided methods and create a constructor for getting the data from Activity. In this custom Adapter two methods are more important first is onCreateViewHolder in which we inflate the layout item xml and pass it to View Holder and other is onBindViewHolder in which we set the data in the view\u2019s with the help of View Holder. Finally we implement the setOnClickListener event on itemview and on click of item we display the name of the user with the help of Toast.<\/p>\n<pre> package com.abhiandroid.retrofitexample;\r\n\r\nimport android.content.Context;\r\nimport android.support.v7.widget.RecyclerView;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.TextView;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.List;\r\n\r\n\r\n\r\npublic class UsersAdapter extends RecyclerView.Adapter&lt;UsersAdapter.UsersViewHolder&gt; {\r\n\r\n    Context context;\r\n    List&lt;UserListResponse&gt; userListResponseData;\r\n\r\n    public UsersAdapter(Context context, List&lt;UserListResponse&gt; userListResponseData) {\r\n        this.userListResponseData = userListResponseData;\r\n        this.context = context;\r\n    }\r\n\r\n    @Override\r\n    public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n\r\n        View view = LayoutInflater.from(context).inflate(R.layout.users_list_items, null);\r\n        UsersViewHolder usersViewHolder = new UsersViewHolder(view);\r\n        return usersViewHolder;\r\n    }\r\n\r\n    @Override\r\n    public void onBindViewHolder(UsersViewHolder holder, final int position) {\r\n        \/\/ set the data\r\n        holder.name.setText(\"Name: \" + userListResponseData.get(position).getName());\r\n        holder.email.setText(\"Email: \" + userListResponseData.get(position).getEmail());\r\n        \/\/ implement setONCLickListtener on itemView\r\n        holder.itemView.setOnClickListener(new View.OnClickListener() {\r\n            @Override\r\n            public void onClick(View view) {\r\n                \/\/ display a toast with user name\r\n                Toast.makeText(context, userListResponseData.get(position).getName(), Toast.LENGTH_SHORT).show();\r\n            }\r\n        });\r\n    }\r\n\r\n    @Override\r\n    public int getItemCount() {\r\n        return userListResponseData.size(); \/\/ size of the list items\r\n    }\r\n\r\n    class UsersViewHolder extends RecyclerView.ViewHolder {\r\n        \/\/ init the item view's\r\n        TextView name, email;\r\n\r\n        public UsersViewHolder(View itemView) {\r\n            super(itemView);\r\n            \/\/ get the reference of item view's\r\n            name = (TextView) itemView.findViewById(R.id.name);\r\n            email = (TextView) itemView.findViewById(R.id.email);\r\n        }\r\n    }\r\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In Android, Retrofit is a REST Client for Java and Android by Square inc under Apache 2.0 license. Its a simple network library that used for network transactions. By using this library we can seamlessly capture JSON response from web service\/web API. It&#8217;s easy and fast library to retrieve and upload the data(JSON or any &hellip; <a href=\"https:\/\/abhiandroid.com\/programming\/retrofit\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Retrofit Tutorial With Example In Android Studio [Step by Step]<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-808","page","type-page","status-publish","hentry"],"psp_head":"<title>Retrofit Tutorial With Example In Android Studio [Step by Step] \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Read complete retrofit rest webservice step by step tutorial with example in Android Studio. The example include POST and GET type request from server. Android, Retrofit is a REST Client for Java and Android by Square inc under Apache 2.0 license.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/programming\/retrofit\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/808","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/comments?post=808"}],"version-history":[{"count":3,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/808\/revisions"}],"predecessor-version":[{"id":984,"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/pages\/808\/revisions\/984"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/programming\/wp-json\/wp\/v2\/media?parent=808"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}