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 seguro de tipo de construcción cuadrada para Android y Java que tiene como objetivo simplificar la extensión de los servicios web RESTful. Retrofit 2 utiliza y se basa en OkHttp como capa de administración del sistema. Retrofit hace que JSON reaccione de forma natural a la serialización mediante POJO (PlainOldJavaObject), que debe ser el atributo principal de la estructura JSON. Para serializar JSON, primero necesitamos un convertidor para convertirlo a Gson. La actualización es mucho más simple que otras bibliotecas, no necesitamos analizar nuestro json, devuelve las cosas directamente, pero también hay un inconveniente: no admite la carga de imágenes desde el servidor, pero podemos usar picasso para eso. Ahora deberíamos buscar una implementación práctica que le dará 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 abrir una dependencia, abra el archivo app/build.gradle en su proyecto de Android y agregue las siguientes líneas dentro de él. Pon 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 modificación 2, necesitamos una clase de modelo. Vamos a hacer una clase modelo para recuperar datos del servidor. Para hacer una clase modelo, debemos saber cómo se ve el json.
Haz que nuestro json se vea así:

«página_actual»:1,
«datos»:


“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 IXniii. 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»: «»,
“ingresos_máximos”:””,
“ingresos_max_mensuales”:””,
«edad_mínima»: 14,
«edad_máxima»: 18,
«resto_edad»: «»,
«calidad»: 8,
«empleado»: «»,
“domicilio”: ””,
«married_status»: «Soltero»,
«carrera_padres»:»»,
«Persona con discapacidad»:»»,
“estudiante_actual”: “Sí”,
“min_marks_in_previous_examination”:””,
«fe»: «»,
“Está eliminado”: ​​“falso”,
«isLatest»: «falso»,
«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»
},
….
]»de 1,
«última_página»: 75,
“next_page_url”:”http://localhost:8081//api/v1/search?page=2″,
«por_página»: 10,
«prev_page_url»: nulo,
«a»: 10,
«total»: 741

Si ve el json, comprenderá que json tiene diferentes campos como fuente, postura, sector, id, nombre, sector, gobierno, id, nombre, sector, gobierno, beneficiario elegible, etc. para todos los campos que hemos creado. usamos paquete (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 notado que usamos la enumeración en json (estamos recuperando datos en una matriz de 10). Para manejar esta página crearemos un archivo java más.
Aquí está el código para la numeració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 (manejar datos) y una clase de enumeración (manejar enumeración en json). Ahora necesitamos 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 ha sido agregado Ashutosh Bhushan Srivastava. Si te gusta GeeksforGeeks y quieres contribuir, también puedes escribir un artículo usándolo. escribir.geeksforgeeks.org o envíe su artículo por correo a review-team@geeksforgeeks.org. Vea su artículo destacado en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba un comentario si encuentra algún problema o si desea compartir más información sobre el tema tratado anteriormente.

Mis notas personales
flecha_caer_arriba

Deja un comentario

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