Fetch JSON data using Volley library and display it in RecyclerView — Android Studio

 

Hello Friends, in my last post  “RecyclerView Implementation With CardView Basic Example In Android”  we learn multiple things like how to create RecyclerView, how to use CardView, how to create an adapter class, about modal class etc. Today in this post we work on JSON data and learn how to fetch JSON data using volley library and how to display these data in RecyclerView by creating an Android App in Android Studio.

JSON: JSON stands for JavaScript Object Notation. This is a lightweight human-readable syntax for storing and exchanging data between a server and a browser. JSON is also best alternative to XML.

Components (we will use it for the appearance and functionality)

1) RecyclerView: We will use this component to display a large amount of data in a list, this is the basic and important component of this app. It provides a feature to implement the list in form of horizontal, vertical and Expandable.

2) CardView: This component helps in creating a good looking UI, we use it in this app to design RecyclerView item. With the help of this component, we can work on shadow, elevation, corner radius etc.

3) Volley: Volley is a library that makes networking for Android apps easier and most importantly, faster. It has so many features some of them are:

  • It helps in multiple concurrent network connections.
  • It has a great feature of customization.
  • It provides powerful Debugging and tracing tools.
  • It provides Auto network requests scheduling functionality.

4) Glide: Glide is a fast and efficient image loading and media management open source library for Android. There are so many features of glide like disk cache, memory cache, fetch the image, resize the image, display a remote image etc.

5) Gson: Gson is a Java-based open source library developed by Google, it is also known as Google Gson. It is used for serialization and deserialization of Java objects to JSON.

With the help of making an app, we learn how to fetch JSON data using volley library and display it in RecyclerView. Before start to creating app see the demo app given below.

Demo

Create New Project

Before Implementing the following code first create a new project in Android Studio, go to File  => then go to New => then select New Project option. In Add an activity option select default activity(Blank Activity) and proceed.

Structure Of Code

Sample JSON

Link: http://www.techsolpoint.com/api_example/api.json

{
"list":[
{
"id":1,
"name":"Item-1",
"img":"https://i0.wp.com/www.techsolpoint.com/wp-content/uploads/2018/04/make-money-online.jpeg"
},
{
"id":2,
"name":"Item-2",
"img":"https://i2.wp.com/www.techsolpoint.com/wp-content/uploads/2018/04/bg.jpg"
},
{
"id":3,
"name":"Item-3",
"img":"https://i0.wp.com/www.techsolpoint.com/wp-content/uploads/2018/03/google_seo.jpeg"
},
{
"id":4,
"name":"Item-4",
"img":"https://i2.wp.com/www.techsolpoint.com/wp-content/uploads/2018/03/seo.jpeg"
},
{
"id":5,
"name":"Item-5",
"img":"https://4.bp.blogspot.com/-           nrp2ovenoYs/WPXtdu7YjZI/AAAAAAAAAcw/0ZO1oWD3Dz4TNpeJWGkQVF3gI4tmWJ-       NQCLcB/s1600/913518289_5021def7bc_b.jpg"
}
]
}

Code

 

Code for build.gradle (Module: app )

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.asus.recyclerviewjson"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.github.bumptech.glide:glide:4.2.0'
    implementation 'com.google.code.gson:gson:2.8.2'
}

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asus.recyclerviewjson">

<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"
android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"/>
</application>

</manifest>

 

Code for MainActivity.java file.

package com.example.asus.recyclerviewjson;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.asus.recyclerviewjson.adapter.RvAdapter;
import com.example.asus.recyclerviewjson.model.Rvdata;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

ArrayList<Rvdata> proSearch = new ArrayList<Rvdata>();
RecyclerView rvTechSolPoint;
RvAdapter rvAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// ArrayList<Rvdata> rvdata = getData();

rvTechSolPoint = findViewById(R.id.rv_techsolpoint);
rvTechSolPoint.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
rvTechSolPoint.setLayoutManager(layoutManager);

getServerData();
}

private void getServerData() {
String urlGetServerData = "http://www.techsolpoint.com/api_example/api.json";
System.out.print(urlGetServerData);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetServerData,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response);

try {
Gson gson = new Gson();
JSONArray jsonArray = response.getJSONArray("list");

for (int p=0; p<jsonArray.length(); p++){
JSONObject jsonObject = jsonArray.getJSONObject(p);
Rvdata rvdata = gson.fromJson(String.valueOf(jsonObject), Rvdata.class);
proSearch.add(rvdata);
}
rvAdapter = new RvAdapter(getApplicationContext(), proSearch);
rvTechSolPoint.setAdapter(rvAdapter);

} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(jsonObjectRequest);
}
}

 

Code for 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:background="#eee"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_techsolpoint"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

 

Code for NewActivity.java file.

package com.example.asus.recyclerviewjson;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
}
}

 

Code for activity_new.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:background="#76D7C4"
    tools:context=".NewActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:layout_gravity="center"
        android:textSize="30sp"
        android:textColor="#E74C3C"
        android:text="techsolpoint.com"/>

</LinearLayout>
 

Code for  rv_item.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:padding="5dp"
    android:id="@+id/ll_item"
    android:layout_height="190dp">

    <android.support.v7.widget.CardView
        app:cardCornerRadius="10dp"
        android:layout_gravity="center_vertical"
        android:layout_margin="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:background="#ffffff"
            android:layout_height="match_parent">
            <RelativeLayout
                android:layout_width="match_parent"
                android:background="#000000"
                android:layout_height="190dp">
                <ImageView
                    android:alpha="0.5"
                    android:id="@+id/item_img"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    android:src="@drawable/seo1"/>
                <TextView
                    android:layout_marginTop="50dp"
                    android:id="@+id/article_name"
                    android:layout_width="match_parent"
                    android:layout_height="30dp"
                    android:text="My First Article on RecyclerView"
                    android:textColor="#ffffff"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:gravity="center"/>
                <TextView
                    android:background="@drawable/bg_button"
                    android:layout_centerInParent="true"
                    android:layout_below="@+id/article_name"
                    android:layout_width="100dp"
                    android:layout_height="30dp"
                    android:text="Read"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:textColor="#1ff8e9"
                    android:gravity="center"/>
            </RelativeLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
 

Code for RvAdapter.java file.

package com.example.asus.recyclerviewjson.adapter;

import android.content.Context;
import android.content.Intent;
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.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.asus.recyclerviewjson.NewActivity;
import com.example.asus.recyclerviewjson.R;
import com.example.asus.recyclerviewjson.model.Rvdata;

import java.util.ArrayList;

/**
 * Created by  techsolpoint.com on 3/18/2018.
 */

public class RvAdapter extends RecyclerView.Adapter<RvAdapter.RvViewHolder>{

    Context context;
    ArrayList<Rvdata> rvdatas;

    public RvAdapter(Context context,ArrayList<Rvdata> rvdatas){
        this.context = context;
        this.rvdatas = rvdatas;
    }

    View view;
    @Override
    public RvAdapter.RvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        view = inflater.from(parent.getContext()).inflate(R.layout.rv_item,parent,false);
        RvViewHolder rvViewHolder = new RvViewHolder(view);
        return rvViewHolder;
    }

    @Override
    public void onBindViewHolder(RvAdapter.RvViewHolder holder, int position) {
        final Rvdata  rvdata = rvdatas.get(position);
        holder.itemName.setText(rvdata.getName());
        String imgUrl = rvdata.getImg();
        Glide.with(context)
                .load(imgUrl)
                .thumbnail(0.5f)
                .into(holder.itemImg);
        holder.llItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context,NewActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });
    }

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

    public class RvViewHolder extends RecyclerView.ViewHolder {
        TextView itemName;
        ImageView itemImg;
        LinearLayout llItem;
        public RvViewHolder(View itemView) {
            super(itemView);

            itemName = itemView.findViewById(R.id.article_name);
            itemImg = itemView.findViewById(R.id.item_img);
            llItem = itemView.findViewById(R.id.ll_item);
        }
    }
}
 

Code for Rvdata.java file.

package com.example.asus.recyclerviewjson.model;

public class Rvdata {
    public int id;
    public String name;
    public String img;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public int getId() {
        return id;
    }

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

Screenshot

Fetch JSON data using Volley library and display it in RecyclerView — Android Studio
Tagged on:

3 thoughts on “Fetch JSON data using Volley library and display it in RecyclerView — Android Studio

  • April 29, 2018 at 11:16 am
    Permalink

    Thanx for sharing your knowlwdge.

    Reply
  • May 11, 2018 at 12:15 am
    Permalink

    I like the code as i used it and it works fine. great help. Thanks 🙂

    Reply
  • November 10, 2018 at 6:22 pm
    Permalink

    I must show my love for your kind-heartedness giving support to those individuals that have the need for help with this important subject matter. Your real commitment to getting the solution along had become particularly beneficial and have usually enabled girls just like me to arrive at their desired goals. This valuable recommendations can mean a great deal to me and extremely more to my colleagues. Thank you; from everyone of us.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *