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.
Table of Contents
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.
- A collection of Name Value pairs. We call it an object.
- A list of values, we can call it an Array.
JSON Object
Below is a JSON Object.
1 2 3 4 5 6 7 8 9 | { "name":"Belal Khan", "address":"Ranchi", "college":"St. Xavier's College", "age":24, "dob":"30-04-1993" } |
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.
1 2 3 4 5 6 7 8 | [ "Spiderman", "Iron Man", "Captain America", "Thor" ] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | [ { "name":"Belal Khan", "address":"Ranchi", "college":"St. Xavier's College", "age":24, "dob":"30-04-1993" }, { "name":"Sunny Kumar", "address":"Ranchi", "college":"JRU", "age":24, "dob":"20-04-1994" }, { "name":"Ramiz Khan", "address":"Ranchi", "college":"St. Xavier's College", "age":22, "dob":"30-04-1993" } ] |
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.

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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php //these are the server details //the username is root by default in case of xampp //password is nothing by default //and lastly we have the database named android. if your database name is different you have to change it $servername = "localhost"; $username = "root"; $password = ""; $database = "android"; //creating a new connection object using mysqli $conn = new mysqli($servername, $username, $password, $database); //if there is some error connecting to the database //with die we will stop the further execution by displaying a message causing the error if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //if everything is fine //creating an array for storing the data $heroes = array(); //this is our sql query $sql = "SELECT id, name FROM heroes;"; //creating an statment with the query $stmt = $conn->prepare($sql); //executing that statment $stmt->execute(); //binding results for that statment $stmt->bind_result($id, $name); //looping through all the records while($stmt->fetch()){ //pushing fetched data in an array $temp = [ 'id'=>$id, 'name'=>$name ]; //pushing the array inside the hero array array_push($heroes, $temp); } //displaying the data in json format echo json_encode($heroes); |
- 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.

- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedlearning.androidjsonparsing.MainActivity"> <!-- this is our listview where we will display the fetched data --> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" /> </RelativeLayout> |
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.

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.

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.
1 2 3 | http://localhost/Android/getdata.php |
- 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.
1 2 3 | http://192.168.101.1/Android/getdata.php |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | //this method is actually fetching the json string private void getJSON(final String urlWebService) { /* * As fetching the json string is a network operation * And we cannot perform a network operation in main thread * so we need an AsyncTask * The constrains defined here are * Void -> We are not passing anything * Void -> Nothing at progress update as well * String -> After completion it should return a string and it will be the json string * */ class GetJSON extends AsyncTask<Void, Void, String> { //this method will be called before execution //you can display a progress bar or something //so that user can understand that he should wait //as network operation may take some time @Override protected void onPreExecute() { super.onPreExecute(); } //this method will be called after execution //so here we are displaying a toast with the json string @Override protected void onPostExecute(String s) { super.onPostExecute(s); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); } //in this method we are fetching the json string @Override protected String doInBackground(Void... voids) { try { //creating a URL URL url = new URL(urlWebService); //Opening the URL using HttpURLConnection HttpURLConnection con = (HttpURLConnection) url.openConnection(); //StringBuilder object to read the string from the service StringBuilder sb = new StringBuilder(); //We will use a buffered reader to read the string from service BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); //A simple string to read values from each line String json; //reading until we don't find null while ((json = bufferedReader.readLine()) != null) { //appending it to string builder sb.append(json + "\n"); } //finally returning the read string return sb.toString().trim(); } catch (Exception e) { return null; } } } //creating asynctask object and executing it GetJSON getJSON = new GetJSON(); getJSON.execute(); } |
- Now you can call the above method in onCreate().
1 2 3 | getJSON("http://192.168.101.1/Android/getdata.php"); |
Allowing Internet Permission
- But a network operation requires internet permission as well. So before testing it define internet permission in your AndroidManifest.xml.
1 2 3 | <uses-permission android:name="android.permission.INTERNET" /> |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="net.simplifiedcoding"> <application android:usesCleartextTraffic="true" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="AllowBackup,GoogleAppIndexingWarning,UnusedAttribute"> <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> |
- 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.

- 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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private void loadIntoListView(String json) throws JSONException { //creating a json array from the json string JSONArray jsonArray = new JSONArray(json); //creating a string array for listview String[] heroes = new String[jsonArray.length()]; //looping through all the elements in json array for (int i = 0; i < jsonArray.length(); i++) { //getting json object from the json array JSONObject obj = jsonArray.getJSONObject(i); //getting the name from the json object and putting it inside string array heroes[i] = obj.getString("name"); } //the array adapter to load data into list ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes); //attaching adapter to listview listView.setAdapter(arrayAdapter); } |
- Now we will call this method inside onPostExecute() method of AsyncTask.
1 2 3 4 5 6 7 | try { loadIntoListView(s); } catch (JSONException e) { e.printStackTrace(); } |
The complete Code
- Now here is the complete code of MainActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | public class MainActivity extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); getJSON("http://192.168.101.1/Android/getdata.php"); } private void getJSON(final String urlWebService) { class GetJSON extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); try { loadIntoListView(s); } catch (JSONException e) { e.printStackTrace(); } } @Override protected String doInBackground(Void... voids) { try { URL url = new URL(urlWebService); HttpURLConnection con = (HttpURLConnection) url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String json; while ((json = bufferedReader.readLine()) != null) { sb.append(json + "\n"); } return sb.toString().trim(); } catch (Exception e) { return null; } } } GetJSON getJSON = new GetJSON(); getJSON.execute(); } private void loadIntoListView(String json) throws JSONException { JSONArray jsonArray = new JSONArray(json); String[] heroes = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject obj = jsonArray.getJSONObject(i); heroes[i] = obj.getString("name"); } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes); listView.setAdapter(arrayAdapter); } } |
- Now you can run the application.

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

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
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.
How can parse from the different queries values to android studio volley
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 🙁
Thank you very much!!!
ALHAMDULILLAH it is WORKING. apparently spaces destroy the php file in my case :/ but THANK YOU 🙂
Your Welcome 🙂
Exception is :
java lang NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
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
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?????
Please make you question clear .. I didn’t get you
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
How can i use you code to connect with Recycleview instead of listview
can you show me some example if any and which code should i change
Many Thanks!! It works now! Now I am going to try to make update and delete data.
when i start my apllication .
Unfortunately Listview has stopped
(ListView is my apllication name )
this what an error im facing plz help me out
Check the logcat for exact error
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′.
stay tuned and you will get a tutorial for doing this as well 🙂
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.
Ok I will try to post a tutorial for this soon 🙂
Great tutorial. Thanks!
But if possible please post the updated tutorial as well for SDK version 23 and above.
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.
How to pass detail data into another activity when i click on any Listview record.
Thanks in Advance
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 🙂
Hi Belal, what if I wanted to show the results in a TextView, instead of a ListView?
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
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?
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
I’m so glad that I’ve found this tutorial. It solved my problem in life. 🙂 I mean with my android project.
Nice tutorial, and how to implement progressbar ?
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"
Your JSON is invalid.. Check the JSON you are getting from the URL is correct or not.
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
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
change first php tag <?php
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)
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)
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
Thanks. You made my day.
LOve u buddy u saved my day 🙂 <3
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 🙂
Dear Belal
How do you pass parameters to the URL? For example, if I have to pass user_id to the table and retrieve some data. Thanks.
Hlo sir if got.. NullpointerException in int java. Lang. String. Lengh() on null object reference
very helpful keep it up.
thank you!
Awesome blog. Your way of explanation is too good make this so easy to understand 🙂
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)
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)
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
Check this course to learn everything about rest api, mysql and android
https://www.youtube.com/playlist?list=PLk7v1Z2rk4hhGfJw-IQCm6kjywmuJX4Rh
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
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…
Its amazing solution. really helped me so much!
excellent example…
do u have example like load json image and store in sqlite database..?
What Gradle JDK should i use?