JSON Parsing in Android – Fetching From MySQL Database
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"
}
]
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
//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
echojson_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.
<!--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
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.
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).
No comments:
Post a Comment