JSON parsing in android using PHP and MySqli




we are going to learn how to create JSON parsing in android using PHP and mysql. JSON is light weight and a great alternative to xml. In this android application we will learn how to get json response from a server and json response is generated by PHP and mysql.



Android

JSON parsing in android using PHP and MySql
Project Structure

AndroidManifest.xml

In Android Mainfest file we will add the internet permission so that our app can access the internet to fetch the json response from the server.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hackerkernel.getjsonresponse" >
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

In this file we will create layout for your app. We have a Button and a TextView. When every the Button is clicked we will fetch JSON response from the server and display it into the TextView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Get JSON Response"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get JSON"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="JSON"
        android:id="@+id/result"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

JSON parsing in android using PHP and MySql
Your App Layout



MainActivity.java

This fill will perform all the stuff handling event,Fetching data from the server,Displaying Result etc

  1. On line 39 we are setting a onClickListner on the button and whenever the button is clicked we call the getJsonResponse() Class
  2. On line 48 we have created the getJsonResponse() Class which extends AsyncTask Class
  3. On line 49 we have created String variable of serverUrl in this variable we will store the server address from where we will get the json reponse in our case it is http://10rsfreerecharge.site11.com/getJsonResponse.php
  4. On line 51 we will make a ProgressDialog
  5. On line 59 in the onPreExecute()method we will set the serverUrl variable with server address And we will show the ProgressDilaog
  6. On line 66 in the doInBackground() method we will fetch the json response from the serve and return it
  7. On line 100 in the onPostExecute() method we will catch the response return by the doInBackground() method and display it in the TextView And Dismiss the ProgressDialog()
package com.hackerkernel.getjsonresponse;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends Activity {
    //make member variable is Views
    Button mButton;
    TextView mResult;
    String JSON_RESPONSE;
    ProgressDialog mProgressDialog;
    public static final String TAG = MainActivity.class.getSimpleName(); //TAG for log messages

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //get reference of the views
        mButton = (Button) findViewById(R.id.button);
        mResult = (TextView) findViewById(R.id.result);

        //when button is clicked
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //call the getJsonResponse method and fetch the response from the server
                new getJsonResponse().execute();
            }
        });
    }

    public class getJsonResponse extends AsyncTask<Void,Void,String>{
        String serverUrl;

        public getJsonResponse(){
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage("Please Wait");
            mProgressDialog.setTitle("Processing");
            mProgressDialog.setCancelable(false);
        }

        @Override
        protected void onPreExecute() {

            //set the url from we have to fetch the json response
            serverUrl = "http://10rsfreerecharge.site11.com/getJsonResponse.php";
            mProgressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                URL url = new URL(serverUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_RESPONSE = bufferedReader.readLine()) != null){

                    stringBuilder.append(JSON_RESPONSE + "\n");

                }

                inputStream.close();
                bufferedReader.close();
                httpURLConnection.disconnect();

                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                Log.e(TAG,"MalformedURLException: "+e); //print exception message to log
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e); //print exception message to log
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            //set the result which is returned by doInBackground() method to result textView
            mResult.setText(result);
            mProgressDialog.dismiss();
        }
    }

}

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *