Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of Writing Java Code to Initiate Actions

Writing Java Code to Initiate Actions

The controls defined in the activity layout file need to be loaded in order to display them on the screen. In addition to loading the controls, we want to access the web service and pass to it the user's entry for the city name (and country, if specified). To fetch the JSON data from the web service and display it in the desired format, enter the Java code shown in Listing 2 in the Java activity file AccessWebServiceActivity.java.

Listing 2—Code for Java activity file AccessWebServiceActivity.java.

package com.pearsonarticles.accesswebserviceapp;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.os.AsyncTask;
import org.json.JSONObject;
import org.apache.http.StatusLine;
import org.json.JSONArray;
import java.text.NumberFormat;

public class AccessWebServiceActivity extends Activity {
    String city="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button submitButton = (Button)this.findViewById(R.id.submit_btn);

        submitButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                String country="";
                EditText cityName = (EditText) findViewById(R.id.city_name);
                city=cityName.getText().toString();
                EditText countryName = (EditText) findViewById(R.id.country_name);
                country=countryName.getText().toString();
                String url="http://api.openweathermap.org/data/2.5/weather?q="+city+","+country;
                new ReadJSONFeed().execute(url);
            }
        });
    }
    private class ReadJSONFeed extends AsyncTask<String, String, String> {
        protected void onPreExecute() {}
        @Override
        protected String doInBackground(String... urls) {
            HttpClient httpclient = new DefaultHttpClient();
            StringBuilder builder = new StringBuilder();
            HttpPost httppost = new HttpPost(urls[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return builder.toString();
        }
        protected void onPostExecute(String result) {
            String weatherInfo="Weather Report of "+city +" is: \n";
            try{
                JSONObject jsonObject = new JSONObject(result);
                JSONObject jscoordObject = new JSONObject(jsonObject.getString("coord"));
                weatherInfo+="Longitude: "+jscoordObject.getString("lon")+"\n";
                weatherInfo+="Latitude: "+jscoordObject.getString("lat")+"\n";
                JSONArray jsweatherObject = new JSONArray(jsonObject.getString("weather"));
                    JSONObject jweatherObject = jsweatherObject.getJSONObject(0);
                        weatherInfo+="Clouds: "+jweatherObject.getString("description")+"\n";
                JSONObject jsmainObject = new JSONObject(jsonObject.getString("main"));
                weatherInfo+="Humidity: "+jsmainObject.getString("humidity")+"% \n";
                weatherInfo+="Atmospheric Pressure: "+jsmainObject.getString("pressure")+"hPa \n";
                float temp=Float.parseFloat(jsmainObject.getString("temp"));
                temp = temp - (float) 273.15;
                NumberFormat df = NumberFormat.getNumberInstance();
                df.setMaximumFractionDigits(2);
                weatherInfo+="Temperature: "+ String.valueOf(df.format(temp)) +" C\n";
                JSONObject jswindObject = new JSONObject(jsonObject.getString("wind"));
                weatherInfo+="Wind Speed: "+jswindObject.getString("speed")+"mps \n";
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            TextView resp = (TextView) findViewById(R.id.response);
            if(weatherInfo.trim().length() >0 )
                resp.setText(weatherInfo);
            else
                resp.setText("Sorry no match found");
        }
    }
}

The Java activity file in Listing 2 performs the following tasks to access data from the web service:

  1. Using HTTP, connect to the server.
  2. Because the HTTP POST method is used for sending requests to the server, the HttpPost class is used to specify the URL of the server. The city and country names entered in the two EditText controls are accessed and appended to the URL.
  3. The HttpClient class is used to connect to the server.
  4. The HttpResponse class is used to get the connection status from the server. If the status code is 200, it means that the connection is successfully established with the server.
  5. On establishing connection with the server, the BufferedReader and InputStreamReader classes are used to fetch the information returned by the web service. Remember that the information returned by the service is in JSON format.
  6. From the received JSON format, the latitude, longitude, cloud description, humidity, temperature, and so on are accessed and displayed via the TextView control.

In simple terms, the fetched content is received as a JSONArray. The latitude, longitude, cloud description, humidity, atmospheric pressure, temperature, and wind speed values are accessed from the JSONArray and displayed through the TextView control.

To access the web service uploaded on a server, we need to add Internet permission to the Android project. Nest the following statement in the <manifest> element in the AndroidManifest.xml file:

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

Our Android application is finally ready! When the application runs, a screen appears, prompting the user to enter the city and (optionally) country name whose weather information is required, and click the Submit button, after which our application uses the Internet to access the web service and returns the requested data to the user's screen.

Summary

You've learned how you can access publicly available web services and enhance features in your Android application. The only thing you need to understand is the format in which the JSON data is returned by the web service. As you construct your applications, analyze the JSON structure so you can use the supplied attributes correctly to access and return the desired information.

For more interesting programs, check out my book Android Programming Unleashed. The book uses a step-by-step approach to explore the features provided by this amazing smartphone platform.

  • + Share This
  • 🔖 Save To Your Account