Android JSON Parsing Using Volley And Display With RecyclerView is today’s tutorial.
First of all, we will parse the JSON from URL using Volley.
Then we will populate a recyclerview using the data fetched from the JSON.
Generally, we need to make http calls to use the data on the remote server but volley simplifies this process.
Volley will reduce the number of Coding lines to make GET or POST calls to the web service.
We will fetch the information like name, country, city and image URL from the JSON.
Along with recyclerview, we will also use cardview to make it looking more attractive.
RecyclerView From Volley
Step 1. Internet Permission In Manifest
Internet is the basic requirement to call JSON from the remote server.
Add the below line in the AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.parsaniahardik.json_recycler_volley"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Here, we do not need to code for runtime permissions because internet is the normal or basic permission.
Normal permission means that it is lesser harming to the user privacy.
Step 2. Some Dependencies
It is time write some dependencies in the build.gradle(Module: app) file as per the below
implementation 'com.android.volley:volley:1.1.1' implementation 'com.squareup.picasso:picasso:2.71828' implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.android.support:cardview-v7:27.1.1'
I have added these lines for four different purposes.
First one is for volley library. It will enable us to use volley classes with any other integrations.
Second line is for picasso library which helps us to fetch the image from URL seamlessly.
Third line will allow us to use the recyclerview.
And finally, fourth line will give us the required classes for the usage of cardview.
Step 3. XML File For RecyclerView
Let us create an XML file under res->layout directory.
Give it a name rv_one.xml and add the following code in it
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.CardView android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" app:cardCornerRadius="5dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/iv" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:scaleType="fitXY" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="100dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:orientation="vertical"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_marginTop="5dp" android:layout_weight="1" android:text="ddd" android:textColor="#000" android:textStyle="bold" /> <TextView android:id="@+id/country" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:text="ddd" android:textColor="#000" android:textStyle="bold" /> <TextView android:id="@+id/city" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:text="ddd" android:textColor="#000" android:textStyle="bold" /> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout>
This file will provide the view structure to every row of the recyclerview.
I have taken one imaheview and three textviews in this file.
All these widgets are under the cardview that will create card layout to every row item.
Step 4. Data Model
Let us create a new class and give it a name DataModel.java
Code structure for DataModel.java is as the following
public class DataModel { private String name, country, city, imgURL; public String getImgURL(){ return imgURL; } public void setImgURL(String imgURL){ this.imgURL = imgURL; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
Step 5. Required Adapter
Adapter class will help us to populate the recyclerview.
Make a new JAVA class and give it a name RvAdapter.java
Code block for RvAdapter.java is as the following block
import android.content.Context; 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.squareup.picasso.Picasso; import java.util.ArrayList; public class RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> { private LayoutInflater inflater; private ArrayList<DataModel> dataModelArrayList; public RvAdapter(Context ctx, ArrayList<DataModel> dataModelArrayList){ inflater = LayoutInflater.from(ctx); this.dataModelArrayList = dataModelArrayList; } @Override public RvAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.rv_one, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(RvAdapter.MyViewHolder holder, int position) { Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv); holder.name.setText(dataModelArrayList.get(position).getName()); holder.country.setText(dataModelArrayList.get(position).getCountry()); holder.city.setText(dataModelArrayList.get(position).getCity()); } @Override public int getItemCount() { return dataModelArrayList.size(); } class MyViewHolder extends RecyclerView.ViewHolder{ TextView country, name, city; ImageView iv; public MyViewHolder(View itemView) { super(itemView); country = (TextView) itemView.findViewById(R.id.country); name = (TextView) itemView.findViewById(R.id.name); city = (TextView) itemView.findViewById(R.id.city); iv = (ImageView) itemView.findViewById(R.id.iv); } } }
Consider the below lines
private LayoutInflater inflater; private ArrayList<DataModel> dataModelArrayList; public RvAdapter(Context ctx, ArrayList<DataModel> dataModelArrayList){ inflater = LayoutInflater.from(ctx); this.dataModelArrayList = dataModelArrayList; }
First compiler will define the objects of LayoutInflater and arraylist.
Constructor will give us context and arraylist via it’s parameters.
Look at the following code block
@Override public void onBindViewHolder(RvAdapter.MyViewHolder holder, int position) { Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv); holder.name.setText(dataModelArrayList.get(position).getName()); holder.country.setText(dataModelArrayList.get(position).getCountry()); holder.city.setText(dataModelArrayList.get(position).getCity()); }
First line is loading the Image from the URL.
Compiler will use Picasso library here. It will get the url using getter method.
Compiler will write the name, country and city using related getter methods from the objects of the arraylist.
Step 6. Main Modifications
Add the following lines in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" android:background="#cd15e6" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Below RecyclerView is populated from JSON Data Volley" android:textColor="#fff" android:textStyle="bold" /> <android.support.v7.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginTop="15dp"/> </LinearLayout>
It includes one textview and recyclerview.
Now write down the following lines in MainActivity.java file
import android.app.ProgressDialog; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php"; private static ProgressDialog mProgressDialog; ArrayList<DataModel> dataModelArrayList; private RvAdapter rvAdapter; private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler); fetchingJSON(); } private void fetchingJSON() { showSimpleProgressDialog(this, "Loading...","Fetching Json",false); StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("strrrrr", ">>" + response); try { removeSimpleProgressDialog(); JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ dataModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { DataModel playerModel = new DataModel(); JSONObject dataobj = dataArray.getJSONObject(i); playerModel.setName(dataobj.getString("name")); playerModel.setCountry(dataobj.getString("country")); playerModel.setCity(dataobj.getString("city")); playerModel.setImgURL(dataobj.getString("imgURL")); dataModelArrayList.add(playerModel); } setupRecycler(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // request queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } private void setupRecycler(){ rvAdapter = new RvAdapter(this,dataModelArrayList); recyclerView.setAdapter(rvAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); } public static void removeSimpleProgressDialog() { try { if (mProgressDialog != null) { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } } catch (IllegalArgumentException ie) { ie.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static void showSimpleProgressDialog(Context context, String title, String msg, boolean isCancelable) { try { if (mProgressDialog == null) { mProgressDialog = ProgressDialog.show(context, title, msg); mProgressDialog.setCancelable(isCancelable); } if (!mProgressDialog.isShowing()) { mProgressDialog.show(); } } catch (IllegalArgumentException ie) { ie.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
Broad View Of Main Class
Read the below lines
private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php"; private static ProgressDialog mProgressDialog; ArrayList<DataModel> dataModelArrayList; private RvAdapter rvAdapter; private RecyclerView recyclerView;
First line is defining the URL of the Web service.
We will parse JSON using this URL via volley.
Second line is making the object of the progrss bar.
Third one is creating an arraylist with the objects of the DataModel class.
Fourth is making on object of RvAdapter and fifth is of RecyclerView class.
Inside onCreate() method, compiler is calling fetchingJSON() method.
Following is the code structure for fetchingJSON() method.
private void fetchingJSON() { showSimpleProgressDialog(this, "Loading...","Fetching Json",false); StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("strrrrr", ">>" + response); try { removeSimpleProgressDialog(); JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ dataModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { DataModel playerModel = new DataModel(); JSONObject dataobj = dataArray.getJSONObject(i); playerModel.setName(dataobj.getString("name")); playerModel.setCountry(dataobj.getString("country")); playerModel.setCity(dataobj.getString("city")); playerModel.setImgURL(dataobj.getString("imgURL")); dataModelArrayList.add(playerModel); } setupRecycler(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // request queue RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); }
- This method will parse the JSON and will populate the arraylist.
Json that it will parse is as the following
{ "status": "true", "message": "Data fetched successfully!", "data": [ { "id": "1", "name": "Roger Federer", "country": "Switzerland", "city": "Basel", "imgURL": "https://demonuts.com/Demonuts/SampleImages/roger.jpg" }, { "id": "2", "name": "Rafael Nadal", "country": "Spain", "city": "Madrid", "imgURL": "https://demonuts.com/Demonuts/SampleImages/nadal.jpg" }, { "id": "3", "name": "Novak Djokovic", "country": "Serbia", "city": "Monaco", "imgURL": "https://demonuts.com/Demonuts/SampleImages/djoko.jpg" }, { "id": "4", "name": "Andy Murray", "country": "United Kingdom", "city": "London", "imgURL": "https://demonuts.com/Demonuts/SampleImages/murray.jpg" }, { "id": "5", "name": "Maria Sharapova", "country": "Russia", "city": "Moscow", "imgURL": "https://demonuts.com/Demonuts/SampleImages/shara.jpg" }, { "id": "6", "name": "Caroline Wozniacki", "country": "Denmark", "city": "Odense", "imgURL": "https://demonuts.com/Demonuts/SampleImages/woz.jpg" }, { "id": "7", "name": "Eugenie Bouchard", "country": "Canada", "city": " Montreal", "imgURL": "https://demonuts.com/Demonuts/SampleImages/bou.png" }, { "id": "8", "name": "Ana Ivanovic", "country": "Serbia", "city": "Belgrade", "imgURL": "https://demonuts.com/Demonuts/SampleImages/iva.jpg" } ] }
fetchingJSON() method will make an array (dataArray) using JSONArray class.
Then compiler will execute a for loop for the number of times equals to the number of items of the daraArray.
During every iteration, compiler will create one object of the DataModel class.
Then it will set the values using setter methods and finally, it will add the object into the arraylist (dataModelArrayList)
Then compiler will call the setupRecycler() method.
Code for setupRecycler() method is as the following
private void setupRecycler(){ rvAdapter = new RvAdapter(this,dataModelArrayList); recyclerView.setAdapter(rvAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); }
In this method, compiler will create the objects of the RvAdapter class.
It will use dataModelArrayList while making this object.
At last, this adapter is set to the recyclerview and it will create recyclerview from JSON data.
Download Source Code For Android JSON Parsing Using Volley And Display With RecyclerView
[sociallocker]Download Source Code For Json_Recycler_Volley[/sociallocker]