JSON Parsing in Android – Fetching From MySQL Database

Hey guys, do you want to learn about JSON parsing in Android? If “YES” then today we will learn fetching values from MySQL database as JSON then in the Android side we will parse that JSON data.  It is useful when you want to retrieve your stored data on MySQL database. So let’s start our Android JSON Parsing Tutorial.

What is JSON?

Before moving further, I would like to explain that what is JSON. If you already know about JSON, then you can skip this part.

JSON stands for  JavaScript Object Notation. It is a widely used data interchange format. It is lightweight easy to understand and use.

We use JSON because for machines we need a well-structured format to read the data, as the computer cannot think as human and machine need a fixed structure so that it can be programmed. That is why, we use JSON. There are other formats also available for this like XML, but JSON is used the most. And as a developer you will always be working with JSON.

A JSON can be of two structures.

  1. A collection of Name Value pairs. We call it an object.
  2. A list of values, we can call it an Array.

JSON Object

Below is a JSON Object.

So remember if we are considering a JSON object it will be inside a pair of curly braces { json data }. And inside the curly braces we have the data in name and value pairs. 

JSON Array 

Below is a JSON array.

Now if we talk about a JSON Array then it would be inside square braces  [ JSON array ]. And inside the braces, we can have all the items that we want on the JSON array. In the above-given array, we have only a list of strings. But we can also have the list of JSON objects inside a JSON Array.  See an example below.

If you need more explanation about JSON then you should watch this video.

JSON Parsing in Android

In this post, we will focus on fetching data from MySQL as well. So basically we will create an API that will return us some data in JSON format. For database here we are going to use MySQL and for building the API we will be using PHP.

The Database Table

Assuming I have the following table in my PhpMyAdmin.

JSON Parsing in Android
JSON Parsing in Android

Now here I have a straightforward table, But in real scenarios, you may have complicated tables with many relations or many fields. But the underlying process is the same always. If you want to check a detailed course about Building and Consuming RESTful APIs for your android application, then you should checkout this complete course. Because in this “JSON Parsing in Android” post, we are not digging it much deeper.

Fetching Data from MySQL

  • Now we will fetch the values from the table. For this go to htdocs. (c:/xampp/htdocs) and create a new folder there. You can name your folder anything you want. I have named it Android.
  • Inside that folder create a php script named getdata.php and write the following code.

  • Now when you will open this script in your browser you will see the following. And it is nothing but our RESTful API that is giving us some data. And this data is easy to parse in our Android Code.
android json parsing
Fetched JSON
  • You see we have the data in JSON format. Now our PHP and MySQL part is over, lets learn JSON Parsing in Android.

Android JSON Parsing

Creating a new Android Studio Project

  • First we will create a new Android Studio Project. So create a project with any name using an EmptyActivity.

Creating User Interface

  • Now we will fetch the data and will display the fetched heroes in a ListView. So for this we will create a ListView in our activity_main.xml.

Consuming the API to Fetch JSON in Android

  • This is the most important part.
  • The first thing we need is the URL to our PHP Script that we created. Remember using localhost will not work.
  • So first open command prompt and write ipconfig command. It will show you some IPs (Make sure your xampp is running).

Accessing Localhost from Emulator

  • Now you will see some IPs you need to try replacing localhost with these IPs and test whether your emulator can access your host or not.
android json parsing
Accessing Localhost in Emulator

Accessing Localhost from Real Device

  • If you are having a real device then what you can do is, first connect your real device and computer using your device’s hotspot.
  • Now again in the list of IPs you have to use the IP of WiFi.
android json parsing
Wireless LAN IP

The Web Service URL

  • The PHP file that we created is called a Web Service. And we access that service using a URL. So before we used the following URL.

  • But remember using localhost will not work. You have to replace the localhost with the IP that is working in your case. So for my case the URL would be.

Fetching JSON String

  • Now we will fetch the JSON String from the server using the URL.
  • For this we will use an AsyncTask. The following code snippet will explain this.

  • Now you can call the above method in onCreate().

Allowing Internet Permission

  • But a network operation requires internet permission as well. So before testing it define internet permission in your AndroidManifest.xml.

  • But adding the internet permission alone is not enough, because our API is using the http protocol (it is not secured). And when the API we are using is using non https then we need to add one more thing in our project.

Allowing HTTP (Non Secured Connection)

  • You need to define usesCleartextTraffic=”true” as a property for your application tag inside AndroidManifest.xml. For details, see below my AndroidManifest.xml file.

  • You can see just after the <application line we have android:usesCleartextTraffic=”true” and it is to allow the application to communicate with non secured URLs (HTTP URLs).
  • Now run the application and you should see the JSON String.
android json parsing
Fetching JSON
  • So we have the JSON from server to our Android Device. The only thing remaining now is parsing and reading this JSON. It is also very easy. So lets do this.

JSON Parsing in Android

  • This is the last part of this JSON Parsing in Android Tutorial. We will parse the JSON and will display it to the ListView.
  • So for this I have created a new method named loadIntoListView(String json). 

  • Now we will call this method inside onPostExecute() method of AsyncTask.

The complete Code

  • Now here is the complete code of MainActivity.java.

  • Now you can run the application.
android json parsing
JSON Parsing in Android
  • Bingo! It is working absolutely fine.

JSON Parsing in Android Source Code Download

  • If you are having any confusions or troubles following the post, then you can download my source code from below as well.

JSON Parsing in Android Source Code

So thats all for this Android JSON Parsing Tutorial friends. Feel free to leave your comments if having any query or confusion. Thank You 🙂

54 thoughts on “JSON Parsing in Android – Fetching From MySQL Database”

  1. can you please explain how to implement a listview with images whose url is stored in mysql no json files are involved , i am trying to do this but its not working using xampp server.

    please respond soon.

    Reply
  2. hi
    tnx bro for this best tutorial
    i’m new developer
    i have a mysql database with users table that it has username , password , id
    my question is how i can send username and get that username id ????
    plz help me 🙁

    Reply
  3. Exception is :
    java lang NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference

    Reply
  4. Hai,
    I am new to android. Need to retrieve a data from mysql using php based on the user given input in textbox. Can you help me.

    Thanks in advance

    Reply
  5. hi …

    i am too can u explain me how to get lat and longitutde stored in database need to retrive in map and to mark that place?????

    Reply
  6. I just created the same project using the code above, but i get an exception when i press Parse JSON button
    ERROR Fatal Exception when calling showData() method. it seems like it return null from the data base

    Reply
  7. when i start my apllication .
    Unfortunately Listview has stopped
    (ListView is my apllication name )
    this what an error im facing plz help me out

    Reply
  8. Hi sir,thanks for the lovely tutorial.But i have a question.The question is–How to get a particular json(particular data not all),’like only data of a single person whose id is 5′.

    Reply
  9. Can u kindly make the one that has an editText for entering a value or Id then a button that when is clicked , it fetches the specific records and displays. Thank you.

    Reply
  10. Thanks Bro It works.

    Im working with Login And Display the user information. did you have any tutorial with the same project im working with?. Can you Send here the Link if you have. Thanks . Im looking forward with your updated tutorials.

    Reply
  11. Great tutorial 🙂 Keep up the good work dude 🙂

    I have some doubts , Can you please post an tutorial on tableview (i.e) Fetch data from database and display it in table format in android . Instead listview can you post it in tableview ? It would be helpful to me 🙂

    Thank you dude 🙂

    Reply
  12. Hello, thank you for your coding. It really helpful for me. Can you help me with onclick item on the listview for simple adapter. Thank you

    Reply
  13. this is very helpful thank you…

    So how to do the same retrieve concept with markers on android using google maps ? To retrieve the lat and lang?

    Reply
  14. This tutorial is very helpful.. What do I do, if I want to assign dynamic checkbox to the listview which is already retrieved from mysql? Pls ans its urgent

    Reply
  15. I’m so glad that I’ve found this tutorial. It solved my problem in life. 🙂 I mean with my android project.

    Reply
  16. Hello, I am getting following error can anyone help me in solving this

    “org.json.JSONException: Value <? of type java.lang.String cannot be converted to JSONArray"

    Reply
  17. Guys, thank you for the simple and straight forwatd code. it runs and am happy ( I had spend days searching but not finding).

    Thank yoou very much

    Reply
  18. hi, i m following ur tutorial, but every statement using “->” in php, always showed in browser n it does not execute. plz help. Thank u

    Reply
  19. hey belal, error a java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)

    Reply
  20. hey belal erorr java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)

    Reply
  21. nice tutorial,but in my android project i have an “edit text” based on that i want to fetch and display the result how to do it…
    and my php code looks like this:

    how to pass datas from android studio and get the required result

    Reply
  22. hi buddy I tried yourcodes it works, but when I call third item from mydatabase ,app doesnt show anything I added “email” item extra to my database its like id,name,email it work only with these two items id and name when ı add 3rd item it doesnt show data to layout pls help thanks 🙂

    Reply
  23. Thank you for the tutorial, i am getting the error below

    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONArray.(JSONArray.java:92)
    at org.json.JSONArray.(JSONArray.java:108)
    at com.visionarymindszm.textfieldfromserver.MainActivity.loadIntoListView(MainActivity.java:114)
    at com.visionarymindszm.textfieldfromserver.MainActivity.access$000(MainActivity.java:19)
    at com.visionarymindszm.textfieldfromserver.MainActivity$1GetJSON.onPostExecute(MainActivity.java:59)
    at com.visionarymindszm.textfieldfromserver.MainActivity$1GetJSON.onPostExecute(MainActivity.java:41)

    Reply
  24. Thank you for the tutorial, i am getting this error below

    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONArray.(JSONArray.java:92)
    at org.json.JSONArray.(JSONArray.java:108)
    at com.visionarymindszm.textfieldfromserver.MainActivity.loadIntoListView(MainActivity.java:114)
    at com.visionarymindszm.textfieldfromserver.MainActivity.access$000(MainActivity.java:19)
    at com.visionarymindszm.textfieldfromserver.MainActivity$1GetJSON.onPostExecute(MainActivity.java:59)
    at com.visionarymindszm.textfieldfromserver.MainActivity$1GetJSON.onPostExecute(MainActivity.java:41)

    Reply
  25. Thank you sir it works Jazak Allah . Now I want to send parameter like id to the php help me sir how to send parameter

    Reply
  26. Hi, thanks for the tutorial, everything works fine except one, it’s returning null in android:
    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference

    Reply
  27. During the development and testing in the Emulator and also on the phone all the data are getting properly fetched and displayed as expected… and everything is working perfectly fine. Then created a bundle APK

    Now, upload the same APK bundle in Google play store.

    Now, Download the App from the Google Play store after approval … While running the app, No data is showing up… Instead it is showing “Null”

    What can be the issue…. Even tried with IP address of the $servername =”10.100.100.10″; still not working. infact started throwing error…

    Hosted in hostgator and using the myPhp SQL…

    Reply

Leave a Comment