Wednesday, 17 December 2014

Json Parsing

Download jar file must- "commons-httpclient-3.0-rc4.jar and httpmime-4.1.2.jar",

MainActivity
package com.example.json_parsing_demo;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private Weather_services services;
private Thread thread;
private ArrayList<Uttils> arrayList = new ArrayList<Uttils>();
private TextView temp, clouds, presure, Humidity, temp_mx, temp_min;
private EditText city_box;
private String city;
private Button chk_wthr_btn;
private Handler handler;
ProgressDialog  dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getid();
services = new Weather_services();
chk_wthr_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
city = city_box.getText().toString();
if (!city.equalsIgnoreCase("")) {
dialog = ProgressDialog.show(MainActivity.this, "", "Fataching Data...");
// thread ***
thread = new Thread() {
public void run() {
arrayList = services.Call_service(null, "http://api.openweathermap.org/data/2.5/weather?q=" + city);
handler.sendEmptyMessage(0);
};
};
thread.start();
}else {
Toast.makeText(MainActivity.this, "Enter City", 3000).show();
}
}
});



}

private void getid() {
city_box = (EditText) findViewById(R.id.city_edt_box);
chk_wthr_btn = (Button) findViewById(R.id.chk_wthr_btn);
temp = (TextView) findViewById(R.id.tem_txt);
clouds = (TextView) findViewById(R.id.cloud_txt);
presure = (TextView) findViewById(R.id.pressure_txt);
Humidity = (TextView) findViewById(R.id.humidity_txt);
temp_mx = (TextView) findViewById(R.id.temp_max_txt);
temp_min = (TextView) findViewById(R.id.temp_min_txt);
// handler****
handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (dialog!=null) {
dialog.dismiss();
dialog=null;
}
System.out.println("=====arrray size=="+arrayList.size());
if (arrayList.size()!=0) {
for (int j = 0; j < arrayList.size(); j++) {
temp.setText(arrayList.get(j).TEMP);
clouds.setText(arrayList.get(j).CLOUDS);
presure.setText(arrayList.get(j).PRESSURE);
Humidity.setText(arrayList.get(j).HUMIDITY);
temp_mx.setText(arrayList.get(j).MAX_TEMP);
temp_min.setText(arrayList.get(j).MIN_TEM);
}
}else {
Toast.makeText(MainActivity.this, "No Data Found", 3000).show();
temp.setText("");
clouds.setText("");
presure.setText("");
Humidity.setText("");
temp_mx.setText("");
temp_min.setText("");
}

};
};
}


}
Uttils.java
package com.example.json_parsing_demo;

public class Uttils {
String TEMP;
String CLOUDS;
String WIND_SPPEED;
String WIND_DIRECTNS;
String HUMIDITY; 
String MIN_TEM;
String MAX_TEMP;
String PRESSURE;
public String getMIN_TEM() {
return MIN_TEM;
}
public void setMIN_TEM(String mIN_TEM) {
MIN_TEM = mIN_TEM;
}
public String getMAX_TEMP() {
return MAX_TEMP;
}
public void setMAX_TEMP(String mAX_TEMP) {
MAX_TEMP = mAX_TEMP;
}
public String getPRESSURE() {
return PRESSURE;
}
public void setPRESSURE(String pRESSURE) {
PRESSURE = pRESSURE;
}
public String getTEMP() {
return TEMP;
}
public void setTEMP(String tEMP) {
TEMP = tEMP;
}
public String getCLOUDS() {
return CLOUDS;
}
public void setCLOUDS(String cLOUDS) {
CLOUDS = cLOUDS;
}
public String getWIND_SPPEED() {
return WIND_SPPEED;
}
public void setWIND_SPPEED(String wIND_SPPEED) {
WIND_SPPEED = wIND_SPPEED;
}
public String getWIND_DIRECTNS() {
return WIND_DIRECTNS;
}
public void setWIND_DIRECTNS(String wIND_DIRECTNS) {
WIND_DIRECTNS = wIND_DIRECTNS;
}
public String getHUMIDITY() {
return HUMIDITY;
}
public void setHUMIDITY(String hUMIDITY) {
HUMIDITY = hUMIDITY;
}
}
Weather_services.java
package com.example.json_parsing_demo;

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

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.json.JSONException;
import org.json.JSONObject;

public class Weather_services {
public static String ERROR_massage = "";

public ArrayList<Uttils> Call_service(NameValuePair[] city, String url) {
ArrayList<Uttils> Call_serviceArr = new ArrayList<Uttils>();
String requst = url;
String responce = "";
GetMethod getMethod = new GetMethod(requst);
HttpClient client = new HttpClient();
client.setConnectionTimeout(5000);
try {
client.executeMethod(getMethod);
responce = getMethod.getResponseBodyAsString();

} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Call_serviceArr = PARSING(responce);
System.out.println("=======error==" + ERROR_massage);
return Call_serviceArr;

}

public ArrayList<Uttils> PARSING(String string) {
ArrayList<Uttils> PARSER_serviceArr = new ArrayList<Uttils>();
Uttils uttils = new Uttils();

try {
JSONObject jsonObject = new JSONObject(string);
ERROR_massage = jsonObject.getString("cod");
if (!ERROR_massage.equalsIgnoreCase("404")) {
JSONObject jsonObject2 = jsonObject.getJSONObject("main");
JSONObject jsonObject3 = jsonObject.getJSONObject("clouds");
uttils.setTEMP(jsonObject2.getString("temp"));
uttils.setPRESSURE(jsonObject2.getString("pressure"));
uttils.setHUMIDITY(jsonObject2.getString("humidity"));
uttils.setMIN_TEM(jsonObject2.getString("temp_min"));
uttils.setMAX_TEMP(jsonObject2.getString("temp_max"));
uttils.setWIND_SPPEED(jsonObject2.getString("temp_max"));
uttils.setCLOUDS(jsonObject3.getString("all"));
PARSER_serviceArr.add(uttils);
}

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

}
}
XMl Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="100" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_weight="25" >

        <EditText
            android:id="@+id/city_edt_box"
            android:hint="Enter City..."
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:singleLine="true" />

        <Button
            android:id="@+id/chk_wthr_btn"
            android:layout_width="fill_parent"
            android:text="Cheak Weather"
            android:layout_height="48dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="75"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Temprature:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/tem_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Clouds:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/cloud_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Humidity:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/humidity_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Temp Min:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/temp_min_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="Temp Max:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/temp_max_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:text="pressure:-"
                android:textSize="20sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/pressure_txt"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:textSize="20sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>






XML Parsing

Main Activity.Java

public class Main Activity extends Activity {
private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
private String url2 = "&mode=xml";
private TextView country, temperature, humidity, pressure, city;
private EditText location;
private HandleXML obj;
Button weather_btn;

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = (EditText) findViewById(R.id.editText1);
country = (TextView) findViewById(R.id.cunty_txt);
temperature = (TextView) findViewById(R.id.temprature_txt);
humidity = (TextView) findViewById(R.id.humidyty_txt);
pressure = (TextView) findViewById(R.id.prature_txt);
weather_btn = (Button) findViewById(R.id.button1);
city = (TextView) findViewById(R.id.City_txt);
weather_btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {
String url = location.getText().toString();
if (!url.equalsIgnoreCase("")) {
String finalUrl = url1 + url + url2;
country.setText(finalUrl);
obj = new HandleXML(finalUrl);
obj.fetchXML();
while (obj.parsingComplete)
;
country.setText(obj.getCountry());
temperature.setText(obj.getTemperature());
humidity.setText(obj.getHumidity());
pressure.setText(obj.getPressure());
city.setText(obj.getCity());
} else {
Toast.makeText(MainActivity.this, "Faild Conections", 3000).show();
country.setText("");
temperature.setText("");
humidity.setText("");
pressure.setText("");
city.setText("");
}
}
});
}


}

HandleXML_Services

package com.example.xml_parsing;

import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import org.xmlpull.v1.XmlPullParserFactory;

public class HandleXML_Services {

   private String country = "county";
   private String temperature = "temperature";
   private String humidity = "humidity";
   private String pressure = "pressure";
   private String City = "City";
   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject;
   public volatile boolean parsingComplete = true;
   public HandleXML_Services(String url){
      this.urlString = url;
   }
   public String getCountry(){
      return country;
   }
   public String getTemperature(){
      return temperature;
   }
   public String getHumidity(){
      return humidity;
   }
   public String getCity(){
     return City;
  }
   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:
              if(name.equals("city")){
              City = myParser.getAttributeValue(null,"name");
                    }
               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(); 



   }



}

xml layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="100" >

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="25"
        android:orientation="vertical" >

        <EditText

            android:id="@+id/editText1"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:singleLine="true"
            android:hint="Enter City Name"
            android:textSize="20sp" />

        <Button

            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="Get Weather" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="75"
        android:orientation="vertical"
        android:weightSum="100" >

        <LinearLayout

            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:orientation="horizontal"
            android:weightSum="100" >

            <TextView

                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:text="Country:-"
                android:textSize="20sp" />

            <TextView

                android:id="@+id/cunty_txt"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:textSize="20sp" />
        </LinearLayout>

        <View

            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />

        <LinearLayout

            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:orientation="horizontal"
            android:weightSum="100" >

            <TextView

                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:text="City:-"
                android:textSize="20sp" />

            <TextView

                android:id="@+id/City_txt"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:textSize="20sp" />
        </LinearLayout>

        <View

            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />

        <LinearLayout

            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:orientation="horizontal"
            android:weightSum="100" >

            <TextView

                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:text="Temperature:-"
                android:textSize="20sp" />

            <TextView

                android:id="@+id/temprature_txt"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:textSize="20sp" />
        </LinearLayout>

        <View

            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />

        <LinearLayout

            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:orientation="horizontal"
            android:weightSum="100" >

            <TextView

                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:text="Humidity:-"
                android:textSize="20sp" />

            <TextView

                android:id="@+id/humidyty_txt"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:textSize="20sp" />
        </LinearLayout>

        <View

            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />

        <LinearLayout

            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="20"
            android:orientation="horizontal"
            android:weightSum="100" >

            <TextView

                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:text="Presser:-"
                android:textSize="20sp" />

            <TextView

                android:id="@+id/prature_txt"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="50"
                android:gravity="center"
                android:textSize="20sp" />
        </LinearLayout>

        <View

            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />
    </LinearLayout>


</LinearLayout>

ScreenShots