Skip to main content

Retrofit Simple Example || Bind Data in Recycler View with full Source code | Android Studio

What is Retrofit?


Retrofit is REST client for Android as well as JAVA by Square

Retrofit easily retrieve and  upload JSON by using REST based web service.

You can also configure a converter which is used for the data serialization.

Generally for JSON we can use GSON or you can also add your own or custom converter to process other protocols or XML.

In most case Retrofit uses the OKHTTP library for HTTP Request.


For using Retrofit basically we need three classes
  • Model Class
  • Interface
  • RetrofitBuilder class

Let's start the code :

First of all add following permission to your AndroidManifest.xml file.

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

Add following dependencies to your build.gradle file.

 compile 'com.google.code.gson:gson:2.6.2'  
 compile 'com.squareup.retrofit2:retrofit:2.0.2'  
 compile 'com.squareup.retrofit2:converter-gson:2.0.2'  

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:id="@+id/parentLayout"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:fitsSystemWindows="true"  
   tools:context=".Activity.MainActivity">  
   <android.support.v4.widget.SwipeRefreshLayout  
     android:id="@+id/swipe_refresh"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
   <android.support.v7.widget.RecyclerView  
     android:id="@+id/mRecyclerView"  
     android:layout_width="fill_parent"  
     android:layout_height="match_parent"/>  
   </android.support.v4.widget.SwipeRefreshLayout>  
 </android.support.design.widget.CoordinatorLayout>  

layout_root_view.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:orientation="vertical">  
   <RelativeLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="5dp"  
     >  
     <TextView  
       android:id="@+id/act_main_name"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:layout_marginLeft="10dp"  
       android:text="Hardik Lakhani"  
       android:textColor="@color/colorPrimary"  
       android:textStyle="bold"  
       android:textSize="30sp"  
       />  
     <TextView  
       android:id="@+id/act_main_id"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentRight="true"  
       android:text="C1362"  
       android:gravity="right"  
       android:layout_marginRight="10dp"  
       android:layout_marginTop="5dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp" />  
     <TextView  
       android:id="@+id/act_main_gender"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentRight="true"  
       android:text="MALE"  
       android:gravity="right"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_id"  
       android:layout_marginTop="5dp"  
       />  
     <TextView  
       android:id="@+id/act_main_email"  
       android:layout_width="250dp"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:text="imhardiklakhani@gmail.com"  
       android:gravity="left"  
       android:layout_marginLeft="10dp"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_name"  
       android:layout_marginTop="5dp"  
       />  
     <TextView  
       android:id="@+id/act_main_address"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:text="xx-xx-xxxx,x - street, x - India"  
       android:gravity="left"  
       android:layout_marginLeft="10dp"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_email"  
       android:layout_marginTop="5dp"  
       />  
     <TextView  
       android:id="@+id/act_main_mobile"  
       android:layout_width="250dp"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:text="9099968325"  
       android:gravity="left"  
       android:layout_marginLeft="10dp"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_address"  
       android:layout_marginTop="5dp"  
       />  
     <TextView  
       android:id="@+id/act_main_home"  
       android:layout_width="250dp"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:text="8128828825"  
       android:gravity="left"  
       android:layout_marginLeft="10dp"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_mobile"  
       android:layout_marginTop="5dp"  
       />  
     <TextView  
       android:id="@+id/act_main_office"  
       android:layout_width="250dp"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:text="0281-22882255"  
       android:gravity="left"  
       android:layout_marginLeft="10dp"  
       android:layout_marginRight="10dp"  
       android:textColor="@color/colorPrimary"  
       android:textSize="18sp"  
       android:layout_below="@+id/act_main_home"  
       android:layout_marginTop="5dp"  
       />  
   </RelativeLayout>  
   <View  
     android:layout_width="match_parent"  
     android:layout_height="1dp"  
     android:layout_margin="3dp"  
     android:background="@color/colorPrimaryDark"  
     />  
 </LinearLayout>  

MainActivity.java

 public class MainActivity extends AppCompatActivity {  
   private View parentView;  
   private ArrayList<Contact> contactList;  
   private MyRecyclerAdapter adapter;  
   private SwipeRefreshLayout mSwipeToRefresh;  
   private RecyclerView recyclerView;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     contactList = new ArrayList<>();  
     parentView = findViewById(R.id.parentLayout);  
     mSwipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);  
     recyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);  
     loadData();  
     mSwipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {  
       @Override  
       public void onRefresh() {  
         refreshItem();  
       }  
       private void refreshItem() {  
         loadData();  
         itemLoadComplete();  
       }  
       private void itemLoadComplete() {  
         mSwipeToRefresh.setRefreshing(false);  
       }  
     });  
   }  
   public boolean isNetworkAvailable(final Context context) {  
     return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;  
   }  
   public void loadData(){  
    if(isNetworkAvailable(MainActivity.this)) {  
      mSwipeToRefresh.setRefreshing(true);  
      ApiService api = RetroClient.getApiService();  
      Call<ContactList> call = api.getMyJSON();  
      call.enqueue(new Callback<ContactList>() {  
        @Override  
        public void onResponse(Call<ContactList> call, Response<ContactList> response) {  
          mSwipeToRefresh.setRefreshing(false);  
          if (response.isSuccessful()) {  
            contactList = response.body().getContacts();  
            adapter = new MyRecyclerAdapter(MainActivity.this, contactList);  
            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));  
            recyclerView.setAdapter(adapter);  
          } else {  
            Snackbar.make(parentView, "Something Wrong..", Snackbar.LENGTH_LONG).show();  
          }  
        }  
        @Override  
        public void onFailure(Call<ContactList> call, Throwable t) {  
        }  
      });  
    }  
     else {  
      Toast.makeText(this, "No Internet Connection Available ", Toast.LENGTH_SHORT).show();  
    }  
   }  
 }  

Contact.java

 import android.provider.ContactsContract;  
 /**  
  * Created by Hardik Lakhani  
  */  
 public class Contact {  
   private String id;  
   private String name;  
   private String email;  
   private String address;  
   private String gender;  
   private String profile_pic;  
   private Phone phone;  
   public String getId() {  
     return id;  
   }  
   public void setId(String id) {  
     this.id = id;  
   }  
   public String getName() {  
     return name;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   public String getEmail() {  
     return email;  
   }  
   public void setEmail(String email) {  
     this.email = email;  
   }  
   public String getAddress() {  
     return address;  
   }  
   public void setAddress(String address) {  
     this.address = address;  
   }  
   public String getGender() {  
     return gender;  
   }  
   public void setGender(String gender) {  
     this.gender = gender;  
   }  
   public String getProfile_pic() {  
     return profile_pic;  
   }  
   public void setProfile_pic(String profile_pic) {  
     this.profile_pic = profile_pic;  
   }  
   public Phone getPhone() {  
     return phone;  
   }  
   public void setPhone(Phone phone) {  
     this.phone = phone;  
   }  
   public class Phone{  
     private String mobile;  
     private String home;  
     private String office;  
     public String getMobile() {  
       return mobile;  
     }  
     public void setMobile(String mobile) {  
       this.mobile = mobile;  
     }  
     public String getHome() {  
       return home;  
     }  
     public void setHome(String home) {  
       this.home = home;  
     }  
     public String getOffice() {  
       return office;  
     }  
     public void setOffice(String office) {  
       this.office = office;  
     }  
   }  
 }  

ContactList.java

 import java.util.ArrayList;  
 public class ContactList {  
   private ArrayList<Contact> contacts = new ArrayList<>();  
   public ArrayList<Contact> getContacts() {  
     return contacts;  
   }  
   public void setContacts(ArrayList<Contact> contacts) {  
     this.contacts = contacts;  
   }  
 }  

ApiService.java

 import retrofit2.Call;  
 import retrofit2.http.GET;  
 public interface ApiService {  
   @GET("contact/contact.json")  
   Call<ContactList> getMyJSON();  
 }  

MyRecyclerAdapter.java

 import android.content.Context;  
 import android.support.v7.widget.RecyclerView;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.TextView;  
 import java.util.ArrayList;  
 /**  
  * Created by Hardik Lakhani  
  */  
 public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.View_Holder> {  
   ArrayList<Contact> list;  
   Context context;  
   public MyRecyclerAdapter(Context context, ArrayList<Contact> list) {  
     this.context = context;  
     this.list = list;  
   }  
   @Override  
   public View_Holder onCreateViewHolder(ViewGroup parent, int viewType) {  
     View v;  
     v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_root_view, parent, false);  
     View_Holder view_holder = new View_Holder(v);  
     return view_holder;  
   }  
   @Override  
   public void onBindViewHolder(View_Holder holder, int position) {  
     holder.tv_id.setText(list.get(position).getId());  
     holder.tv_name.setText(list.get(position).getName());  
     holder.tv_email.setText(list.get(position).getEmail());  
     holder.tv_address.setText(list.get(position).getAddress());  
     holder.tv_gender.setText(list.get(position).getGender());  
     holder.tv_mobile.setText(list.get(position).getPhone().getMobile());  
     holder.tv_home.setText(list.get(position).getPhone().getHome());  
     holder.tv_office.setText(list.get(position).getPhone().getOffice());  
   }  
   @Override  
   public void onAttachedToRecyclerView(RecyclerView recyclerView) {  
     super.onAttachedToRecyclerView(recyclerView);  
   }  
   @Override  
   public int getItemCount() {  
     return list.size();  
   }  
   public class View_Holder extends RecyclerView.ViewHolder {  
     TextView tv_id;  
     TextView tv_name;  
     TextView tv_email;  
     TextView tv_address;  
     TextView tv_gender;  
     TextView tv_mobile;  
     TextView tv_office;  
     TextView tv_home;  
     public View_Holder(View itemView) {  
       super(itemView);  
       tv_id = (TextView)itemView.findViewById(R.id.act_main_id);  
       tv_name = (TextView)itemView.findViewById(R.id.act_main_name);  
       tv_email = (TextView)itemView.findViewById(R.id.act_main_email);  
       tv_address = (TextView)itemView.findViewById(R.id.act_main_address);  
       tv_gender = (TextView)itemView.findViewById(R.id.act_main_gender);  
       tv_mobile = (TextView)itemView.findViewById(R.id.act_main_mobile);  
       tv_home = (TextView)itemView.findViewById(R.id.act_main_home);  
       tv_office = (TextView)itemView.findViewById(R.id.act_main_office);  
     }  
   }  
 }  

RetroClient.java

 import android.text.StaticLayout;  
 import retrofit2.Retrofit;  
 import retrofit2.converter.gson.GsonConverterFactory;  
 /**  
  * Created by Hardik Lakhani  
  */  
 public class RetroClient {  
   private static final String ROOT_URL = "http://hardik.coolpage.biz/";  
   private static Retrofit getRetrofitInstance(){  
     return new Retrofit.Builder().baseUrl(ROOT_URL).addConverterFactory(GsonConverterFactory.create()).build();  
   }  
   public static ApiService getApiService(){  
     return getRetrofitInstance().create(ApiService.class);  
   }  
 }  


That's it..


Run your Application with Active internet Connection.

Comments

Post a Comment

Popular posts from this blog

Tri-States | Indeterminate Checkbox Android

Sometimes it is required to implement checkbox with 3 states Unchecked Checked Indeterminate So here is a simple example of how to implement Tri-States or you can say Indeterminate Checkbox Android First of all, make a custom class which is extend Checkbox import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.AppCompatCheckBox import com.android.tristatescheckbox.R class TriStatesCheckBox : AppCompatCheckBox { private var state = 0 constructor ( context: Context ?) : super ( context ) { init () } constructor ( context: Context ?, attrs: AttributeSet ?) : super ( context , attrs ) { init () } constructor ( context: Context ?, attrs: AttributeSet ?, defStyleAttr: Int ) : super ( context , attrs , defStyleAttr ) { init () } private fun init () { state = UNCHECKED...

API Level in Android

Android Version Released API Level Name Build Version Code Android 7.1 December 2016 25 Nougat Android.OS.BuildVersionCodes.NMr1 Android 7.0 August 2016 24 Nougat Android.OS.BuildVersionCodes.N Android 6.0 August 2015 23 Marshmallow Android.OS.BuildVersionCodes.M Android 5.1 March 2015 22 Lollipop Android.OS.BuildVersionCodes.LollipopMr1 Android 5.0 November 2014 21 Lollipop Android.OS.BuildVersionCodes.Lollipop Android 4.4W June 2014 20 Kitkat Watch Android.OS.Bui...

HORIZONTAL FLIP ANIMATION: VIEW PAGER TRANSFORMATION ANIMATION ANDROID

Here I am sharing you a View Pager Transformation Animation Class By Which you can give a transformation animation to you view Pager First of all, create a simple view pager example. If you don't know how to create an example for simple view pager then click below link for creating simple view pager example in android Simple View Pager Example in Android Copy below class and Paste into your project Set Page Transformer to your view pager like below viewpager.setPageTransformer(true, new HorizontalFlip Transformation ()); That's It you're done.