Skip to main content

Demo Retrofit New

URL:- http://pratikbutani.x10.mx/json_data.json

1 ) Create RetrofitClient(Base URL Class)
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;

public class RetrofitClient {

    public static final String API_BASE_URL = "http://pratikbutani.x10.mx/";

    public static Retrofit retrofit=null;

    public static Retrofit getApiClient()
    {
        if(retrofit==null)
        {
            retrofit=new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory
                    .create()).build();
        return retrofit;
    }

}


2 ) Create Retrofit ApiInterface Class(End URL Class)
import com.example.discusit.retrofitdemo.model.Contact;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface
{
    @GET("json_data.json")
    Call<Contact>getContactData();
}

3 ) Create Require Model Class

    A) Contact
       import com.google.gson.annotations.Expose;
       import com.google.gson.annotations.SerializedName;
       import java.util.List;

       public class Contact {
       @SerializedName("contacts")
       @Expose       private List<Contact_> contacts = null;

       public List<Contact_> getContacts() {
        return contacts;
       }

       public void setContacts(List<Contact_> contacts) {
        this.contacts = contacts;
      }
    }

  B) Contact_
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Contact_ {
    @SerializedName("id")
    @Expose    private String id;
    @SerializedName("name")
    @Expose    private String name;
    @SerializedName("email")
    @Expose    private String email;
    @SerializedName("address")
    @Expose    private String address;
    @SerializedName("gender")
    @Expose    private String gender;
    @SerializedName("profile_pic")
    @Expose    private String profilePic;
    @SerializedName("phone")
    @Expose    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 getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }

    public Phone getPhone() {
        return phone;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;

    }
}

C) Phone

   import com.google.gson.annotations.Expose;
   import com.google.gson.annotations.SerializedName;

public class Phone {
    @SerializedName("mobile")
    @Expose    private String mobile;
    @SerializedName("home")
    @Expose    private String home;
    @SerializedName("office")
    @Expose    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;
    }
}   


4 ) Recyclerview Adatper Class

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.discusit.retrofitdemo.R;
import com.example.discusit.retrofitdemo.model.Contact_;
import com.example.discusit.retrofitdemo.model.Phone;

import java.util.ArrayList;

public class DataAdapter extends RecyclerView.Adapter {
    private int mViewItem = 1;
    private String mReminderId;
    private Context mActivity;
    private LayoutInflater mLayoutInflater;
    private SharedPreferences.Editor ReminderId;
    private ArrayList<Phone> mArrPhoneModel = new ArrayList<>();
    private ArrayList<Contact_> mArrContactModel = new ArrayList<>();


    public DataAdapter(Context mActivity, ArrayList<Contact_> mArrContactModel)
    {
        this.mActivity = mActivity;
        this.mArrContactModel=mArrContactModel;
        mLayoutInflater = LayoutInflater.from(mActivity);
    }

    public DataAdapter(Context mActivity, ArrayList<Contact_> mArrContactModel, ArrayList<Phone> mArrPhoneModel)
    {
        this.mActivity = mActivity;
        this.mArrContactModel=mArrContactModel;
        this.mArrPhoneModel=mArrPhoneModel;
        mLayoutInflater = LayoutInflater.from(mActivity);
    }

    @Override    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View view = mLayoutInflater.inflate(R.layout.row_data, parent, false);
        return new CustomViewHolder(view);
    }

    @Override    public int getItemViewType(int position)
    {
        return mArrContactModel.get(position) != null ? mViewItem : 0;
    }

    @Override    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)
    {
        try {

            final Contact_ contactModel = mArrContactModel.get(position);
            final Phone phoneModel= contactModel.getPhone();

            ((CustomViewHolder) holder).mTextId.setText(contactModel.getId());
            ((CustomViewHolder) holder).mTextName.setText(contactModel.getName());
            ((CustomViewHolder) holder).mTextCountry.setText(contactModel.getEmail());
            ((CustomViewHolder) holder).mTextCity.setText(contactModel.getAddress());
            ((CustomViewHolder) holder).mTextMobile.setText(phoneModel.getMobile());
            ((CustomViewHolder) holder).mTextHome.setText(phoneModel.getHome());
            ((CustomViewHolder) holder).mTextOffice.setText(phoneModel.getOffice());
        }

        catch (Exception exception)
        {
            Log.e("Error:>>>>>>", String.valueOf(exception));
        }

    }

    @Override    public int getItemCount()
    {
        return mArrContactModel.size();
    }

    public static class CustomViewHolder extends RecyclerView.ViewHolder
    {
        private TextView mTextId, mTextName,mTextCountry,mTextCity,mTextMobile,mTextHome,mTextOffice;
        public CustomViewHolder(View view)
        {
            super(view);
            mTextId = (TextView) view.findViewById(R.id.text_row_data_id);
            mTextName = (TextView) view.findViewById(R.id.text_row_data_name);
            mTextCountry= (TextView) view.findViewById(R.id.text_row_data_country);
            mTextCity= (TextView) view.findViewById(R.id.text_row_data_city);
            mTextMobile= (TextView) view.findViewById(R.id.text_row_data_mobile);
            mTextHome=(TextView)view.findViewById(R.id.text_row_data_home);
            mTextOffice=(TextView)view.findViewById(R.id.text_row_data_office);
        }
    }
}

5 ) Main Activity

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.example.discusit.retrofitdemo.adapter.DataAdapter;
import com.example.discusit.retrofitdemo.model.Contact;
import com.example.discusit.retrofitdemo.model.Contact_;
import com.example.discusit.retrofitdemo.webservices.ApiInterface;
import com.example.discusit.retrofitdemo.webservices.RetrofitClient;

import java.io.IOException;
import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity
{
    private String mEndUrl;
    private DataAdapter dataAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManagerList;
    private String TAG = MainActivity.class.getSimpleName();
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setIds();
        setLayout();
        callDemoAPI();
    }

    //set Ids For The Views    private void setIds()
    {
        mRecyclerView=findViewById(R.id.recycle_Activity_main);
    }

    // Set Layout For Recycler View
    private void setLayout()
    {
//        dataAdapter = new DataAdapter(mActivity,mArrSubFoldersListModel , this);        callDemoAPI();
    }
    private void callDemoAPI()
    {
        new MainActivity.RetrofitAyncTask().execute(this);
    }


    private class RetrofitAyncTask extends AsyncTask<Context, Void, ArrayList<Contact_>> {

        private String TAG = MainActivity.RetrofitAyncTask.class.getSimpleName();
        private Context contx;

        @Override        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override        protected ArrayList<Contact_> doInBackground(Context... params) {
            Log.e(TAG, "processing http request in async task using retrofit");
            contx = (Context) params[0];

            //create service which is implementation of CouponApi interface by passing it to retrofit object            ApiInterface couponService = RetrofitClient.getApiClient().create(ApiInterface.class);
            //call api method which returns call object            Call<Contact> call = couponService.getContactData();

            try {
                //call the api synchronously as this is part of back ground thread already with AsncTask                Response<Contact> rp  =  call.execute();
                return (ArrayList<Contact_>) rp.body().getContacts();
            } catch (IOException e) {
                Log.e(TAG, "error in getting response from service using retrofit");
            }

            return null;
        }

        @Override        protected void onPostExecute(ArrayList<Contact_> result) {
            super.onPostExecute(result);

            if (result != null) {
                Log.e(TAG, "populate recyclerview Linear in UI after response from service using retrofit");

                //populate recyclerview grid from retrofit response result
                DataAdapter couponAdapter = new DataAdapter(contx,result);
                mRecyclerView.setHasFixedSize(true);
                mLinearLayoutManagerList = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
                mRecyclerView.setLayoutManager(mLinearLayoutManagerList);
                mRecyclerView.setAdapter(couponAdapter);
            }
        }
    }
}


6 ) Activity Main.XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_Activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</RelativeLayout>
    
7 )row.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_id"
        tools:text="id"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_name"
        tools:text="name"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_country"
        tools:text="country"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_city"
        tools:text="city"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_mobile"
        tools:text="mobile"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_row_data_home"
        tools:text="hoem"
        android:textSize="20sp"
        android:textStyle="bold"
        />
    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text_row_data_office"
    tools:text="office"
    android:textSize="20sp"
    android:textStyle="bold"
    />
</LinearLayout>

Notes : 

1 ) Require Libraries


//App Design
implementation 'com.android.support:design:27.1.0'
//AppCompact
implementation 'com.android.support:appcompat-v7:27.1.1'
// Retrofit & OkHttp
implementation 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
implementation 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
//Recyclerview
implementation 'com.android.support:recyclerview-v7:27.1.1'

// Output 

{
    "contacts": [
        {
                "id": "c200",
                "name": "Pratik Butani",
                "email": "pratik13butani@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
  "profile_pic" : "http://lorempixel.com/100/100/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/105/105/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c202",
                "name": "Leonardo Dicaprio",
                "email": "leonardo_dicaprio@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/110/110/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c203",
                "name": "John Wayne",
                "email": "john_wayne@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/120/120/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c204",
                "name": "Angelina Jolie",
                "email": "angelina_jolie@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "female",
                "profile_pic" : "http://lorempixel.com/115/115/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c205",
                "name": "Dido",
                "email": "dido@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "female",
                "profile_pic" : "http://lorempixel.com/125/125/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c206",
                "name": "Adele",
                "email": "adele@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "female",
                "profile_pic" : "http://lorempixel.com/122/122/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c207",
                "name": "Hugh Jackman",
                "email": "hugh_jackman@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/130/130/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c208",
                "name": "Will Smith",
                "email": "will_smith@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/125/125/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c209",
                "name": "Clint Eastwood",
                "email": "clint_eastwood@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/135/135/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c2010",
                "name": "Barack Obama",
                "email": "barack_obama@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/140/140/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c2011",
                "name": "Kate Winslet",
                "email": "kate_winslet@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "female",
                "profile_pic" : "http://lorempixel.com/150/150/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c2012",
                "name": "Eminem",
                "email": "eminem@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "profile_pic" : "http://lorempixel.com/160/160/",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        }
    ]
}

Comments

Popular posts from this blog

Post data with retrofit

1 ) Retrofit Client Class public class RetrofitClient { private static final String AUTH = "Basic " + Base64. encodeToString (( "belalkhan:123456" ).getBytes(), Base64. NO_WRAP ); private static final String BASE_URL = "http://simplifiedlabs.xyz/MyApi/public/" ; private static RetrofitClient mInstance ; private Retrofit retrofit ; private RetrofitClient() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .addHeader( "Authorization" , AUTH ) .meth...

Android MVVM (Model View ViewModel) Design Pattern

DataBinding Pdf Link:-   https://drive.google.com/open?id=1uL0xK9EktcEWOke5vqUqp-rgqpA1ARR3 DataBinding References : -  https://www.youtube.com/watch?v=v4XO_y3RErI Steps for applying MVVM design pattern to Android Project  1 ) Applying the changes in build.gradle (App Level) file      android {     compileSdkVersion 27     defaultConfig {         applicationId "com.credencys.databindingwithrecyclerview"         minSdkVersion 15         targetSdkVersion 27         versionCode 1         versionName "1.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled false             proguardFiles ge...

Complex Retrofit Class With Database

URL:-  http://www.mocky.io/v2/ 5b936d6f33000011002061d3 1 )   Create   RetrofitClient(Base URL Class) import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; public class RetrofitClient { //http://www.mocky.io/v2/5b936d6f33000011002061d3 public static final String API_BASE_URL = "http://www.mocky.io/v2/" ; public static Retrofit retrofit = null ; public static Retrofit getApiClient() { if ( retrofit == null ) { retrofit = new Retrofit.Builder().baseUrl( API_BASE_URL ).addConverterFactory(GsonConverterFactory . create ()).build(); } return retrofit ; } } 2 ) Create Retrofit ApiInterface Class(End URL Class) import com.example.discusit.complexretrofitdemo.model.Data; import retrofit2.Call; import retrofit2.http. GET ; public interface ApiInterface { @GET ( "5b936d6f33000011002061d3" ) Call<Data> getData(); } 3 ) Create Require Model Clas...