Tuesday, June 2, 2015

Android - JSON Parser

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four differnet classes to manipulate JSON data. These classes areJSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
{
"sys":
   {
      "country":"GB",
      "sunrise":1381107633,
      "sunset":1381149604
   },
"weather":[
   {
      "id":711,
      "main":"Smoke",
      "description":"smoke",
      "icon":"50n"
   }
],
"main":
   {
      "temp":304.15,
      "pressure":1009,
   }
}

JSON - Elements

An JSON file consist of many components. Here is the table defining the compoents of an JSON file and their description −
Sr.NoComponent & description
1Array([)
In a JSON file , square bracket ([) represents a JSON array
2Objects({)
In a JSON file, curly bracket ({) represents a JSON object
3Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4Value
Each key has a value that could be string , integer or double e.t.c

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is −
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. An JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a seperate function for parsing each of the component of JSON file. Its syntax is given below −
JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
   
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.
Apart from the these methods, there are other methods provided by this class for better parsing JSON files. These methods are listed below −
Sr.NoMethod & description
1get(String name)
This method just Returns the value but in the form of Object type
2getBoolean(String name)
This method returns the boolean value specified by the key
3getDouble(String name)
This method returns the double value specified by the key
4getInt(String name)
This method returns the integer value specified by the key
5getLong(String name)
This method returns the long value specified by the key
6length()
This method returns the number of name/value mappings in this object..
7names()
This method returns an array containing the string names in this object.

Example

Here is an example demonstrating the use of JSONObject class. It creates a basic Weather application that allows you to parse JSON from google weather api and show the result.
To experiment with this example, you can run this on an actual device or in an emulator.
StepsDescription
1You will use Android studio to create an Android application. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Create a new java file under src/HandleJSON.java to fetch and parse XML data
6Modify AndroidManifest.xml to add necessary internet permission
7Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modifed main activity file src/MainActivity.java.
package com.example.arunkumar.weatherapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
com.example.arunkumar.weatherapplication

public class MainActivity extends ActionBarActivity {
   EditText ed1,ed2,ed3,ed4,ed5;
   private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
   private String url2 = "&mode=xml";
   private HandleXML obj;
   Button b1;
   
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      b1=(Button)findViewById(R.id.button);
      
      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      ed3=(EditText)findViewById(R.id.editText3);
      ed4=(EditText)findViewById(R.id.editText4);
      ed5=(EditText)findViewById(R.id.editText5);
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String url = ed1.getText().toString();
            String finalUrl = url1 + url + url2;
            
            ed2.setText(finalUrl);
            obj = new HandleXML(finalUrl);
            obj.fetchXML();
            
            while(obj.parsingComplete);
            ed2.setText(obj.getCountry());
            ed3.setText(obj.getTemperature());
            ed4.setText(obj.getHumidity());
            ed5.setText(obj.getPressure());
         }
      });
   }
   
   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.menu_main, menu);
       return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       
       int id = item.getItemId();
       
       //noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
          return true;
       }
       return super.onOptionsItemSelected(item);
    }
}
Following is the content of src/HandleXML.java.
package com.example.arunkumar.weatherapplication;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by arunkumar on 24/05/2015.
 */
public class HandleXML {
   private String country = "county";
   private String temperature = "temperature";
   private String humidity = "humidity";
   private String pressure = "pressure";
   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject;
   
   public volatile boolean parsingComplete = true;
   public HandleXML(String url){
      this.urlString = url;
   }
   
   public String getCountry(){
      return country;
   }
   
   public String getTemperature(){
      return temperature;
   }
   
   public String getHumidity(){
      return humidity;
   }
   
   public String getPressure(){
      return pressure;
   }
   
   public void parseXMLAndStoreIt(XmlPullParser myParser) {
      int event;
      String text=null;
      
      try {
         event = myParser.getEventType();
         
         while (event != XmlPullParser.END_DOCUMENT) {
            String name=myParser.getName();
            
            switch (event){
               case XmlPullParser.START_TAG:
               break;
               
               case XmlPullParser.TEXT:
               text = myParser.getText();
               break;
               
               case XmlPullParser.END_TAG:
               if(name.equals("country")){
                  country = text;
               }
               
               else if(name.equals("humidity")){
                  humidity = myParser.getAttributeValue(null,"value");
               }
               
               else if(name.equals("pressure")){
                  pressure = myParser.getAttributeValue(null,"value");
               }
               
               else if(name.equals("temperature")){
                  temperature = myParser.getAttributeValue(null,"value");
               }
               
               else{
               }
               
               break;
            }
            event = myParser.next();
         }
         
         parsingComplete = false;
      }
      
      catch (Exception e) {
         e.printStackTrace();
      }
   }
   
   public void fetchXML(){
      Thread thread = new Thread(new Runnable(){
         @Override
         public void run() {
            try {
               URL url = new URL(urlString);
               HttpURLConnection conn = (HttpURLConnection)url.openConnection();
               
               conn.setReadTimeout(10000 /* milliseconds */);
               conn.setConnectTimeout(15000 /* milliseconds */);
               conn.setRequestMethod("GET");
               conn.setDoInput(true);
               conn.connect();
               
               InputStream stream = conn.getInputStream();
               xmlFactoryObject = XmlPullParserFactory.newInstance();
               XmlPullParser myparser = xmlFactoryObject.newPullParser();
               
               myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
               myparser.setInput(stream, null);
               
               parseXMLAndStoreIt(myparser);
               stream.close();
            }
            catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
      thread.start();
   }
}
Following is the modified content of the xml res/layout/activity_main.xml.
<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:text="XML Fetch"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Location"
      android:layout_below="@+id/textView2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_marginTop="61dp"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Weather "
      android:id="@+id/button"
      android:layout_below="@+id/editText"
      android:layout_centerHorizontal="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignRight="@+id/editText"
      android:layout_alignEnd="@+id/editText"
      android:text="Currency" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText3"
      android:layout_below="@+id/editText2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:text="Temp" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText4"
      android:layout_below="@+id/editText3"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignRight="@+id/editText3"
      android:layout_alignEnd="@+id/editText3"
      android:text="Humidity" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText5"
      android:layout_below="@+id/editText4"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:text="Pressure" />
      
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.arunkumar.weatherapplication" >
   <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>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run .Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application.
Now when you press the weather button, the application will contact the Google Weather API and will request for your necessary JSON location file and will parse it. In case of oddanchatram the file would be returned −
Note that this temperature is in kelvin, so if you want to convert it into more understandable format , you have to convert it into Celcius.

No comments:

Post a Comment