Introduction to Retofit 2 in Android | Set 1
I have divided it into 3 parts. I am assuming the reader has basic knowledge of Android and Java.
What is RetoFit 2?
Retrofit 2 is a type-safe REST client built by Square for Android and Java which intends to make it simpler to expand RESTful web services. Retrofit 2 uses OkHttp as the systems administration layer and is based over it. Retrofit naturally serializes the JSON reaction utilizing a POJO (PlainOldJavaObject) which must be characterized in cutting edge for the JSON Structure. To serialize JSON we require a converter to change over it into GSON first. Retrofit is much simpler than other libraries we don’t have to parse our JSON it directly returns objects but there is one disadvantage also it doesn’t provide support to loadimages from the server but we can use Picasso for the same. Now we should go for some practical implementation which will give better understanding to you.
Step-by-Step Implementation of RetoFit 2
Step 1: For using Retrofit in our Android project firstly we have to add dependency in the gradle file. For adding dependency open app/build.gradle file in your Android project and add the following lines inside it. Add these lines inside dependencies{}
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'
Step 2: We should now add InternetPermission inside Manifestfile.Open the manifest.xml file and add the following line.
users-permission android:name="android.permission.INTERNET"
Step 3: For retrieving data from the server using retrofit 2 we require a modelclass. We are going to make a model class to retrieve data from the server. For making a model class we should know how the JSON looks.
Suppose our JSON looks something like this :
"current_page":1,
" ""data":" "[
" "{
" ""id":1,
" ""source":"http:\/\/mhrd.gov.in\/sites\/upload_files\/mhrd\/files\/upload_document\/NSISGE-Scheme-Copy.pdf",
" ""name":"National Scheme of Incentive to Girls for Secondary Education (NSIGSE)",
" ""sector":"Education",
" ""government":"Central",
" ""eligible_beneficiaries":"Individual",
" ""requirements":"i. Girls, who pass class VIII examination and enroll for class IX in State\/UT Government, Government-aided or local body schools.\nii. Girls should be below 16 years of age (as on 31st March) on joining class IX\niii. Girls studying in private un-aided schools and enrolled in schools run by Central Government like KVS, NVS and CBS affiliated Schools are excluded.",
" ""benefits":"FD of Rs.3000 in the name of selected girls. The girls are entitled to withdraw the sum along with interest thereon on reaching 18 years of age and on passing 10th class examination.",
" ""how_to_apply":"Contact Principal\/Headmaster of the School",
" ""profession":"",
" ""nationality":"",
" ""gender":"Female",
" ""social_category":[
" ""SC",
" ""ST",
" ""Girls from Kasturba Gandhi Balika Vidyalayas"" "
],
" ""bpl":"",
" ""maximum_income":"",
" ""maximum_monthly_income":"",
" ""min_age":14,
" ""max_age":18,
" ""age_relaxation":"",
" ""qualification":8,
" ""employed":"",
" ""domicile":"",
" ""marital_status":"Unmarried",
" ""parents_profession":"",
" ""person_with_disabilities":"",
" ""current_student":"Yes",
" ""min_marks_in_previous_examination":"",
" ""religion":"",
" ""isDeleted":"false",
" ""isLatest":"false",
" ""isPopular":"false",
" ""isHtml":"false",
" ""state_url":"http:\/\/161.202.178.14\/kalyani\/storage\/states\/AORGzbxjrB3zHhAyfs6zTqpt3pQhJsHRwSC4JVBs.png",
" ""sector_url":"http:\/\/161.202.178.14\/kalyani\/storage\/sector\/lDASDAsje3BuWQYgaBCqKKWwkfKEuqIvVYp3dp53.png"" "
},
"
.... "
]"from":1,
" ""last_page":75,
" ""next_page_url":"http:\/\/localhost:8081\/\/api\/v1\/search?page=2",
" ""per_page":10,
" ""prev_page_url":null,
" ""to":10,
" ""total":741
If you see the json you will realize that json contains different fields like source, stateurl, sectorurl, id, name, sector, government, id, name, sector, government, eligibleBeneficiarieand etc for all the fields we have created getter setter and used parcelable(https://developer.android.com/reference/android/os/Parcelable.html).
Here is the code for model class please read it for better understanding.
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Scheme implements Parcelable {
public static final Creator<Scheme> CREATOR = new Creator<Scheme> ( ) {
@Override
public Scheme createFromParcel ( Parcel source ) {
return new Scheme ( source );
}
@Override
public Scheme[] newArray ( int size ) {
return new Scheme[size];
}
};
@SerializedName("source")
@Expose
private String source;
@SerializedName("state_url")
@Expose
private String stateurl;
@SerializedName("sector_url")
@Expose
private String sectorurl;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("sector")
@Expose
private String sector;
@SerializedName("government")
@Expose
private String government;
@SerializedName("eligible_beneficiaries")
@Expose
private String eligibleBeneficiaries;
@SerializedName("maximum_income")
@Expose
private String income;
@SerializedName("social_category")
@Expose
private String[] socialCategory;
@SerializedName("religion")
@Expose
private String religion;
@SerializedName("requirements")
@Expose
private String requirements;
@SerializedName("benefits")
@Expose
private String benefits;
@SerializedName("how_to_apply")
@Expose
private String howToApply;
@SerializedName("gender")
@Expose
private String gender;
@SerializedName("min_age")
@Expose
private Integer minAge;
@SerializedName("max_age")
@Expose
private Integer maxAge;
@SerializedName("qualification")
@Expose
private String qualification;
@SerializedName("marital_status")
@Expose
private String maritalStatus;
@SerializedName("bpl")
@Expose
private String bpl;
@SerializedName("disability")
@Expose
private String disability;
public Scheme ( ) {
}
protected Scheme ( Parcel in ) {
this.source = in.readString ( );
this.stateurl = in.readString ( );
this.sectorurl = in.readString ( );
this.id = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.name = in.readString ( );
this.sector = in.readString ( );
this.government = in.readString ( );
this.eligibleBeneficiaries = in.readString ( );
this.income = in.readString ( );
this.socialCategory = in.createStringArray ( );
this.religion = in.readString ( );
this.requirements = in.readString ( );
this.benefits = in.readString ( );
this.howToApply = in.readString ( );
this.gender = in.readString ( );
this.minAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.maxAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.qualification = in.readString ( );
this.maritalStatus = in.readString ( );
this.bpl = in.readString ( );
this.disability = in.readString ( );
}
public String getBpl ( ) {
return bpl;
}
public void setBpl ( String bpl ) {
this.bpl = bpl;
}
public String getDisability ( ) {
return disability;
}
public void setDisability ( String disability ) {
this.disability = disability;
}
public String getStateurl ( ) {
return stateurl;
}
public void setStateurl ( String stateurl ) {
this.stateurl = stateurl;
}
public String getSectorurl ( ) {
return sectorurl;
}
public void setSectorurl ( String sectorurl ) {
this.sectorurl = sectorurl;
}
public String getIncome ( ) {
return income;
}
public void setIncome ( String income ) {
this.income = income;
}
public String[] getSocialCategory ( ) {
return socialCategory;
}
public void setSocialCategory ( String[] socialCategory ) {
this.socialCategory = socialCategory;
}
public String getReligion ( ) {
return religion;
}
public void setReligion ( String religion ) {
this.religion = religion;
}
public String getRequirements ( ) {
return requirements;
}
public void setRequirements ( String requirements ) {
this.requirements = requirements;
}
public String getSource ( ) {
return source;
}
public void setSource ( String source ) {
this.source = source;
}
public Integer getId ( ) {
return id;
}
public void setId ( Integer id ) {
this.id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name ) {
this.name = name;
}
public String getSector ( ) {
return sector;
}
public void setSector ( String sector ) {
this.sector = sector;
}
public String getGovernment ( ) {
return government;
}
public void setGovernment ( String government ) {
this.government = government;
}
public String getEligibleBeneficiaries ( ) {
return eligibleBeneficiaries;
}
public void setEligibleBeneficiaries ( String eligibleBeneficiaries ) {
this.eligibleBeneficiaries = eligibleBeneficiaries;
}
public String getBenefits ( ) {
return benefits;
}
public void setBenefits ( String benefits ) {
this.benefits = benefits;
}
public String getHowToApply ( ) {
return howToApply;
}
public void setHowToApply ( String howToApply ) {
this.howToApply = howToApply;
}
public String getGender ( ) {
return gender;
}
public void setGender ( String gender ) {
this.gender = gender;
}
public Integer getMinAge ( ) {
return minAge;
}
public void setMinAge ( Integer minAge ) {
this.minAge = minAge;
}
public Integer getMaxAge ( ) {
return maxAge;
}
public void setMaxAge ( Integer maxAge ) {
this.maxAge = maxAge;
}
public String getQualification ( ) {
return qualification;
}
public void setQualification ( String qualification ) {
this.qualification = qualification;
}
public String getMaritalStatus ( ) {
return maritalStatus;
}
public void setMaritalStatus ( String maritalStatus ) {
this.maritalStatus = maritalStatus;
}
public String getSocialCategoryString(){
if(socialCategory != null && socialCategory.length > 0){
return android.text.TextUtils.join(",", socialCategory);
}
return null;
}
@Override
public int describeContents ( ) {
return 0;
}
@Override
public void writeToParcel ( Parcel dest, int flags ) {
dest.writeString ( this.source );
dest.writeString ( this.stateurl );
dest.writeString ( this.sectorurl );
dest.writeValue ( this.id );
dest.writeString ( this.name );
dest.writeString ( this.sector );
dest.writeString ( this.government );
dest.writeString ( this.eligibleBeneficiaries );
dest.writeString ( this.income );
dest.writeStringArray ( this.socialCategory );
dest.writeString ( this.religion );
dest.writeString ( this.requirements );
dest.writeString ( this.benefits );
dest.writeString ( this.howToApply );
dest.writeString ( this.gender );
dest.writeValue ( this.minAge );
dest.writeValue ( this.maxAge );
dest.writeString ( this.qualification );
dest.writeString ( this.maritalStatus );
dest.writeString ( this.bpl );
dest.writeString ( this.disability );
}
}
You must have observed that we have used pagination in json (we are retrieving data in a set of 10).For handling this pagination we will create one more java file.
Here is the code for pagination please read it for better understanding.
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class Page implements Parcelable {
public static final Creator<Page> CREATOR = new Creator<Page> ( ) {
@Override
public Page createFromParcel ( Parcel source ) {
return new Page ( source );
}
@Override
public Page[] newArray ( int size ) {
return new Page[size];
}
};
@SerializedName("current_page")
@Expose
private Integer currentPage;
@SerializedName("data")
@Expose
private ArrayList<Scheme> data = null;
@SerializedName("from")
@Expose
private Integer from;
@SerializedName("last_page")
@Expose
private Integer lastPage;
@SerializedName("next_page_url")
@Expose
private String nextPageUrl;
@SerializedName("path")
@Expose
private String path;
@SerializedName("per_page")
@Expose
private Integer perPage;
@SerializedName("prev_page_url")
@Expose
private String prevPageUrl;
@SerializedName("to")
@Expose
private Integer to;
@SerializedName("total")
@Expose
private Integer total;
public Page ( ) {
}
protected Page ( Parcel in ) {
this.currentPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.data = in.createTypedArrayList ( Scheme.CREATOR );
this.from = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.lastPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.nextPageUrl = in.readString ( );
this.path = in.readString ( );
this.perPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.prevPageUrl = in.readString ( );
this.to = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
this.total = (Integer) in.readValue ( Integer.class.getClassLoader ( ) );
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public ArrayList<Scheme> getData ( ) {
return data;
}
public void setData ( ArrayList<Scheme> data ) {
this.data = data;
}
public Integer getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public Integer getLastPage() {
return lastPage;
}
public void setLastPage(Integer lastPage) {
this.lastPage = lastPage;
}
public String getNextPageUrl() {
return nextPageUrl;
}
public void setNextPageUrl(String nextPageUrl) {
this.nextPageUrl = nextPageUrl;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Integer getPerPage() {
return perPage;
}
public void setPerPage(Integer perPage) {
this.perPage = perPage;
}
public String getPrevPageUrl ( ) {
return prevPageUrl;
}
public void setPrevPageUrl ( String prevPageUrl ) {
this.prevPageUrl = prevPageUrl;
}
public Integer getTo() {
return to;
}
public void setTo(Integer to) {
this.to = to;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
@Override
public int describeContents ( ) {
return 0;
}
@Override
public void writeToParcel ( Parcel dest, int flags ) {
dest.writeValue ( this.currentPage );
dest.writeTypedList ( this.data );
dest.writeValue ( this.from );
dest.writeValue ( this.lastPage );
dest.writeString ( this.nextPageUrl );
dest.writeString ( this.path );
dest.writeValue ( this.perPage );
dest.writeString ( this.prevPageUrl );
dest.writeValue ( this.to );
dest.writeValue ( this.total );
}
}
Now we have created model class(forhandlingdata) and pagination class(handling pagination in json). Now we have to create adapter and API service provider and display our data. We will cover these things in second and third part of this tutorial.
Reference : http://square.github.io/retrofit/