Android Retrofit ViewModel Example
Hola amigos en esta ocasión vamos a aprender a utilizar una librería llamada Retrofit para el consumo de datos en servicios web. Y crearemos un ViewModel para ello.![]() |
Como utilizar Retrofit y crear un ViewModel en Android |
Como crear un proyecto en Android (Aquí)
Vamos a crear un proyecto para nuestro ejemplo Retrofit ViewModel y poder desarrollarlo.Como crear un proyecto en Android |
Crear diseño de Retrofit ViewModel
Comenzaremos creando el diseño de nuestra aplicación Retrofit ViewModel.Vamos a añadir las librerias necesarias para nuestra aplicación y abriremos el archivo build.gradle (Module:app). Y agregaremos las dependencias.
//adding dependencies
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
implementation "android.arch.lifecycle:extensions:1.1.0"
implementation "android.arch.lifecycle:viewmodel:1.1.0"
Y le daremos Sync. para recompilar la aplicación. Continuamos y añadiremos los controles que necesitaremos. Añadiremos el permiso para Internet en nuestro archivo AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
En nuestro archivo activity_main.xml añadiremos el siguiente control.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Diseño de activity_main.xml RecyclerView |
Vamos a agregar un nuevo archivo al que le agregaremos los siguientes controles.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Diseño Retrofit ViewModel |
Código de Retrofit ViewModel en Android
Ahora continuamos y añadiremos varias clases para la funcionalidad de nuetro ViewModel.Añadiremos una clase que sera el constructor de nuestro ViewModel le llamaremos Hero.
public class Hero {
private String name;
private String realname;
private String team;
private String firstappearance;
private String createdby;
private String publisher;
private String imageurl;
private String bio;
public Hero(String name, String realname, String team, String firstappearance, String createdby, String publisher, String imageurl, String bio) {
this.name = name;
this.realname = realname;
this.team = team;
this.firstappearance = firstappearance;
this.createdby = createdby;
this.publisher = publisher;
this.imageurl = imageurl;
this.bio = bio;
}
public String getName() {
return name;
}
public String getRealname() {
return realname;
}
public String getTeam() {
return team;
}
public String getFirstappearance() {
return firstappearance;
}
public String getCreatedby() {
return createdby;
}
public String getPublisher() {
return publisher;
}
public String getImageurl() {
return imageurl;
}
public String getBio() {
return bio;
}
}
Ahora añadiremos una clase que sera el Adapter.
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class HeroesAdapter extends RecyclerView.Adapter<HeroesAdapter.HeroViewHolder> {
Context mCtx;
List<Hero> heroList;
public HeroesAdapter(Context mCtx, List<Hero> heroList) {
this.mCtx = mCtx;
this.heroList = heroList;
}
@NonNull
@Override
public HeroViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_layout, parent, false);
return new HeroViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull HeroViewHolder holder, int position) {
Hero hero = heroList.get(position);
Glide.with(mCtx)
.load(hero.getImageurl())
.into(holder.imageView);
holder.textView.setText(hero.getName());
}
@Override
public int getItemCount() {
return heroList.size();
}
class HeroViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public HeroViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
}
}
}
Continuamos y añadiremos una clase que sera para nuestra API que vamos a consumir con nuestro Retrofit.
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface Api {
String BASE_URL = "https://simplifiedcoding.net/demos/";
@GET("marvel")
Call<List<Hero>> getHeroes();
}
Y agregaremos nuestra clase para nuestro ViewModel.
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class HeroesViewModel extends ViewModel {
//this is the data that we will fetch asynchronously
private MutableLiveData<List<Hero>> heroList;
//we will call this method to get the data
public LiveData<List<Hero>> getHeroes() {
//if the list is null
if (heroList == null) {
heroList = new MutableLiveData<List<Hero>>();
//we will load it asynchronously from server in this method
loadHeroes();
}
//finally we will return the list
return heroList;
}
//This method is using Retrofit to get the JSON data from URL
private void loadHeroes() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
//finally we are setting the list to our MutableLiveData
heroList.setValue(response.body());
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
}
});
}
}
Y por ultimo agregaremos en nuestro MainActivity lo siguiente.
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
HeroesAdapter adapter;
List<Hero> heroList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
HeroesViewModel model = ViewModelProviders.of(this).get(HeroesViewModel.class);
model.getHeroes().observe(this, new Observer<List<Hero>>() {
@Override
public void onChanged(@Nullable List<Hero> heroList) {
adapter = new HeroesAdapter(MainActivity.this, heroList);
recyclerView.setAdapter(adapter);
}
});
}
}
Y con esto tendríamos listo nuestro ejemplo.
Como crear un emulador AVD en Android (Aquí)
Vamos a crear un emulador para ver nuestro ejemplo de Retrofit ViewModel en ejecución.Retrofit ViewModel en emulador AVD |
Y listo dejanos saber tu opinión sobre este tutorial. Gracias.
Referencia. SimplifiedCoding
No hay comentarios:
Publicar un comentario