How to parse JSON data from server to Android
Tags: android, php, mysql, java
Published: 2021-06-13 19:07:45

  Hi Everyone!!!, My Name is Mathesh a student and part time Mobile and Web App Developer. In this tutorial, I am going to fetch data from server through android app and print the same in android app  

   Getting a data from server and and parsing it into applications is a necessity for dynamic mobile applications.
So we are going to see a basic step on how to get data from database through server and show it to the user who is using mobile app. On this tutorial we are going to use MYSQL as a database, PHP as a server language and Java as a android language.


 The first step of the process is to code the server side files. On this example we are looking at a scenario where we have to show the salary of the specific employee in a company. So we start by getting the value from database and printing the value in JSON format so as to communicate with the mobile application.

```php
<?php
header('Content-Type: application/json');
$servername='localhost';

$username='root';

$password='';

$dbname='employee';

$conn = mysqli_connect($servername,$username,$password,$dbname);

//Checking weather the values is passed in the URL. 
if(isset($_GET['logid']))
{
    $logid = $_GET['logid'];
 
    $sql = "SELECT p_amt FROM package  WHERE c_uname = '$logid'";

    $res = mysqli_query($conn,$sql);

    
    $packages = array();
    
    while($row = mysqli_fetch_array($res))
    {

    $totalamt=$row['p_amt'];
    
    }
    
    array_push($packages,array('logid'=>$logid,
    'totamt'=>$totalamt)
    );
    echo json_encode(array("packages"=>$packages));
  

    
    mysqli_close($conn);
  }

?>
```

So in the above code we are first defining the values needed for connection of database and further connecting to the MYSQL database. We are using GET method to get the login id of the employee through URL and fetching the related salary from the database. At the last step we are printing the fetched data from database in JSON format.

With the above step the server side of things is over, now we can concentrate on fetching the data through Android.

Since we are fetching the details in JSON format, we are going to use Volley Library to fetch the data from the database.

```gradle
implementation 'com.android.volley:volley:1.1.0'
```

Next step is to access internet permission since we are using Internet to communicate with the server. In the Android Manifest file fill the below permission to proceed further.

```xml
<uses-permission android:name="android.permission.INTERNET" />
```

Now, let us the design the activity_main.xml with a single text view to display the amount.

```xml
<LinearLayout 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=".MainActivity">
 <TextView
            android:id="@+id/amt"
            android:layout_width="290dp"
            android:layout_height="52dp"
            android:gravity="center"
            android:text="print"
            android:textColor="#000000"
            android:textSize="25sp" />
</LinearLayout>
``` 
Now lets start coding the MainActivity.java file by first declaring the necessary variables.
```java
TextView amt;
private RequestQueue mQueue;
``` 

Now refer the same variables in the oncreate method
```java
amt=(TextView) findViewById(R.id.amt);
mQueue = Volley.newRequestQueue(this);
``` 

Let's now write a function to get JSON data from the String URL. This function should be placed within MainActivity Class.
```java
 public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {

        HttpURLConnection urlConnection = null;

        URL url = new URL(urlString);

        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);

        urlConnection.setDoOutput(true);

        urlConnection.connect();

        BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

        char[] buffer = new char[1024];

        String jsonString = new String();

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line+"\n");
        }
        br.close();

        jsonString = sb.toString();

        System.out.println("JSON: " + jsonString);
        urlConnection.disconnect();

        return new JSONObject(jsonString);
    }
``` 

The above method gets string(URL) as a parameter and return the JSON values it retrieved.

The final step is to use this method, apply the same to get the salary amount and display it.
```java
String Channel="1201MAN02" //This is the Employee Id sent through GET method.
String URL = new StringBuilder().append("https://quasartechsolutions.in/manvaasam/mtotamt.php?logid=").append(channel).toString();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try
                        {
                            JSONArray jsonArray = response.getJSONArray("packages");
                                JSONObject employee = jsonArray.getJSONObject(0);
                                int totalamt = employee.getInt("totamt");
                                totamt.append( "Total Amount Collected By "+channel + "\n\n" );
                                amt.append(" "+String.valueOf(totalamt) + "\n\n");
                        }
                        catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
``` 
  In the above code snippet we are declaring the employee id to be parsed along with the URL and fetching the amount from the data.

Note:- Here I am using my firm QuasarTechSolutions as a URL. It won't work if you are trying with the same URL. Pls change the URL to your desired URL to make the application error free.

#### So that's it, Whoooooo!!! You have learned how to get data from Server through JSON and use it to your android app.

If you have any further doubts, please contact me through:

LinkedIn : [Connect me through LinkedIn](https://www.linkedin.com/in/mathesh-t/)
Email : mathesh@quasartechsolutions.in