Native Mobile App Development With Java

Android Retrofit Example With RecyclerView

15-Sep-2024

Learn how to show API data using Retrofit and RecyclerView in Android Studio using Java

Android Retrofit  Example With RecyclerView



We are Get data from https://reqres.in/api/users this url

1/  Create A New Project and add Libarary.




dependencies {

implementation libs.appcompat
implementation libs.material
implementation libs.activity
implementation libs.constraintlayout
testImplementation libs.junit
androidTestImplementation libs.ext.junit
androidTestImplementation libs.espresso.core

implementation "com.squareup.retrofit2:converter-gson:2.8.1" //Add Library for retrofit here
implementation "com.squareup.retrofit2:retrofit:2.9.0"
  implementation "com.github.bumptech.glide:glide:4.11.0" //Add Library for Image
annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"

}



2/ See  https://reqres.in/api/users Api Response  




{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "george.bluth@reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "janet.weaver@reqres.in",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-image.jpg"
},
{
"id": 3,
"email": "emma.wong@reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
{
"id": 4,
"email": "eve.holt@reqres.in",
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://reqres.in/img/faces/4-image.jpg"
},
{
"id": 5,
"email": "charles.morris@reqres.in",
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://reqres.in/img/faces/5-image.jpg"
},
{
"id": 6,
"email": "tracey.ramos@reqres.in",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}





3/ Add user permission in AndroidManifest.xml



<uses-permission android:name="android.permission.INTERNET"/>


 Folder Like this



4/  Create A Model Class UserData.class



package com.example.retrofitdatalist.model;

public class UserData {

int id;
String email;
String first_name;
String last_name;
String avatar;

public UserData(int id, String email, String first_name, String last_name, String avatar) {
this.id = id;
this.email = email;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}

public String getLast_name() {
return last_name;
}

public void setLast_name(String last_name) {
this.last_name = last_name;
}

public String getAvatar() {
return avatar;
}

public void setAvatar(String avatar) {
this.avatar = avatar;
}
}



5/  Create A New Class SuportData.class



package com.example.retrofitdatalist.model;

public class SuportData {

String url;
String text;

public SuportData(String url, String text) {
this.url = url;
this.text = text;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}
}





6/  Create A New Class UserListResponse.class



package com.example.retrofitdatalist.model;

import java.util.ArrayList;

public class UserListResponse {
ArrayList<UserData> data;

int total;
int per_page;

SuportData support;

public UserListResponse(ArrayList<UserData> data, int total,int per_page) {
this.data = data;
this.total = total;
this.per_page = per_page;
}

public ArrayList<UserData> getData() {
return data;
}

public void setData(ArrayList<UserData> data) {
this.data = data;
}

public int getTotal() {
return total;
}

public void setTotal(int total) {
this.total = total;
}

public int getPer_page() {
return per_page;
}

public void setPer_page(int per_page) {
this.per_page = per_page;
}
}




7/  Create A Interface RetrofitAPI.



package com.example.retrofitdatalist.api_interface;
import com.example.retrofitdatalist.model.UserListResponse;

import retrofit2.Call;
import retrofit2.http.GET;

public interface RetrofitAPI {
@GET("/api/users")
public Call<UserListResponse> getAllUser();



}






8/  Create A user_lay.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content">

<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"

android:orientation="horizontal">

<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_weight="2"

android:layout_height="100dp"
tools:srcCompat="@tools:sample/avatars" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="10dp"
android:orientation="vertical">

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20dp"
android:textColor="@color/black"
android:text="TextView" />

<TextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>

</LinearLayout>

</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>






9/ Create UserAdapter




package com.example.retrofitdatalist.adpter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.retrofitdatalist.R;
import com.example.retrofitdatalist.model.UserData;

import java.util.ArrayList;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {

ArrayList<UserData> dataArrayList;
Context context;

public UserAdapter(ArrayList<UserData> dataArrayList, Context context) {
this.dataArrayList = dataArrayList;
this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_lay, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}


@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

holder.name.setText(dataArrayList.get(position).getFirst_name().toString()+ " "+ dataArrayList.get(position).getLast_name().toString());

holder.email.setText(dataArrayList.get(position).getEmail().toString());

holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, dataArrayList.get(position).getFirst_name().toString(), Toast.LENGTH_SHORT).show();
}
});


Glide.with(context).load(dataArrayList.get(position).getAvatar()).listener(new RequestListener() {


@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
return false;
}

@Override
public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
return false;
}
}).into(holder.image);
}

@Override
public int getItemCount() {
return dataArrayList.size();
}


public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView image;
TextView email;
public MyViewHolder(View itemView) {
super(itemView);

name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.imageView);
email = (TextView) itemView.findViewById(R.id.email);
}
}
}



10/  Now  in MainActivity




package com.example.retrofitdatalist;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.retrofitdatalist.adpter.UserAdapter;
import com.example.retrofitdatalist.api_interface.RetrofitAPI;
import com.example.retrofitdatalist.model.UserListResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);

getData();

}

private void getData(){

Retrofit retrofit = new Retrofit.Builder().baseUrl("https://reqres.in/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);



Call<UserListResponse> call = retrofitAPI.getAllUser();

call.enqueue(new Callback<UserListResponse>() {
@Override
public void onResponse(Call<UserListResponse> call, Response<UserListResponse> response) {

Log.d("responseData",response.body().getData().toString());


recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);

UserAdapter userAdapter=new UserAdapter(response.body().getData(),MainActivity.this);
recyclerView.setAdapter(userAdapter);


}
@Override
public void onFailure(Call<UserListResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
}
});
}

}


Run code then see output.



Comments