Android material design Programming Blog

Android JSON Parsing and display with RecyclerView

This tutorial demonstrates how to do Android JSON Parsing and display with RecyclerView or ListView. The data may be from JSON file or PHP.

To fetch JSON data in android I used java’s builtin class called AsyncTask and HttpUrlConnection and Android JSON Parsing will be done by using JSONArray and JSONObject class and finally, to display the data we use the RecyclerView(Supported in Android support library v7) widget. Let’s get started.

Download Code From Github

Android JSON Parsing Demo


The below is an example of fish data I’m using which has some basic info like image URL, fish name, category, size, and price.


[{"fish_img":"1.jpg","fish_name":"Indian Mackerel","cat_name":"Marine Fish","size_name":"Medium","price":"100"},
{"fish_img":"2.jpg","fish_name":"Manthal Repti","cat_name":"Marine Fish","size_name":"Small","price":"200"},
{"fish_img":"3.jpg","fish_name":"Baby Sole Fish","cat_name":"Marine Fish","size_name":"Small","price":"600"},
{"fish_img":"4.jpg","fish_name":"Silver Pomfret","cat_name":"Marine Fish","size_name":"Large","price":"300"},
{"fish_img":"5.jpg","fish_name":"Squid","cat_name":"Shell Fish","size_name":"Small","price":"800"},
{"fish_img":"6.jpg","fish_name":"Clam Meat","cat_name":"Shell Fish","size_name":"Small","price":"350"},
{"fish_img":"7.jpg","fish_name":"Indian Prawns","cat_name":"Shell Fish","size_name":"Medium","price":"270"},
{"fish_img":"8.jpg","fish_name":"Mud Crab","cat_name":"Shell Fish","size_name":"Medium","price":"490"},
{"fish_img":"9.jpg","fish_name":"Grey Mullet","cat_name":"Backwater Fish","size_name":"Small","price":"670"},
{"fish_img":"10.jpg","fish_name":"Baasa","cat_name":"Backwater Fish","size_name":"Large","price":"230"},
{"fish_img":"11.jpg","fish_name":"Pearl Spot","cat_name":"Backwater Fish","size_name":"Small","price":"340"},
{"fish_img":"12.jpg","fish_name":"Anchovy","cat_name":"Marine Fish","size_name":"Small","price":"130"},
{"fish_img":"13.jpg","fish_name":"Sole Fish","cat_name":"Marine Fish","size_name":"Medium","price":"250"},
{"fish_img":"14.jpg","fish_name":"Silver Croaker","cat_name":"Marine Fish","size_name":"Small","price":"220"}]


The files and steps used in this tutorial as follow.

Adding Dependencies

Open your build.gradle(Module: app) file and add the following dependencies highlighted below and sync your project Gradle.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
    compile 'com.github.bumptech.glide:glide:3.5.2'

Note: You need to replace the version of dependency files added except glide dependency, in my case version is 23.3.0. You can find your build tool version on top of the same page. Fetch JSON and Android JSON Parsing

The step by step procedure as follows.

  1. Immediate after the creation of activity, a call to AsyncFetch class is made to carry out the Asynchronous task.
  2. Before the task execution, onPreExecute() method invokes on the UI thread. In this method, we display a loading message.
  3. doInBackground(Params…), invoked on the background thread immediately after
    onPreExecute() finishes executing. The receiving of data from JSON file using HttpURLConnection class has done in this function.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The data received from server/JSON file is stored and JSON Parsing will be done.
  5. Finally, the data is sent to the adapter to display it on RecyclerView.
package com.androidcss.jsonexample;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        //Make call to AsyncTask
        new AsyncFetch().execute();

    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        protected void onPreExecute() {

            //this method will be running on UI thread


        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                return e.toString();
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();

                // setDoOutput to true as we recieve data from json file

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                return e1.toString();

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");

            } catch (IOException e) {
                return e.toString();
            } finally {


        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            List<DataFish> data=new ArrayList<>();

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.fishImage= json_data.getString("fish_img");
                    fishData.fishName= json_data.getString("fish_name");
                    fishData.catName= json_data.getString("cat_name");
                    fishData.sizeName= json_data.getString("size_name");
                    fishData.price= json_data.getInt("price");

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(;
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();



package com.androidcss.jsonexample;

public class DataFish {

    public String fishImage;
    public String fishName;
    public String catName;
    public String sizeName;
    public int price;

When the user scrolls through RecyclerView, The binding of data to views and recycling of views will be done.

package com.androidcss.jsonexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Collections;
import java.util.List;

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

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;
    int currentPos=0;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        inflater= LayoutInflater.from(context);;

    // Inflate the layout when viewholder created
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;

    // Bind data
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.textSize.setText("Size: " + current.sizeName);
        myHolder.textType.setText("Category: " + current.catName);
        myHolder.textPrice.setText("Rs. " + current.price + "\\Kg");
        myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

        // load image into imageview using glide
        Glide.with(context).load("" + current.fishImage)


    // return total item from List
    public int getItemCount() {
        return data.size();

    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            textFishName= (TextView) itemView.findViewById(;
            ivFish= (ImageView) itemView.findViewById(;
            textSize = (TextView) itemView.findViewById(;
            textType = (TextView) itemView.findViewById(;
            textPrice = (TextView) itemView.findViewById(;




The XML file for

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


The XML file for

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""


        android:text="fish name"


        android:text="Small Text"




Don’t forget to add uses-permission for the internet to your AndroidManifest.xml file, otherwise, it will give access denied error.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.androidcss.jsonexample" >
    <uses-permission android:name="android.permission.INTERNET"/>
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Add yours

  1. please add native admob ads inside recycler view

  2. hello sir i got error that string cannot be converted to jsonarray

    but my json looks like same like yours

    how to fix this??

  3. hi my json type is json array but i get error cannot convert to array list,what should i do?

  4. not working showing exception that it cannot convert to jsonarray.

  5. displaying placeholder image instead of the actual image.

  6. This is my php file :

    echo json_encode($res);

    This is my php output :
    [{"Complaints":"dashboard not working","address":"ville parle"},{"Complaints":"call logs not available","address":"ville parle"}]

    Now the problem is when I run the application it shows nothing

    • Please Log/debug your result variable of onPostExecute() method to see what is returning. Once you confirm the data then you need to parse data accordingly based on your json format.

  7. Hi, I followed your blog post- to log in and it worked very well. Thank you.
    But when you have logged in and entered a new activity, in this new activity you want to parse JSON data, how will the PHP file look like?
    I did that with this code initially:

    $host = 'localhost';
    $user = 'root';
    $pwd = '';
    $db = 'android';
    $conn = mysqli_connect($host, $user, $pwd, $db);
    die("Error in connection : " . $mysqli_connect_error());
    $response = array();
    $sql_query = "select * from users";
    $result = mysqli_query($conn, $sql_query);
    if(mysqli_num_rows($result) > 0){
    $response['success'] = 1;
    $heroes = array();
    while ($row = mysqli_fetch_assoc($result)) {
    array_push($heroes, $row);
    $response['heroes'] = $heroes;
    $response['success'] = 0;
    $response['message'] = 'No data found';
    echo json_encode($response);

    It worked then, but now I don’t know how to modify it after being logged in.

    • Hi Zainab, Could you elaborate your question in more details. I’m confused, whether do you really want to call a new service in the new activity or pass data from login activity to new activity.

      • Thank you for replying, Gururaj.
        I have this code for login (followed fom your tutorial):
        $stmt->bindParam(‘:username’, $username, PDO::PARAM_STR);
        $stmt->bindParam(‘:password’, $password, PDO::PARAM_STR);
        if($stmt->rowCount()) {
        else if(!$stmt->rowCount()) {
        echo $result;
        I just want to get the ID of the user being logged in and pass it to another PHP file through session. I don’t understand how to do that as PHP is not my thing.
        I’ve had this piece of code for fetching ID, but I don’t know how to adjust this in login.php file:
        $id = ‘SELECT id FROM cars WHERE name = :username AND password = :password’;
        $IDresult = mysqli_query($conn, $id);
        $row = mysqli_fetch_assoc($IDresult);
        echo “ID: ” . $row[‘id’];
        $_SESSION[“Id”] = $row[‘id’];

      • I mean yes, I want to pass data from login activity to new activity.

  8. Hi, how add event onClickListener in RecyclerView?

    • There are many ways you can add event listener to your RecyclerView. One way is that you can add event listener in onBindViewHolder method like this.
      myHolder.textFishName.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
      // do something

  9. how do I create a menu with categories in that application getting the data via JSON?

    • Do you mean, how to create menu with RecyclerView?

      • Na verdade eu queria saber qual a melhor maneira de criar um menu (Não importa se é menu drop down ou outro), só queria saber como faço para listar as categorias desse projeto em um menu

      • Actually I wanted to know what the best way to create a menu (No matter if it’s drop down menu or another), just wanted to know how do I list the categories of that project in a menu

  10. This tutorial is great!! Thank you.

  11. Great Tutorial 🙂
    Thanks before, but i have a small doubt about JSON. Are the image from json must be on same directory? and when i create a detail activity and i want passing data from json text and json image how do i do it? I’m very confused about passing data to detail activity.

  12. Hello,
    Actually, in my project, I am using back end as python and Django. This code is working or not.

  13. Big thanks. I want to implement onclick in adapter to open new activity that show details.

  14. Great tutorial thanks! I was wondering how I would go about adding a footer to the recyclerview? Thanks

  15. Setting adapter in AsyncTak is creating a problem(No adapter attached,skipping layout),what could be the alternative.

  16. Lamberto Fredrick Nababan

    April 7, 2017 at 5:23 pm

    Nice tutorial thanks bro…
    Very helpful

    Can you give a tutorial implement this method on tab layout with fragments ?


  17. Nice tutorial thanks bro…
    Very helpful

  18. Hi Gururaj,

    Thanks for the above code. I need a help in populating 2 recycler views from 2 different URLs how do I do that? Is it possible? Because I’m able to populate 2 recycler views with same data.

    Thanks in advance!

  19. Hi Guru,

    May I know how should I do if I want to fetch the SQL data from xampp server using php and display in the list view like the example above? Really appreciate your help.
    Btw your code were awesome!

  20. Great post

  21. i get this error:
    JSONException: Value of type java.lang.String cannot be converted to JSONObject

  22. Hello ,teacher First I like to thank you for this wonderful tutorial, but had trouble during the application (RecyclerView: No adapter attached; skipping layout) ,and messag Error is org.json.jsonexception:value connection of type java.lang.string cannot be converted to jsonarray
    whta the soulation

  23. Haii Gururaj, i have a simple question for you, but its so difficult for me. The question is, how i can change the color of textview if (sample) the size name is middle then the color is red, or when the size name is small then the color of textview is green. Can you help me?

  24. Hi,
    Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview.
    As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment.
    I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it.
    Please help.

  25. Good tutorial…thank you. But its not working,it says No adapter Attached;skipping layout…on the stack trace

    • This question is already been answered. Please go through all comments.

      • Hi,
        please help me with this
        Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview.
        As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment.
        I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it.
        And I have already asked this earlier.
        Please help.

  26. Thank you for the explanations! A question – what is better, to read my JSON file from a server, or to have it in the raw folder, res directory? If the second case, do I need AsynTask?


  27. Hello, We are trying your code, it’s helpful but we got an error “of type JsonObject cannot be converted in JsonArray” and we cannot be able to see our RecyclerView.

  28. This is the best working example I’ve tried. minimal coding!!!
    by the way Gururaj P Kharvi do you have any example for Sorting json values by the use of Spinner? Thanks

  29. this helps me in my project SO GREAT TUTORIAL
    just follow the steps guys!!!!

  30. Hello Gururaj P Kharvi, thanks for the tutorial,can you do one for Json parsing using volley

  31. Hi, This is the best tutorial ever. It will be more awesome if you do a tutorial on using firebase database instead of the usual http call.

    Again, Wonderful tutorial

  32. dis code will work for if i ll use web api as a service

  33. Thank you very nice tutorial it works for me.
    I tried to put the same code in a fragment class but it doesn’t work and the error message is (E/RecyclerView: No adapter attached; skipping layout) what should i change?
    Thank you.

  34. THis is my Main Activity , the app is crashing the error is

    FATAL EXCEPTION: AsyncTask #1
    Process: com.example.task, PID: 14461
    java.lang.RuntimeException: An error occurred while executing doInBackground()

    What am i doing wrong ???

    // Code stripped out

  35. Thanks Mr.GuruRaj,Your blog save me from the Bottle neck problem, I have a query i.e. How to show the multiple images in each row in recyclerview from the API ?. Do you have any idea please share it, Thanks in advance.
    Here is Json String:
    “post”: {
    “pm_post_id”: “2655”,
    “pm_user_id”: “6022”,
    “pm_type”: “1”,
    “pm_title”: “”,
    “pm_description”: “Mobile Testing post”,
    “pm_likes”: “1”,
    “pm_comments”: “1”,
    “pm_contributors”: “0”,
    “pm_report”: “0”,
    “pm_views”: “0”,
    “pm_created_on”: “2016-07-27 17:21:43”,
    “pm_updated_on”: “0000-00-00 00:00:00”,
    “pm_shared_type”: “1”,
    “pm_shared_with”: “0”,
    “pm_tags”: “0,126,0”,
    “pm_timeline”: “1”,
    “pm_step”: “0”,
    “pm_status”: “1”,
    “pm_epid”: “0”
    “images_count”: 5,
    “images”: [
    “pg_gallery_id”: “2975”,
    “pg_name”: “iphone.jpeg”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2976”,
    “pg_name”: “iphone5se (1).jpg”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2977”,
    “pg_name”: “profile_blue.png”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2978”,
    “pg_name”: “profile_logo (1).png”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2979”,
    “pg_name”: “elnb.gif”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “post_user”: [
    “first_name”: “Michelle”,
    “last_name”: “Smith”,
    “profile_pic”: “tomisima_src1.jpg”

  36. May I ask a question?

    Why the pdloading dialog doesn’t dismiss after load all data?

    Thank you

    • pdloading.dismiss(); statement on onPostExecute() is duplicated. May be that causing the problem. Please remove one of them and re run your app.

  37. I’m just getting the following exception when using this way. Any Ideas?

    “org.json.jsonexception value of type java.lang.string cannot be converted to jsonarray”

    • The value coming from your PHP file is string so it’s giving error, you need to pass JSON array. better test your PHP file in browser or display toast message to see what exactly returning.

  38. Hi Gururaj..
    can you help me? How to use putExtra with this tutorial…
    example… from MainActivity to DetailFish?
    because i wanna take this tutorial to my project
    im sorry for bad language english 😀 thanks

  39. Thank the tutorials is great.But why do too much work on the networking call .Why did you use library like Volley to simplify the network since you also used a library (Glide ) to handle images.

    • That’s right. I possibly use Volley or Retrofit library in upcoming tutorials but some of my tutorials may still contains AsyncTask because they may directly relate to my previous article.

  40. Hi Guru,

    Nice example. Can you help me out with JSON parsing, in my project i stuck with nested JSON array.

    • You need to have multiple for loop like this.

      JSONArray jArray = new JSONArray(result);
      for(int i=0;i<jArray.length();i++)
        JSONObject json_data = jArray.getJSONObject(i);
        JSONArray fishArray = json_data.getJSONArray("fishes");
        for(int j=0;j<fishArray.length();j++)
           JSONObject fish_data = fishArray.getJSONObject(j);
           // Extract data ex: fish_data.getString("fish_name");
  41. I understand that is great to learn how to do things using only the android apis. But why not use something more modern like retrofit + rxjava or even just retrofit? You could to the exact same thing with a lot less code! When i started using retrofit i decided i would never go back again! 🙂

  42. Can the recyclerview mix with cardview to make more interactive?

  43. Ty for this code and tutorial

  44. Bro is there any way I can get data in a filtered range eg. My table contains values from 1000 to 10000 and I want when user clicks on 1000-2000 button only that data will be shown in recycler view

    • When user clicks on range button, send those values to PHP(say 1000 and 2000) and apply limit(select * from table1 limit 1000,2000) in your query. For example, PHP code look like this

      $range_from = $_POST['from'];
      $range_to = $_POST['to'];
      $sql = 'select * from table1 limit :range_from,:range_to';
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(':range_from', $range_from, PDO::PARAM_INT);
      $stmt->bindParam(':range_to', $range_to, PDO::PARAM_INT);
  45. Hi Gururaj,

    I just want to voice my opinion in that this is one of the best online android tutorials on how to fetch/retrieve items from MySQL. It’s really well written, clearly understandable and works out of the box.

    In my project I have about 100 items that I fetch and I want to implement a favourites feature. I already have my favourite button with an onClick ready to go, can you please guide us to add/remove fetched items (text and images) to a “favorites” activity using SharedPreferences please? There doesn’t seem to be any good online examples of this feature.

    Much appreciated, thank you.

    • In your scenario, SQLite works well over SharedPreferences. I recommend you to use SQLite(Android inbuilt database engine) and please refer Android SQLite Database tutorial on TutorialsPoint.

      • Gururaj,

        I learned about sqlite yesterday (thank you for mentioning it) and then modified the adapter class to include the code (onClick) to insert NAME and URL to sqlite. I used Android Studio to extract the sqlite db onto my computer and then browsed the db, I actually see the values stored in the correct db, table and columns.

        ..Now the challenge is to actually view the data inside a new Favorites activity using recycle view and cardview.

        • Sorry for late reply. Hope you done with your problem.

          • Gururaj with your suggestion I was able to get a step further, however I’m facing an issue now. I can read/write to sqlite in my adapter class, however I need to read the db and change the color of a textview depending on the value of the url. If the db url matches the current url value inside card view then the color of a textview should be “blue”. If the current url doesn’t match what is inside the db then the color should be “red”. I know I need to do this operation outside the adapter class and away from onBindViewHolder for performence but not sure how yet.

            UsersAdapter.Java =

            Basically fontFamilyText3.setTextColor(ContextCompat.getColor(context, R.color.dot_dark_screen1)); inside my adapter should be blue if the url matches what is already inside the db, if not it should be blue.

            I’m stumped in programatically making this.

          • Gururaj P Kharvi

            June 19, 2016 at 6:41 am

            Apart from changing color, the favorite(add and display) functionality works perfect right?

          • Gururaj,

            You are correct. Apart from changing color, the favorite(add and display) functionality works perfectly.

          • Gururaj P Kharvi

            June 23, 2016 at 4:51 am

            In your code, I din’t see any retrieve of data from SQLite(only Insert and Delete) and little confusion in understanding. It will be good if you host your project on GitHub with necessary files so that i can run on my machine and get you solution.

  46. Hi, lovely tutorial, simple and clean. Very learning a lot and receiving much help from this. But i was wondering, what if the Async method is actually in a fragment, as i am using a fragment. What can i do to achieve the findViewById, currently i cannot do it. Hope you can reply me 🙂

    • @Bowie

      Use following lines of code if you are using Async in fragment. Replace the similar code on onPostExecute(String result) method. For your understanding, i marked the changes made in code.

      // Setup and Handover data to recyclerview
      mRVFishPrice = (RecyclerView)getView().findViewById(;
      mAdapter = new AdapterFish(getActivity(), data);
      mRVFishPrice.setLayoutManager(new LinearLayoutManager(getActivity()));
  47. Hi Guru,

    May I know how should I do if I want to fetch the SQL data from xampp server using php and display in the list view like the example above? Really appreciate your help.
    Btw your code were awesome!

    • To fetch data from php the method is same as above. The small change you have to do is specify .php file in place of .json file.

      note: In PHP you need to encode your data to json data. Use json_encode() function in PHP to encode data. See example below.

                $sql = 'SELECT fish_img,fish_name, cat_name, size, price  FROM tbl_fish';
                $statement = $connection->prepare($sql);
      				$row_all = $statement->fetchall(PDO::FETCH_ASSOC);
      				header('Content-type: application/json');
         		  		echo json_encode($row_all);

      If you don’t know how to test your app with XAMP or WAMP then please follow the below steps.

      1. You need to find the IPV4 address of your computer. If you are using windows system, then you can open command prompt and type ipconfig for ipv4 address.
      2. Make sure XAMP is running, Now open your browser and enter your ipv4 address and go. If you see result same as result when you enter localhost then you can proceed to next step and if some error you see then you may need to map your xamp localhost to your computer ipv4 address. Unfortunately, i don’t know how to do with xamp server but i know how to in wamp server. If you are interested in installing wamp, you can refer How to install and setup PHP and MySql in windows 10 and 7 tutorial and in wamp to map your localhost to ipv4 address, goto menu and click on put online. The following figure depict the same.
        Wamp server put online
      3. In your android code enter address as

        For example

        (please note that which is same as


        and entering address with localhost does not work with android, you should specify ipv4 address only)

      4. Now, run your app in emulator to see result and if you want to run your app on your android mobile then make sure that both of your computer and mobile connected to same wifi router.
  48. How to create JSON file?

    • Gururaj P Kharvi

      May 9, 2016 at 6:48 am

      JSON file can be created with extension as .json or even .txt(text file) also works. JSON has its own syntax to follow when deal with content, for example if i put some data inside square brackets then it treated as array. If you have your data and you want to organize that data then you can create json file and feed your data appropriately and give it to system(in my case it’s android) that understands your json data.

      If you understand what XML files are, i think you understand the purpose of JSON too.

      For more information you can refer json tutorial on w3schools

Leave a Reply

Your email address will not be published.


About | Policy | Disclaimer

Creative Commons LicenceUp ↑