I have implemented recyclerview in my application and now i need to fetch data from the API but i dont find a good example of how to do it. It's the first time i try to get data from an API and i dont really know how to do it.
The API delivers the data in this way:
{
status: "OK"
code: 0
message: ""
results: [
{
id: 0
slug: "data"
slug_franquicia: "data"
slug_categoria: "data"
}}
Here u can see my constructor (i'm using the constructor with 6 fields at the moment to show static data, the constructor i want to use is the big one to parse the data):
int id;
String slug;
String slug_franquicia;
String slug_categoria;
private String Franquicia;//nombre_franquicia
private String Modalidad;//nombre_categoria
private String nombre;
private String DescripcionC;
String contenido;
String oferta_ahorro;
int latitud;
int longitud;
String direccion;
String foto_negocio;//url
String foto_principal;//url
String horario;
String web;//url
String telefono;
String email;
String facebook;//url
String twitter;//url
String youtube;//url
String instagram;//url
String vimeo;//url
String googleplus;//url
String wordpress_autor;
String plan;
String estado;
String update_date;
String record_date;
private boolean Premium;//este no
private int imagen;//este no
public Empresas(int id, String slug,String slug_franquicia,String slug_categoria,String Franquicia,String Modalidad,String nombre, String DescripcionC,
String contenido, String oferta_ahorro, int latitud, int longitud, String direccion, String foto_negocio, String foto_principal, String horario,
String web, String telefono, String email, String facebook, String twitter, String youtube, String instagram, String vimeo, String googleplus,
String wordpress_autor, String plan, String estado, String update_date, String record_date){
this.id=id;
this.slug=slug;
this.slug_franquicia=slug_franquicia;
this.slug_categoria=slug_categoria;
this.Franquicia=Franquicia;
this.Modalidad=Modalidad;
this.nombre=nombre;
this.DescripcionC=DescripcionC;
this.contenido=contenido;
this.oferta_ahorro=oferta_ahorro;
this.latitud=latitud;
this.longitud=longitud;
this.direccion=direccion;
this.foto_negocio=foto_negocio;
this.foto_principal=foto_principal;
this.horario=horario;
this.web=web;
this.telefono=telefono;
this.email=email;
this.facebook=facebook;
this.twitter=twitter;
this.youtube=youtube;
this.instagram=instagram;
this.vimeo=vimeo;
this.googleplus=googleplus;
this.wordpress_autor=wordpress_autor;
this.plan=plan;
this.estado=estado;
this.update_date=update_date;
this.record_date=record_date;
}
public Empresas(int imagen, String nombre, String DescripcionC, String Modalidad, String Franquicia, boolean Premium) {
this.imagen = imagen;
this.nombre = nombre;
this.DescripcionC = DescripcionC;
this.Modalidad = Modalidad;
this.Franquicia = Franquicia;
this.Premium = Premium;
}
Here i fill the list with static info:
public class Empresas2 {
private static Empresas[] empresas={
new Empresas(R.drawable.activatuocio, "Activa tu ocio y di capacitados","Asociación sin ánimo de lucro que llena con ocio y talleres de formación en distintos ámbitos el tiempo de las personas con discapacidad intelectual. Confianza en si mismas, autonomía e integración.","Social", "El Ejido", true),
new Empresas(R.drawable.agroservicios, "Agroservicios Manuel Garzón","Todo tipo de trabajos de tractor con la mejor máquina, los aperos más completos y la mayor maestría en la conducción y profesionalidad para que el rendimiento de los cultivos vaya a mucho más.","Agricultura", "El Ejido", true ),
new Empresas(R.drawable.alexgarcia, "Alex García", "Alex García: Cantautor Almeriense. Disfruta de su nuevo disco titulado ''Por amor al arte, hasta que se harten.''","Artistas", "El Ejido", true ),
new Empresas(R.drawable.allianz, "Allianz Seguros Jorge Berenguer","Trato personalizado en la gestión de dos grandes marcas como Allianz y sus seguros de particulares y empresas para autónomos, pymes y grandes firmas, y Solunion y sus seguros de crédito y recobro.", "Legal", "El Ejido", false),
new Empresas(R.drawable.alteco, "Alteco", "Alteco Electricidad y Electrónica", "Profesionales", "El Ejido", true),
new Empresas(R.drawable.aluminiosmanuel, "Aluminios Manuel Estévez", "Grandes profesionales, las primeras marcas del mercado, las innovaciones que aparecen en el sector, todo congregado en una empresa que se ha ganado su prestigio a base de clientes satisfechos.", "Profesionales", "Vícar", true),
new Empresas(R.drawable.amalgama, "Amalgama Centro Musical", "Conocimiento, profesionalidad y un trato exclusivo es lo que nos diferencia en Amalgama, nuestra vida es la música, y eso transmitimos.", "Educación", "El Ejido", true),};
public static List<Empresas> getEmpresas() {
return Arrays.asList(empresas);
}
public static Empresas getCourseByPosition(int position) {
return empresas[position];
}
And this is the adapter i use in my recyclerview:
public class EmpresasAdapter extends RecyclerView.Adapter<EmpresasAdapter.EmpresasViewHolder>
implements ItemClickListener{
private final Context context;
private List<Empresas> items;
public EmpresasAdapter(Context context, List<Empresas> items) {
this.context = context;
this.items = items;
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public EmpresasViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.empresa_card, viewGroup, false);
return new EmpresasViewHolder(v, this);
}
@Override
public void onBindViewHolder(EmpresasViewHolder viewHolder, int i) {
// Item procesado actualmente
Empresas currentItem = items.get(i);
viewHolder.nombrep.setText(currentItem.getNombre());
viewHolder.franquiciap.setText(currentItem.getModalidad()+" | "+currentItem.getFranquicia());
// Cargar imagen
Glide.with(context)
.load(currentItem.getImagen())
.into(viewHolder.imagenp);
}
@Override
public void onItemClick(View view, int position) {
// Imagen a compartir entre transiciones
/* View sharedImage = view.findViewById(R.id.imagenp);
EmpresaDetalle.launch(
(Activity) context, position, sharedImage);*/
Empresas currentItem = items.get(position);
String nombre=currentItem.getNombre();
String descripcion=currentItem.getDescripcionC();
String franquicia=currentItem.getFranquicia();
int imagen = currentItem.getImagen();
View sharedImage = view.findViewById(R.id.imagenp);
Intent intent = new Intent(context, EmpresaDetalle.class);
intent.putExtra("nombre", nombre);
intent.putExtra("descripcion", descripcion);
intent.putExtra("franquicia", franquicia);
intent.putExtra("imagen",imagen);
context.startActivity(intent);
}
/**
* View holder para reciclar elementos
*/
public static class EmpresasViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
// Views para un curso
public ImageView imagenp;
public TextView nombrep;
public TextView franquiciap;
// Interfaz de comunicación
public ItemClickListener listener;
public EmpresasViewHolder(View v, ItemClickListener listener) {
super(v);
nombrep = (TextView) v.findViewById(R.id.nombrep);
franquiciap = (TextView) v.findViewById(R.id.Franquiciap);
imagenp = (ImageView) v.findViewById(R.id.imagenp);
v.setOnClickListener(this);
this.listener = listener;
}
@Override
public void onClick(View v) {
listener.onItemClick(v, getAdapterPosition());
}
}}
interface ItemClickListener {
void onItemClick(View view, int position);}