Android Show Multiple JSON Parsing Data inside RecyclerView

How to fetch PHP MySQL student records from server and display inside Custom RecyclerView including CardView.

In this tutorial we would going to create a complete server integrated student data management RecyclerView. This RecyclerView is build using multiple JSON parsing data straight incoming from online server. We would convert the MySQL database records into JSON form using PHP script and parse that JSON into our application. After done all work we would also show the RecyclerView clicked values and print student name on screen using Toast message. You could print any thing from that record as your own requirement. So here is the complete step by step tutorial for Android Show Multiple JSON Parsing Data inside RecyclerView.

Contents in this project Show Multiple JSON Parsing Data inside RecyclerView CardView :

  1. Watch the live demo video.
  2. Create database on your server including table.
  3. Create PHP Script to convert MySQL data into JSON form.
  4. Run the PHP Script to see JSON output on web browser.
  5. Start a new android application development project.
  6. Import RecyclerView, CardView and Volley library.
  7. Add internet permission to your project.
  8. Start Coding.

List of all JAVA files in this project :

  • MainActivity.java
  • RecyclerViewAdapter.java
  • DataAdapter.java

List of all layout files in this project :

  • activity_main.xml
  • cardview.xml

List of PHP files in this project :

  • DatabaseConfig.php
  • StudentDetails.php

1. Watch live demo video :

2. Create database on your server including table :

3. Create PHP Script to convert MySQL data into JSON form :

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "mysql.hostinger.in";

//Define your database username here.
$HostUser = "id632449_androidjson";

//Define your database password here.
$HostPass = "kdfjdfdskljomew9ry3873";

//Define your database name here.
$DatabaseName = "id632449_androidjson";

?>

Code for StudentDetails.php file.

<?php
include 'DatabaseConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM StudentDetailsTable";

$result = $conn->query($sql);

if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
 
} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?>

4. Run the PHP Script to see JSON output on web browser :

5. Start a new android application development project.

6. Import RecyclerView, CardView and Volley library :

Open your projects build.gradle(Module:app) file.

Add compile ‘com.android.support:cardview-v7:25.0.+’ , compile ‘com.android.support:recyclerview-v7:25.0.+’ and compile ‘com.mcxiaoke.volley:library:1.0.19’ .

7. Add internet permission to your project :

Open your AndroidManifest.xml file and write below code.

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

 8. Start Coding of project Show Multiple JSON Parsing Data in RecyclerView:

Code for MainActivity.java file.

package com.androidjson.recyclerviewshowmultipledata_androidjsoncom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.json.JSONArray;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import com.android.volley.RequestQueue;

public class MainActivity extends AppCompatActivity {

    List<DataAdapter> DataAdapterClassList;

    RecyclerView recyclerView;

    RecyclerView.LayoutManager recyclerViewlayoutManager;

    RecyclerView.Adapter recyclerViewadapter;

    ProgressBar progressBar;

    JsonArrayRequest jsonArrayRequest ;

    ArrayList<String> SubjectNames;

    RequestQueue requestQueue ;

    String HTTP_SERVER_URL = "https://androidjsonblog.000webhostapp.com/StudentDetails.php";

    View ChildView ;

    int RecyclerViewClickedItemPOS ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        DataAdapterClassList = new ArrayList<>();

        SubjectNames = new ArrayList<>();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(recyclerViewlayoutManager);

        // JSON data web call function call from here.
                JSON_WEB_CALL();

        //RecyclerView Item click listener code starts from here.
        recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {

            GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

                @Override public boolean onSingleTapUp(MotionEvent motionEvent) {

                    return true;
                }

            });
            @Override
            public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

                ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());

                if(ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {

                    //Getting RecyclerView Clicked item value.
                    RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);

                    //Printing RecyclerView Clicked item clicked value using Toast Message.
                    Toast.makeText(MainActivity.this, SubjectNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_LONG).show();

                }

                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

    }

    public void JSON_WEB_CALL(){

        jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,

                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue = Volley.newRequestQueue(this);

        requestQueue.add(jsonArrayRequest);
    }

    public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){

        for(int i = 0; i<array.length(); i++) {

            DataAdapter GetDataAdapter2 = new DataAdapter();

            JSONObject json = null;
            try {
                json = array.getJSONObject(i);

                GetDataAdapter2.setId(json.getInt("id"));

                GetDataAdapter2.setName(json.getString("name"));

                //Adding subject name here to show on click event.
                SubjectNames.add(json.getString("name"));

                GetDataAdapter2.setSubject(json.getString("subject"));

                GetDataAdapter2.setPhone_number(json.getString("phone_number"));

            }
            catch (JSONException e)
            {

                e.printStackTrace();
            }

            DataAdapterClassList.add(GetDataAdapter2);

        }

        progressBar.setVisibility(View.GONE);

        recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);

        recyclerView.setAdapter(recyclerViewadapter);
    }
}

Code for RecyclerViewAdapter.java file.

package com.androidjson.recyclerviewshowmultipledata_androidjsoncom;

/**
 * Created by Juned on 2/6/2017.
 */

import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;

    List<DataAdapter> dataAdapters;

    public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){

        super();

        this.dataAdapters = getDataAdapter;
        this.context = context;
    }

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

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {

        DataAdapter dataAdapter =  dataAdapters.get(position);

        viewHolder.TextViewID.setText(dataAdapter.getName());

        viewHolder.TextViewName.setText(String.valueOf(dataAdapter.getId()));

        viewHolder.TextViewPhoneNumber.setText(dataAdapter.getPhone_number());

        viewHolder.TextViewSubject.setText(dataAdapter.getSubject());

    }

    @Override
    public int getItemCount() {

        return dataAdapters.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public TextView TextViewName;
        public TextView TextViewID;
        public TextView TextViewPhoneNumber;
        public TextView TextViewSubject;


        public ViewHolder(View itemView) {

            super(itemView);

            TextViewName = (TextView) itemView.findViewById(R.id.textView2) ;
            TextViewID = (TextView) itemView.findViewById(R.id.textView4) ;
            TextViewPhoneNumber = (TextView) itemView.findViewById(R.id.textView6) ;
            TextViewSubject = (TextView) itemView.findViewById(R.id.textView8) ;


        }
    }
}

Code for DataAdapter.java file.

package com.androidjson.recyclerviewshowmultipledata_androidjsoncom;

/**
 * Created by Juned on 2/6/2017.
 */

import java.util.ArrayList;


public class DataAdapter {

    int Id;
    String name;
    String phone_number;
    String subject;


    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public int getId() {

        return Id;
    }

    public void setId(int Id1) {

        this.Id = Id1;
    }


    public String getPhone_number() {

        return phone_number;
    }

    public void setPhone_number(String phone_number1) {

        this.phone_number = phone_number1;
    }

    public String getSubject() {

        return subject;
    }

    public void setSubject(String subject1) {

        this.subject = subject1;
    }

}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.recyclerviewshowmultipledata_androidjsoncom.MainActivity">

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

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/progressBar"
        />

</RelativeLayout>

Code for cardview.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="6dp"
    card_view:cardElevation="6dp"
    card_view:contentPadding="7dp"
    android:padding="10dp"
    android:layout_margin="7dp"
    card_view:cardBackgroundColor="#009688"
    >


    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TableRow>
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="ID : "
                android:textColor="#ffff"
                />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="ID Show Here"
                android:textColor="#ffff"
                />
        </TableRow>

        <TableRow>

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Name : "
                android:textColor="#ffff"
                />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Name Show Here"
                android:textColor="#ffff"/>
        </TableRow>

        <TableRow>

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Phone Number : "
                android:textColor="#ffff"
                />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Phone Number Show"
                android:textColor="#ffff"
                />
        </TableRow>

        <TableRow>

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Subject : "
                android:textColor="#ffff"
                />

            <TextView
                android:id="@+id/textView8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="Subject Show Here"
                android:textColor="#ffff"
                />

        </TableRow>

    </TableLayout>

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

Code for AndroidManifest.xml file.

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

Screenshot:

Show Multiple JSON Parsing Data

Download Code

5 Comments

  1. Hi there, ive been doing a couple of examples in android, using php mysql and android studio, and almost all of them use POST or GET method, i was wondering why you dont need on your examples to stecify the method? btw thank you for your examples really helpfull

  2. I also have a question, if i have more than 4 variables in my table, can i just list 3-4 of them on my recycleview without having any problems?

    • Yes sure just only add 3-4 into your adapter on parsing time . For example i am adding name using GetDataAdapter2.setName(json.getString(“name”)); instead you can add anything into your adapter as you require.

Leave a Reply to Admin Cancel reply

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