We already know about JSON parsing and displaying in ListView. Now, in this tutorial, we will parse and display JSON in RecyclerView.
You can call any JSON API, here used JSONplaceholder rest API for learning purposes. Further, we will also make rest API using PHP MySQL. By the way, we try a simple way to fetch and display data in RecyclerView.
Let’s start creating JSON parsing and showing data in Android RecyclerView.
You know, we learn every tutorial step by step. This tutorial has also shown you the step-by-step process of displaying JSON format data in RecyclerView.
How to get JSON data and display it in android RecyclerView using retrofit?
Step: 1
Create a new Android project.
Step: 2
Dependencies
Go to build.gradle(module:app)file.
Script⇾build.gradle(module:app).
Add the following two dependencies.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Then don’t forget to click on Sync Project.
Step: 3
Permission
We’ll fetch data from the internet server and also send an HTTP request from the server. So we need the internet to show JSON data in RecyclerView. So we have to give internet permission. which you have already seen in previous ListView tutorials.
Go to AndroidManifest.xml file and give internet permission.
Manifest⇾AndroidManifest.xml and add the following internet permission.
<uses-permission android:name="android.permission.INTERNET"/>
Step: 4
Create a Model named Class.
Java⇾right-click on the package name⇾new ⇾java class.
We already know about the Model class.
The code of the model class is given below.
Model.java
package com.example.jsonretrofit;
class Model {
private int id;
private String title,body;
//generate constructor
public Model(int id, String title, String body) {
this.id = id;
this.title = title;
this.body = body;
}
//generate getter and setter method
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Step: 5
After the Model class is created, create a new interface java class to call API.
Java ⇾right-clicks on the package name⇾new ⇾java class⇾named MyApi and select interface.
The code for the MyApi interface is given below.
MyApi.java
package com.example.jsonretrofit;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
interface MyApi {
@GET("posts")
Call<ArrayList<Model>>modelCall();
}
Step: 6
Now we create UI design in our layout xml as textview data is to be shown.
Go to res⇾right click on layout ⇾activity_main.xml Go to the default activity_main layout file. We will add RecyclerView to it.
The following code of activity_main.xml
activity_main.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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/rv"/>
</RelativeLayout>
Step: 7
Now, we want to create a singleview XML layout file to display the data in the RecyclerView.
Res⇾right click on Layout ⇾new⇾layout resource file.
The following code of singleview.xml
Singleview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/idtxt"/>
<TextView
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/titletxt"/>
<TextView
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bodytxt"/>
</LinearLayout>
Step: 8
Now, we will create an adapter class to view the data in Recyclerview.
Java ⇾right-click on the package name⇾new ⇾java class⇾named MyAdapter.java
The following code of MyAdapter.java
MyAdapter.java
package com.example.jsonretrofit;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
//create variable
private ArrayList<Model>modelArrayList;
private Context context;
//generate constructor
public MyAdapter(ArrayList<Model> modelArrayList, Context context) {
this.modelArrayList = modelArrayList;
this.context = context;
}
@NonNull
@Override
public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//layout inflater
View view= LayoutInflater.from ( parent.getContext () ).inflate ( R.layout.singleview,parent,false );
return new ViewHolder (view);
}
@Override
public void onBindViewHolder(@NonNull MyAdapter.ViewHolder holder, int position) {
//get position form model class
Model model=modelArrayList.get ( position );
//set data in textview
holder.idtxt.setText ("Id:-"+ model.getId ()+"\n" );
holder.titletxt.setText ("Title:-"+ model.getTitle ()+"\n" );
holder.bodytxt.setText ("Body:-"+ model.getBody ()+"\n" );
}
@Override
public int getItemCount() {
return modelArrayList.size ();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//create variable
TextView idtxt,titletxt,bodytxt;
public ViewHolder(@NonNull View itemView) {
super ( itemView );
//initialize variable
idtxt=itemView.findViewById ( R.id.idtxt );
titletxt=itemView.findViewById ( R.id.titletxt );
bodytxt=itemView.findViewById ( R.id.bodytxt );
}
}
}
Step: 9
Finally, we come to the Main Activity or the default Java Activity, MainActivity.java.
In the MainActivity.java file, we will create a Java variable, initialize it, call the Adapter class, and create a method.
Here Retrofit is used and Adapter class is called and finally, data is displayed in RecyclerView.
The following code of MainActivity.java
MainActivity.java
package com.example.jsonretrofit;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private MyApi myApi;
private RecyclerView recyclerView;
private ArrayList<Model>modelArrayList;
private String BaseUrl="https://jsonplaceholder.typicode.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
//initialize variable
recyclerView=findViewById ( R.id.rv );
//create an arraylist
modelArrayList=new ArrayList<> ();
//create a view data method
viewJsonData();
}
private void viewJsonData() {
//create retrofit
Retrofit retrofit=new Retrofit.Builder ()
.baseUrl ( BaseUrl )
.addConverterFactory ( GsonConverterFactory.create () )
.build ();
//retrofit api
myApi=retrofit.create ( MyApi.class );
//display all data from api
Call<ArrayList<Model>>arrayListCall=myApi.modelCall ();
arrayListCall.enqueue ( new Callback<ArrayList<Model>> () {
@Override
public void onResponse(Call<ArrayList<Model>> call, Response<ArrayList<Model>> response) {
modelArrayList=response.body ();
//usign for loop for data display from adapter
int i=0;
for (i=0;i<modelArrayList.size ();i++){
//create adapter class
MyAdapter myAdatepr=new MyAdapter(modelArrayList,MainActivity.this);
//implementaion linearlayout manager
LinearLayoutManager manager=new LinearLayoutManager (MainActivity.this,RecyclerView.VERTICAL,false );
//set layout manager
recyclerView.setLayoutManager ( manager );
//set adapter
recyclerView.setAdapter ( myAdatepr );
}
}
@Override
public void onFailure(Call<ArrayList<Model>> call, Throwable t) {
}
} );
}
}
As a result, we will get output like below.
Note: In this post, if you find any mistakes, incorrect or bugs and errors, feel free to contact or give feedback to improve the quality. Great if you give your feedback about this tutorial and other tutorials.