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 🙂