Blog Archive

Android JSON parsing Tutorial using Java Servlet and MySQL database - Part 2

Click here for previous Chapter
In the previous chapter we have created the Java WEB Service that will talk to our Android application and respond back with JSON. Here we are going to develop our Android application that send HTTP request to the WEB Service, parse and display the JSON response on the screen.

Android JSON Web Service Tutorial using Java Servlet and MySQL database
Android JSON Web Service Tutorial using Java Servlet and MySQL database
Android JSON Web Service Tutorial using Java Servlet and MySQL database
Android JSON Web Service Tutorial using Java Servlet and MySQL database

Source for manifest file AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light"
        android:screenOrientation="sensorLandscape">
        <service android:name=".JSONRequest" />
        <activity android:name=".AndroidJSONTutorialActivity"
            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>

Source for IntentService to process any Web Request JSONRequest.java

package com.as400samplecode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.as400samplecode.AndroidJSONTutorialActivity.MyRequestReceiver;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class JSONRequest extends IntentService{

    private String inMessage;
   
    public static final String IN_MSG = "requestType";
    public static final String OUT_MSG = "outputMessage";

    public JSONRequest() {
        super("JSONRequest");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        //Get Intent extras that were passed
        inMessage = intent.getStringExtra(IN_MSG);
        if(inMessage.trim().equalsIgnoreCase("getCountryInfo")){
            String countryCode = intent.getStringExtra("countryCode");
            getCountryInfo(countryCode);
        }
        else if(inMessage.trim().equalsIgnoreCase("getSomethingElse")){
            //you can choose to implement another transaction here
        }

    }

    private void getCountryInfo(String countryCode) {

        //prepare to make Http request 
        String url = "http://10.0.2.2:8080/AndroidJSONWebService" + "/CountryServlet";
       
        //add name value pair for the country code
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("countryCode",countryCode));
        String response = sendHttpRequest(url,nameValuePairs);

        //broadcast message that we have received the reponse 
        //from the WEB Service
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(MyRequestReceiver.PROCESS_RESPONSE);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        broadcastIntent.putExtra(IN_MSG, inMessage);
        broadcastIntent.putExtra(OUT_MSG, response);
        sendBroadcast(broadcastIntent);
    }

    private String sendHttpRequest(String url, List<NameValuePair> nameValuePairs) {

        int REGISTRATION_TIMEOUT = 15 * 1000;
        int WAIT_TIMEOUT = 60 * 1000;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();
        HttpResponse response;
        String content =  "";
       
        try {

            //http request parameters
            HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
            ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

            //http POST
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

            //send the request and receive the repponse
            response = httpclient.execute(httpPost);

            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
            }

            else{
                //Closes the connection.
                Log.w("HTTP1:",statusLine.getReasonPhrase());
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }

        } catch (ClientProtocolException e) {
            Log.w("HTTP2:",e );
        } catch (IOException e) {
            Log.w("HTTP3:",e );
        }catch (Exception e) {
            Log.w("HTTP4:",e );
        }

        //send back the JSON response String
        return content;

    }

   
}

Source for Android Activity file AndroidJSONTutorialActivity.java

package com.as400samplecode;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.as400samplecode.util.Country;
import com.google.gson.Gson;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidJSONTutorialActivity extends Activity {
   
    private MyRequestReceiver receiver;
    private Button getInfo;
    private EditText countryCode;
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //Register your receiver so that the Activity can be notified
        //when the JSON response came back
        IntentFilter filter = new IntentFilter(MyRequestReceiver.PROCESS_RESPONSE);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new MyRequestReceiver();
        registerReceiver(receiver, filter);

        countryCode = (EditText) findViewById(R.id.countryCode);
       
        //button that will trigger the http request
        getInfo = (Button) findViewById(R.id.getInfo);
        getInfo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                getCountryInformation();
                //hide the soft keyboard
                InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(countryCode.getWindowToken(), 0);
               
            }
        });

       
    }
   
    @Override
    protected void onDestroy() {
        Log.v("AndroidJSONTutorialActivity", "onDestory");
       
        unregisterReceiver(receiver);
        super.onDestroy();
    }
   
    private void getCountryInformation() {

        boolean internet =  isNetworkAvailable(this);
        if(internet){
            String code = countryCode.getText().toString();
            //if no country code was entered
            if(code.trim().isEmpty()){
                Toast toast = Toast.makeText(this, "Please enter a Country Code first!", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 105, 50);
                toast.show();
            }
            else {
                //pass the request to your service so that it can 
                //run outside the scope of the main UI thread
                Intent msgIntent = new Intent(this, JSONRequest.class);
                msgIntent.putExtra(JSONRequest.IN_MSG, "getCountryInfo");
                msgIntent.putExtra("countryCode", code.trim());
                startService(msgIntent);
            }
        }
    }
   
    //parse and display JSON response
    private void displayCountryInformation(String response){

        JSONObject responseObj = null; 
        DecimalFormat df2 = new DecimalFormat("0.00##");
       
        //get references to your views
        TextView name = (TextView) findViewById(R.id.name);
        TextView continent = (TextView) findViewById(R.id.continent);
        TextView region = (TextView) findViewById(R.id.region);
        TextView lifeExpectancy = (TextView) findViewById(R.id.lifeExpectancy);
        TextView gnp = (TextView) findViewById(R.id.gnp);
        TextView surfaceArea = (TextView) findViewById(R.id.surfaceArea);
        TextView population = (TextView) findViewById(R.id.population);
        TextView errorMessage = (TextView) findViewById(R.id.errorMessage);
       
        try {
            //create JSON object from JSON string
            responseObj = new JSONObject(response); 
            //get the success property
            boolean success = responseObj.getBoolean("success");
            if(success){
               
                Gson gson = new Gson();
                //get the country information property
                String countryInfo = responseObj.getString("countryInfo");
                //create java object from the JSON object
                Country country = gson.fromJson(countryInfo, Country.class);
               
                //set values from your country java object
                name.setText(country.getName());
                continent.setText(country.getContinent());
                region.setText(country.getRegion());
                lifeExpectancy.setText(df2.format(country.getLifeExpectancy()));
                gnp.setText(df2.format(country.getGnp()));
                surfaceArea.setText(df2.format(country.getSurfaceArea()));
                population.setText(String.valueOf(country.getPopulation()));
                errorMessage.setText(" ");   
            }
            else {
               
                name.setText(" ");
                continent.setText(" ");
                region.setText(" ");
                lifeExpectancy.setText(" ");
                gnp.setText(" ");
                surfaceArea.setText(" ");
                population.setText(" ");
                errorMessage.setText("Invalid Country Code!");   
               
            }
           

        } catch (JSONException e) {
            e.printStackTrace();
        }
       
    }

    //check if you have internet connection
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    Log.w("INTERNET:",String.valueOf(i));
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.w("INTERNET:", "connected!");
                        return true;
                    }
                }
            }
        }
        return false;
    }

   
    //broadcast receiver to receive messages sent from the JSON IntentService
    public class MyRequestReceiver extends BroadcastReceiver{

        public static final String PROCESS_RESPONSE = "com.as400samplecode.intent.action.PROCESS_RESPONSE";

        @Override
        public void onReceive(Context context, Intent intent) {

            String response = null;
            String responseType = intent.getStringExtra(JSONRequest.IN_MSG);
           
            if(responseType.trim().equalsIgnoreCase("getCountryInfo")){
                response = intent.getStringExtra(JSONRequest.OUT_MSG);
                displayCountryInformation(response);
            }
            else if(responseType.trim().equalsIgnoreCase("getSomethingElse")){
                //you can choose to implement another transaction here
            }

        }
    }
}

Source for Android screen layout main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/topLayout"
        android:layout_width="match_parent" android:layout_height="220dp"
        android:orientation="horizontal">
        <RelativeLayout android:layout_height="match_parent"
            android:id="@+id/topLeftLayout" android:layout_width="300dp"
            android:paddingRight="20dp">
            <TextView android:textAppearance="?android:attr/textAppearanceMedium"
                android:id="@+id/countryText" android:text="Country Code:"
                android:layout_height="wrap_content" android:layout_width="wrap_content"
                android:textStyle="bold" />
            <EditText android:id="@+id/countryCode"
                android:layout_height="wrap_content" android:layout_below="@id/countryText"
                android:maxLength="3" android:layout_width="75dp">
                <requestFocus />
            </EditText>
            <Button android:text="Get Information" android:layout_height="wrap_content"
                android:id="@+id/getInfo" android:layout_below="@id/countryText"
                android:layout_toRightOf="@id/countryCode" android:layout_width="wrap_content" />
            <TextView android:text=" " android:id="@+id/errorMessage"
                android:layout_height="wrap_content" android:layout_below="@id/countryCode"
                android:layout_width="match_parent" android:paddingLeft="80dp"
                android:textStyle="bold|italic" />
        </RelativeLayout>
        <LinearLayout android:layout_height="match_parent"
            android:id="@+id/rightTopLayout" android:orientation="vertical"
            android:layout_width="match_parent">
            <TableLayout android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/tableLayout1"
                android:stretchColumns="1,2">
                <TableRow android:layout_width="wrap_content"
                    android:layout_height="wrap_content" android:id="@+id/tableRow1">
                    <TextView android:layout_height="wrap_content"
                        android:text="Name:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text="" android:id="@+id/name"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:textStyle="bold" />
                </TableRow>
                <TableRow android:layout_width="wrap_content"
                    android:layout_height="wrap_content" android:id="@+id/tableRow2">
                    <TextView android:layout_height="wrap_content"
                        android:text="Continent:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text="" android:id="@+id/continent"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
                <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView android:layout_height="wrap_content"
                        android:text="Region:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text="" android:id="@+id/region"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
                <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView android:layout_height="wrap_content"
                        android:text="Life Expectancy:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text=" " android:id="@+id/lifeExpectancy"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
                <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView android:layout_height="wrap_content"
                        android:text="GNP:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text="" android:id="@+id/gnp"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
                <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView android:layout_height="wrap_content"
                        android:text="Surface Area:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text=" " android:id="@+id/surfaceArea"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:paddingLeft="10dp" android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
                <TableRow android:id="@+id/tableRow7" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView android:layout_height="wrap_content"
                        android:text="Population:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text=" " android:id="@+id/population"
                        android:layout_height="wrap_content" android:paddingLeft="10dp"
                        android:textAppearance="?android:attr/textAppearanceMedium" />
                </TableRow>
            </TableLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Recommended Reading