Blog Archive

Android spinner tutorial using JSON data from MySQL and Java Sevlet - Part 2

Click here for previous Chapter
In the previous chapter we have created the Java WEB Service that sends back JSON data of countries from MySQL database. Here we are going to develop our Android application that will parse the JSON data and display a Spinner. Also we are going to look into setting a default value for the spinner and after selecting a specific country display additional information about it.

Android spinner example using JSON data from MySQL and Java Servlet
Android spinner example using JSON data from MySQL and Java Servlet
Android spinner example using JSON data from MySQL and Java Servlet

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">
        <activity android:name=".AndroidSpinnerJSONDataActivity"
            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 Android Activity file AndroidSpinnerJSONDataActivity.java

package com.as400samplecode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidSpinnerJSONDataActivity extends Activity {

    private ArrayList<Country> countryList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String url = "http://10.0.2.2:8080/CountryWebService" + "/CountryServlet";
        grabURL(url); 

    }

    public void grabURL(String url) {
        Log.v("Android Spinner JSON Data Activity", url);
        new GrabURL().execute(url);
    }

    private void displayCountries(String response){

        JSONObject responseObj = null; 
        int dftIndex = 0;

        try {

            Gson gson = new Gson();
            responseObj = new JSONObject(response); 
            JSONArray countryListObj = responseObj.getJSONArray("countryList");

            countryList = new ArrayList<Country>(); 
            String[] country_array = new String[countryListObj.length()]; 

            for (int i=0; i<countryListObj.length(); i++){
               
                //add to country names array
                country_array[i] = countryListObj.getJSONObject(i).getString("name");

                //get the country information JSON object
                String countryInfo = countryListObj.getJSONObject(i).toString();
                //create java object from the JSON object
                Country country = gson.fromJson(countryInfo, Country.class);
                //add to country array list
                countryList.add(country);
               
                //setting the default to USA
                if(countryListObj.getJSONObject(i).getString("code").equalsIgnoreCase("USA")){
                    dftIndex = i;
                    displayCountryInformation(country);
                }
               
            }

            Spinner sp = (Spinner) findViewById(R.id.countries);
            ArrayAdapter<String> adapter = 
                new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, country_array);      
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sp.setAdapter(adapter);
            OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(this);
            sp.setOnItemSelectedListener(spinnerListener);
            sp.setSelection(dftIndex);


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

    }

    public class myOnItemSelectedListener implements OnItemSelectedListener {

        Context mContext;

        public myOnItemSelectedListener(Context context){
            this.mContext = context;
        }

        public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {

            Country country = countryList.get(pos);
            displayCountryInformation(country);

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            //nothing here
        }
    }   

    private void displayCountryInformation(Country country){

        DecimalFormat df2 = new DecimalFormat("0.00##");

        //get references to your views
        TextView code = (TextView) findViewById(R.id.code);
        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);

        //set values from your country java object
        code.setText(country.getCode());
        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()));

    }

    private class GrabURL extends AsyncTask<String, Void, String> {
        private static final int REGISTRATION_TIMEOUT = 3 * 1000;
        private static final int WAIT_TIMEOUT = 30 * 1000;
        private final HttpClient httpclient = new DefaultHttpClient();
        final HttpParams params = httpclient.getParams();
        HttpResponse response;
        private String content =  null;
        private boolean error = false;
        private ProgressDialog dialog = new ProgressDialog(AndroidSpinnerJSONDataActivity.this);

        protected void onPreExecute() {
            dialog.setMessage("Getting your data... Please wait...");
            dialog.show();
        }

        protected String doInBackground(String... urls) {

            String URL = null;

            try {

                URL = urls[0];
                HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
                ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

                HttpPost httpPost = new HttpPost(URL);

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("fakeInput","not in USE for this demo"));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

                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 );
                content = e.getMessage();
                error = true;
                cancel(true);
            } catch (IOException e) {
                Log.w("HTTP3:",e );
                content = e.getMessage();
                error = true;
                cancel(true);
            }catch (Exception e) {
                Log.w("HTTP4:",e );
                content = e.getMessage();
                error = true;
                cancel(true);
            }

            return content;
        }

        protected void onCancelled() {
            dialog.dismiss();
            Toast toast = Toast.makeText(AndroidSpinnerJSONDataActivity.this, "Error connecting to Server", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            toast.show();

        }

        protected void onPostExecute(String content) {
            dialog.dismiss();
            Toast toast;
            if (error) {
                toast = Toast.makeText(AndroidSpinnerJSONDataActivity.this, content, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400);
                toast.show();
            } else {
                displayCountries(content);
            }
        }

    }
}

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="Select a Country: "
                android:layout_height="wrap_content" android:layout_width="wrap_content"
                android:textStyle="bold" />
                <Spinner android:prompt="@string/country_prompt"
                android:layout_height="wrap_content" android:id="@+id/countries"
                android:layout_width="match_parent" android:layout_below="@id/countryText" />
            </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="Code:" android:textAppearance="?android:attr/textAppearanceMedium"
                        android:id="@+id/textView1" android:layout_width="wrap_content"
                        android:layout_gravity="right" />
                    <TextView android:text="" android:id="@+id/code"
                        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>

7 comments :

  1. thanks friend !!!! where is the source codes this project ?

    ReplyDelete
  2. please could you send to me the older of the code

    sara.alhrbi@gmail.com

    Thaaaanks in advance

    ReplyDelete
  3. Replies
    1. Check previous chapter, link is on the top of this page

      Delete
  4. can uu pls send me this source code to sanjaikumar3@gmail.com i need it badly thank youu....

    ReplyDelete