Android RecyclerView Using JSon Parsing PHP MySQL Data

Android RecyclerView is the advance version of android simple ListView. It comes with CardView which is a animated view widget comes with drop shadow, rounded corner radius and inner shadow view. RecyclerView can handle large amount of data comes into multiple sets and they also could scroll very efficiently on android mobile phone screen.

Contents in this project :

  1. Watch the live demo video of this project.
  2. Start a new android application project on Studio.
  3. Create MySQL database with table on your local or online hosting server.
  4. Create PHP Script to convert MySQL data into JSon data.
  5. Test the PHP Script.
  6. Add internet permission in your project.
  7. Add RecyclerView ,CardView and Volley library in your Android Studio project.
  8. Start Coding.

List of Java file in this project :

  • MainActivity.java
  • RecyclerViewCardViewAdapter.java
  • subjects.java

List of layout files in this project :

  • activity_main.xml
  • cardview.xml

List of PHP files in this project :

  • DataBaseConfig.php
  • Subjects.php

1. Watch the live demo video of this project :

2. Start a new android application project on Studio.

3. Create MySQL database with table on your local or online hosting server :

Create MySQL database and then inside that a table which will contain the items.

4. Create PHP Script to convert MySQL data into JSon data :

This script will automatically convert the MySQL db data into JSon form.

Code for DatabaseConfig.phpfile.

 <?php

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

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

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

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

?>

Code for Subjects.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 ListViewDataTable";

$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();
?>

5. Test the PHP Script : Next step is to run the uploaded php script URL which will display the JSON .

6. Add internet permission in your project : Open your project’s AndroidManifest.xml file and internet permission inside it.

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

 7. Add RecyclerView ,CardView and Volley library in your Android Studio project :

1. Open your project’s build.gradle(Module:App) file.

2. Add below code inside dependencies scope.

 compile 'com.android.support:appcompat-v7:25.1.0'

 compile 'com.android.support:cardview-v7:25.0.+'

 compile 'com.android.support:recyclerview-v7:25.0.+'

 compile 'com.mcxiaoke.volley:library:1.0.19'

3. Screen shot of build.gradle(Module:app) file after adding above 4 libraries :

8. Start Coding :

Code for MainActivity.java file.

package com.androidjson.recyclerviewcardviewjson_androidjsoncom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import com.android.volley.RequestQueue;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    List<subjects> subjectsList;

    RecyclerView recyclerView;

    RecyclerView.LayoutManager recyclerViewlayoutManager;

    RecyclerView.Adapter recyclerViewadapter;

    ProgressBar progressBar;

    String HTTP_JSON_URL = "http://androidblog.esy.es/AndroidJSon/Subjects.php";

    String GET_JSON_FROM_SERVER_NAME = "subjects";

    JsonArrayRequest jsonArrayRequest ;

    RequestQueue requestQueue ;

    View ChildView ;

    int GetItemPosition ;

    ArrayList<String> SubjectNames;

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

        setContentView(R.layout.activity_main);

        subjectsList = new ArrayList<>();

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

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

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(recyclerViewlayoutManager);

        progressBar.setVisibility(View.VISIBLE);

        SubjectNames = new ArrayList<>();

                JSON_DATA_WEB_CALL();

        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)) {

                    GetItemPosition = Recyclerview.getChildAdapterPosition(ChildView);

                    Toast.makeText(MainActivity.this, SubjectNames.get(GetItemPosition), Toast.LENGTH_LONG).show();
                }

                return false;
            }

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

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

    }

    public void JSON_DATA_WEB_CALL(){

        jsonArrayRequest = new JsonArrayRequest(HTTP_JSON_URL,

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

                        progressBar.setVisibility(View.GONE);

                        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++) {

            subjects GetDataAdapter2 = new subjects();

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

                GetDataAdapter2.setName(json.getString(GET_JSON_FROM_SERVER_NAME));

                SubjectNames.add(json.getString(GET_JSON_FROM_SERVER_NAME));


            } catch (JSONException e) {

                e.printStackTrace();
            }
            subjectsList.add(GetDataAdapter2);
        }

        recyclerViewadapter = new RecyclerViewCardViewAdapter(subjectsList, this);

        recyclerView.setAdapter(recyclerViewadapter);

    }
}

Code for RecyclerViewCardViewAdapter.java file.

package com.androidjson.recyclerviewcardviewjson_androidjsoncom;

/**
 * Created by Juned on 1/20/2017.
 */
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.content.Context;
import java.util.List;

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

    Context context;

    List<subjects> subjects;

    public RecyclerViewCardViewAdapter(List<subjects> getDataAdapter, Context context){

        super();

        this.subjects = 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 holder, int position) {

        subjects getDataAdapter1 =  subjects.get(position);

        holder.SubjectName.setText(getDataAdapter1.getName());

    }

    @Override
    public int getItemCount() {

        return subjects.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public TextView SubjectName;


        public ViewHolder(View itemView) {

            super(itemView);

            SubjectName = (TextView) itemView.findViewById(R.id.TextViewCard) ;


        }
    }
}

Code for subjects.java file.

package com.androidjson.recyclerviewcardviewjson_androidjsoncom;

/**
 * Created by Juned on 1/20/2017.
 */

public class subjects {

    String SubjectName;

    public String getName() {

        return SubjectName;
    }

    public void setName(String TempName) {

        this.SubjectName = TempName;
    }

}

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.recyclerviewcardviewjson_androidjsoncom.MainActivity">

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

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


</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="#FF9800"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/TextViewCard"
        android:textColor="#ffff"
        android:textSize="20dp"
        android:text="Sample"
        android:layout_gravity="center"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"/>

</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.recyclerviewcardviewjson_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 :

RecyclerView

Download Code

2 Comments

  1. Hi there, I’m making a app which gets product info from my server and i add it to a recycleviewer or list and then i want to select the product and open in a diferent layout with all my product details. This is a great example for a begginer like me, i just wanted to ask how i could change screens when i click one of the products, like when you click one of the languages, and how would i call all my product details,

    Thank you in avance

    Cheers

    • Thanks Silva for comment you can read my this tutorial this will surely help you :-https://androidjson.com/filter-json-data-using-php-mysql/

Leave a Reply

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