Android RecyclerView ListView with ImageView TextView JSON parsing custom data example tutorial

How to retrieve & fetch JSON form URL on server from MySQL database and also the image path is stored into PhpMyAdmin database.

In this tutorial we are going to develop fully dynamic android application with RecyclerView, CardView, ImageView, TextView in the form of ListView using JSON data that is coming from MySQL database which is store on server. We are using PHP file to convert MySQL db data into JSON format and the most important and amazing thing of this project is that all the image is uploaded on server and their paths will be stored into database so while parsing JSON the image path is alos directly coming from server. So here is the complete step by step tutorial for Android RecyclerView ListView with ImageView TextView JSON parsing custom data example tutorial .

android-project-download-code-button

Note: Read below steps very carefully.

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

build-gradle

2. Please add below code inside your build.gradle ( Module : app ) file to import CardView, RecyclerView, design and Volley library.

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

compile 'com.android.support:design:24.0.0'

compile 'com.android.support:cardview-v7:24.0.0'

compile 'com.android.support:recyclerview-v7:24.0.0'

compile 'com.mcxiaoke.volley:library-aar:1.0.0'

3. Screenshot of build.gradle ( Module : app ) file after adding above code.

custom_listview_library

 

Next step is to start coding.

List of All Java files inside this project :

  1. MainActivity.java .
  2. GetDataAdapter.java .
  3. RecyclerViewAdapter.java .
  4. ServerImageParseAdapter.java .

List of layout XML files in this project :

  1. activity_main.xml .
  2. recyclerview_items.xml .

List of PHP files to convert MySQL db data into JSON :

  1. ImageJsonData.php .
  2. dbconfig.php .

NOTE :  Please add internet permission inside your project’s AndroidManifest.xml file.

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

Screenshot of JSON data :

image_json_data_screenshot

Android RecyclerView ListView with ImageView TextView JSON parsing custom data example tutorial.

Code for MainActivity.java file.

package com.android_examples.recyclerviewimagelistview_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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;

public class MainActivity extends AppCompatActivity {

    List<GetDataAdapter> GetDataAdapter1;

    RecyclerView recyclerView;

    RecyclerView.LayoutManager recyclerViewlayoutManager;

    RecyclerView.Adapter recyclerViewadapter;

    String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/ImageJsonData.php";
    String JSON_IMAGE_TITLE_NAME = "image_title";
    String JSON_IMAGE_URL = "image_url";

    JsonArrayRequest jsonArrayRequest ;

    RequestQueue requestQueue ;

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

        setContentView(R.layout.activity_main);

        GetDataAdapter1 = new ArrayList<>();

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

        recyclerView.setHasFixedSize(true);

        recyclerViewlayoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(recyclerViewlayoutManager);


                JSON_DATA_WEB_CALL();


    }

    public void JSON_DATA_WEB_CALL(){

        jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_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++) {

            GetDataAdapter GetDataAdapter2 = new GetDataAdapter();

            JSONObject json = null;
            try {

                json = array.getJSONObject(i);

                GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));

                GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));

            } catch (JSONException e) {

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

        recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);

        recyclerView.setAdapter(recyclerViewadapter);
    }
}

Code for GetDataAdapter.java file.

package com.android_examples.recyclerviewimagelistview_android_examplescom;

/**
 * Created by JUNED on 6/16/2016.
 */
public class GetDataAdapter {

    public String ImageServerUrl;
    public String ImageTitleName;

    public String getImageServerUrl() {
        return ImageServerUrl;
    }

    public void setImageServerUrl(String imageServerUrl) {
        this.ImageServerUrl = imageServerUrl;
    }

    public String getImageTitleName() {
        return ImageTitleName;
    }

    public void setImageTitleNamee(String Imagetitlename) {
        this.ImageTitleName = Imagetitlename;
    }

}

Code for RecyclerViewAdapter.java file.

package com.android_examples.recyclerviewimagelistview_android_examplescom;
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.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;

/**
 * Created by JUNED on 6/16/2016.
 */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    Context context;

    List<GetDataAdapter> getDataAdapter;

    ImageLoader imageLoader1;

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

        super();
        this.getDataAdapter = getDataAdapter;
        this.context = context;
    }

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

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);

        ViewHolder viewHolder = new ViewHolder(v);

        return viewHolder;
    }

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

        GetDataAdapter getDataAdapter1 =  getDataAdapter.get(position);

        imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();

        imageLoader1.get(getDataAdapter1.getImageServerUrl(),
                ImageLoader.getImageListener(
                        Viewholder.networkImageView,//Server Image
                        R.mipmap.ic_launcher,//Before loading server image the default showing image.
                        android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
                )
        );

        Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);

        Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());

    }

    @Override
    public int getItemCount() {

        return getDataAdapter.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public TextView ImageTitleNameView;
        public NetworkImageView networkImageView ;

        public ViewHolder(View itemView) {

            super(itemView);

            ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;

            networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;

        }
    }
}

Code for ServerImageParseAdapter.java file.

package com.android_examples.recyclerviewimagelistview_android_examplescom;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import android.content.Context;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;

/**
 * Created by JUNED on 6/20/2016.
 */
public class ServerImageParseAdapter {

    public static ServerImageParseAdapter SIAdapter;

    public static Context context1;

    public RequestQueue requestQueue1;

    public ImageLoader Imageloader1;

    public Cache cache1 ;

    public Network networkOBJ ;

    LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);

    private ServerImageParseAdapter(Context context) {

        this.context1 = context;

        this.requestQueue1 = RQ();

        Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {

                    @Override
                    public Bitmap getBitmap(String URL) {

                        return LRUCACHE.get(URL);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {

                        LRUCACHE.put(url, bitmap);
                    }
                });
    }

    public ImageLoader getImageLoader() {

        return Imageloader1;
    }

    public static ServerImageParseAdapter getInstance(Context SynchronizedContext) {

        if (SIAdapter == null) {

            SIAdapter = new ServerImageParseAdapter(SynchronizedContext);
        }
        return SIAdapter;
    }

    public RequestQueue RQ() {

        if (requestQueue1 == null) {

            cache1 = new DiskBasedCache(context1.getCacheDir());

            networkOBJ = new BasicNetwork(new HurlStack());

            requestQueue1 = new RequestQueue(cache1, networkOBJ);

            requestQueue1.start();
        }
        return requestQueue1;
    }
}

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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android_examples.recyclerviewimagelistview_android_examplescom.MainActivity">


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

</RelativeLayout>

Code for recyclerview_items.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:cardElevation="3dp"
    card_view:contentPadding="3dp"
    card_view:cardCornerRadius="3dp"
    card_view:cardMaxElevation="3dp"
    >


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

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/VollyNetworkImageView1"
            android:layout_width="150dp"
            android:layout_height="100dp"
            android:src="@mipmap/ic_launcher"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Image Name"
            android:id="@+id/textView_item"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/VollyNetworkImageView1"
            android:layout_toEndOf="@+id/VollyNetworkImageView1"
            android:layout_marginLeft="20dp"/>

    </RelativeLayout>

    </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.android_examples.recyclerviewimagelistview_android_examplescom">

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

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

Code for PHP files :

Code for ImageJsonData.php file.

<?php
include 'dbconfig.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "SELECT * FROM ImageListViewTable";
$result = $conn->query($sql);

if ($result->num_rows >0) {
 // output data of each row
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
 
} else {
 echo "0 results";
}
 echo $json;
$conn->close();
?>

Code for dbconfig.php file.

  <?php

//This script is designed by Android-Examples.com
//Define your host here.
$servername = "mysql.hostinger.in";
//Define your database username here.
$username = "u288012116_and";
//Define your database password here.
$password = "GArpOsx4KVa0GJDquJ";
//Define your database name here.
$dbname = "u288012116_and";

?>

Screenshots :

Android RecyclerView ListView with ImageView TextView JSON parsing custom data example tutorial

 

RecyclerViewImageView-2

Click here to download Android RecyclerView ListView with ImageView TextView JSON parsing custom data example tutorial project with source code.

Leave a Reply

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