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.

76 Comments

  1. THIS IS THE BEST TUTORIAL OF WORLD!! THANKS MAN!!!!

    • Thanks Marco.

      • wooow all along i’ve been struggling with my project,,,,,,,,,,, thax very much sir!

        • Welcome lubwama .

          • Sir, why am i getting this error

            java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference
            at com.android.volley.Request.(Request.java:136)
            at com.android.volley.toolbox.ImageRequest.(ImageRequest.java:71)
            at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219)
            at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:171)
            at com.example.user.haapps.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:50) at com.example.user.haapps.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:18)

          • Kiko just download and install the whole project.

  2. After run the code, I got the following errors :

    RecyclerView: No adapter attached; skipping layout

    How to solve this issue?

  3. Thank you for the good tutorials sir.
    I have a question. could you also either make a small tutorial on how to save imagepath in sqlite and save image to external using a content provider. am still not getting how the inserted uri gets the path of the image in the_data column…but I know there’s the opefilehelper doing its job. And now comes the problem…how does the image from a server get saved to the folder on external sd. Thank you for any guidance

    • Sure juliusham .

      • Good secondly i have been able to save the uri of the photo to sqlite using this
        Uri insertedUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
        values.put(“_data”, dataFile.getAbsolutePath());

        The _data column points to the exact location of the image on the SD.
        The content_uri is supposed to be read by the openOutputStream
        like so getContentResolver().openOutputStream(myRowUri));
        but i dont know how to downloadn the json image to the folder and point to the _data column. i have not found a good tutorial about it either. and pointer to any info will be gladly appreciated, thx

  4. hi
    i can not download code
    please help me??!!!!

  5. Thank you for the good tutorials,
    I have a question:
    this is my json :http://mobileapp1.downapps.ir/get_data.php
    but After Placement i can not get in my app,
    i like get 2 item : “title” , “image”
    can you help me??!!!!

    • Set your table row title in the JSON_IMAGE_TITLE_NAME like i did and JSON_IMAGE_URL as your image url . In your case just define JSON_IMAGE_TITLE_NAME = “title” & JSON_IMAGE_URL = “image” and run the app .

      • yes i did it but do not work
        in json I have “ads” i think i must get “ads” and after that get “title” and “image”.
        is it correct ?
        if is correct ,help me for code
        Thank you:)

  6. JM Please help me when i pass this url,, http://192.168.2.13/sushil/versionjson.php
    error will be come. How to solve this problem.

  7. hi
    I want , after display Images ,caching in my storage
    please help me, thank you

  8. how to make the list can click and get what is the user click?

  9. how to get filtered data from mysql database in recyclerview .
    eg.
    If i have 1000 cell phones details with five different brands.
    now if enter a name of one brand in edittext in first xml and it will show me that particular brand cell phones in second xml which contains recyclerview.

    i have php query like “select * from moblie where brand= ‘ $brand ‘ “;

    thanx.

    • Krupal in this the easiest method is to create 5 different tables and each table hold a particular brand detail so on list selection just open the new activity and call that php json parsing url .

      • its easy for 5 brands .
        suppose i have more then 50 brands . than its hard to create 50 tables.
        and call all the methods for each brand .

        • Yes Krupal then you have to use php for json parsing like “select * from moblie where brand= ‘ $brand ‘ “; you already said but i have not try that . But for you soon i will upload a new tutorial regarding to your query .

  10. Nice Tutorial. It’s Working.
    I have one question How to create the image no margin with left screen?

  11. The best Tutorial !!! good job

  12. thanks a lot,
    this is so good,
    may i know how to write onclicklistener for this cardview

  13. Hello sir, In network image view i can’t get image from my localhost but i get content from the same database, and my project run but without image please solve my problem or send my solution on my email id. thanks.

  14. How make script for MSQL get imagens?

  15. ok I got it!
    Thank you

  16. why i cant see the data when i open the app, i am use localhost for my DB and nothing error in my android but i cant see the data and i just got blank

    • Iqbal did you placing your local system ip before the PHP Url .

      • i think my url is right, when i check the logcat i found some error “RecyclerView: No adapter attached; skipping layout..”
        BTW after i download your project i only changes the php url with my local mySql DB

  17. Hi
    Good Project. Thanks for the tutorial. I need your help . How we can fetch the images with id.please help.

  18. i have a problem.

    After run the code, I got the following errors :
    RecyclerView: No adapter attached; skipping layout..
    i done download your project and run it.but still answered. RecyclerView: No adapter attached; skipping layout.
    How to solve this issue?please help me

  19. Sir do you have any tutorial for update after insert this type of data
    if have then please share sir its very important to me

  20. i want to update after clicking particular item and then update its name and other things

  21. Thank u so much sir

  22. Diego Abel Canete Vera

    BEST TUTORIAL!!!
    how can i implemente onclicklistener in order to get the name from the cardView?

  23. its a nice tutorial thank you..but i am facing a problem when i run the project ,the tittle displays but the images do not display i dont know where i heve gone wrong because i copied everything from you

  24. hallo sir,
    great tutorial, 1 question
    how to delete and update/edit item this project(crud basic) tks

  25. how add search functionality to this type of json project or to this project only

    thank you in advance

Leave a Reply

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