Introducción a Retofit 2 en android | Serie 1

Lo he dividido en 3 partes. Supongo que el lector tiene conocimientos básicos de Android y Java. 
 

Introducción

Retrofit 2 es un cliente REST con seguridad de tipos creado por Square para Android y Java, que pretende simplificar la expansión de los servicios web RESTful. Retrofit 2 usa OkHttp como la capa de administración de sistemas y se basa en ella. Retrofit serializa naturalmente la reacción JSON utilizando un POJO (PlainOldJavaObject) que debe caracterizarse como innovador para la estructura JSON. Para serializar JSON, primero necesitamos un convertidor para cambiarlo a Gson. Retrofit es mucho más simple que otras bibliotecas, no tenemos que analizar nuestro json, devuelve objetos directamente, pero hay una desventaja: no brinda soporte para cargar imágenes desde el servidor, pero podemos usar picasso para lo mismo. Ahora deberíamos buscar una implementación práctica que le brinde una mejor comprensión.
 

Implementación

Paso 1: para usar Retrofit en nuestro proyecto de Android, primero debemos agregar la dependencia en el archivo gradle. Para agregar la dependencia, abra el archivo app/build.gradle en su proyecto de Android y agregue las siguientes líneas dentro de él. Agregue estas líneas dentro de las dependencias{} 
 

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'

Paso 2: ahora debemos agregar InternetPermission dentro de Manifestfile. Abra el archivo manifest.xml y agregue la siguiente línea. 
 

users-permission android:name="android.permission.INTERNET"

Paso 3: para recuperar datos del servidor utilizando la actualización 2, necesitamos una clase de modelo. Vamos a hacer una clase de modelo para recuperar datos del servidor. Para hacer una clase de modelo, debemos saber cómo se ve el json. 
Supongamos que nuestro json se parece a esto: 

“página_actual”:1, 
“datos”: 


“id”:1, 
“fuente”:”http:\/\/mhrd.gov.in\/sites\/upload_files\/mhrd\/files\/upload_document\ /NSISGE-Scheme-Copy.pdf”, 
“name”:”Esquema Nacional de Incentivo a Niñas para la Educación Secundaria (NSIGSE)”, 
“sector”:”Educación”, 
“gobierno”:”Central”, 
“beneficiarios_elegibles”:” Individual”, 
“requisitos”: “i. Niñas, que aprueban el examen de la clase VIII y se matriculan en la clase IX en las escuelas estatales, subsidiadas por el gobierno o locales.\nii. Las niñas deben tener menos de 16 años (al 31 de marzo) al ingresar a la clase IX\niii. Se excluyen las niñas que estudian en escuelas privadas sin ayuda y que están inscritas en escuelas administradas por el gobierno central, como las escuelas afiliadas a KVS, NVS y CBS.”, 
“beneficios”:”FD de Rs.3000 a nombre de las niñas seleccionadas. Las niñas tienen derecho a retirar la suma junto con los intereses correspondientes al cumplir los 18 años de edad y al aprobar el examen de décima clase.”, 
“how_to_apply”:”Comuníquese con el director/director de la escuela”, 
“profesión”:””, 
“ nacionalidad”:””, 
“género”:”Mujer”, 
“categoría_social”:[ 
“SC”, 
“ST”, 
“Chicas de Kasturba Gandhi Balika Vidyalayas” 
], 
“bpl”:””, 
“ingreso_máximo”:”” , 
“ingreso_máximo_mensual”:””, 
“edad_mínima”:14, 
“edad_máxima”:18, 
“relajación_por_edad”:””, 
“calificación”:8, 
“empleado”:””, 
“domicilio”:””, 
“estado_civil” :»Soltero», 
“parents_profession”:””, 
“person_with_disabilities”:””, 
“current_student”:”Yes”, 
“min_marks_in_previous_examination”:””, 
“religion”:””, 
“isDeleted”:”false”, 
“isLatest”:”false ”, 
“isPopular”:”falso”, 
“isHtml”:”falso”, 
“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 

Si ve el json, se dará cuenta de que json contiene diferentes campos como fuente, stateurl, sectorurl, id, nombre, sector, gobierno, id, nombre, sector, gobierno, beneficiario elegible, etc. para todos los campos que hemos creado getter setter y usamos parcelable ( https://developer.android.com/reference/android/os/Parcelable.html ).
Aquí está el código para la clase modelo, léalo para una mejor comprensión. 
 

java

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 );
    }
}

Debe haber observado que hemos usado la paginación en json (estamos recuperando datos en un conjunto de 10). Para manejar esta paginación, crearemos un archivo java más.
Aquí está el código para la paginación, léalo para una mejor comprensión. 
 

java

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 );
    }
}

Ahora hemos creado una clase modelo (para manejar datos) y una clase de paginación (manejo de paginación en json). Ahora tenemos que crear un adaptador y un proveedor de servicios API y mostrar nuestros datos. Cubriremos estas cosas en la segunda y tercera parte de este tutorial.
Referencia:  
http://square.github.io/retrofit/
Este artículo es una contribución de Ashutosh Bhushan Srivastava . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *