Cách kiếm tiền đơn giản, hiệu quả nhất

Thứ Năm, 10 tháng 9, 2015

Android - XML Parser Tutorial use of XMLPullParser parse xml on web api|android studio

|0 nhận xét
XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it.

XML-Parsing
we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser

Example:
Here is an example demonstrating the use of XMLPullParser class. It creates a basic Weather application that allows you to parse XML from google weather api and show the result.

Following is the content of the modified main activity file MainActivity.java.
package androiddemo.example.duyhoang.xmlparsedemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private EditText txt1, txt2, txt3, txt4, txt5;
    private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
    private String url2 = "&mode=xml";
    private HandleXml obj;
    Button btnWeather;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnWeather = (Button) findViewById(R.id.btn_weather);

        txt1 = (EditText) findViewById(R.id.txtLocation);
        txt2 = (EditText) findViewById(R.id.txt_curency);
        txt3 = (EditText) findViewById(R.id.txt_temp);
        txt4 = (EditText) findViewById(R.id.txt_humidity);
        txt5 = (EditText) findViewById(R.id.txt_pressure);
        btnWeather.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                String url = txt1.getText().toString();
                String finalUrl = url1 + url + url2;
                txt2.setText(finalUrl);
                obj = new HandleXml(finalUrl);
                obj.fetchXML();

                while (obj.parsingComplete) ;
                txt2.setText(obj.getCountry());
                txt3.setText(obj.getTemperature());
                txt4.setText(obj.getHumidity());
                txt5.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/com.example.xmlparser/HandleXML.java.
package androiddemo.example.duyhoang.xmlparsedemo;

import android.util.Xml;

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

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

/** * Created by DUYHOANG on 9/10/2015. */public class HandleXml {
    private String country = "country";
    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 parseXMLAndStorelt(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 connect = (HttpURLConnection) url.openConnection();
                    connect.setReadTimeout(10000);
                    connect.setConnectTimeout(15000);
                    connect.setRequestMethod("GET");
                    connect.setDoInput(true);
                    connect.connect();

                    InputStream stream = connect.getInputStream();
                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    XmlPullParser myparser = xmlFactoryObject.newPullParser();
                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    myparser.setInput(stream, null);
                    parseXMLAndStorelt(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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity">

    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:text="@string/fetch"        android:textSize="30dp" />

    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/textView1"        android:layout_centerHorizontal="true"        android:gravity="center"        android:text="@string/weather_report"        android:textColor="@color/text_color"        android:textSize="30dp"        android:textStyle="bold" />

    <EditText        android:id="@+id/txtLocation"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/textView2"        android:hint="@string/Location" />

    <Button        android:id="@+id/btn_weather"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/txtLocation"        android:layout_centerHorizontal="true"        android:text="@string/weather" />

    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/btn_weather"        android:orientation="vertical">

        <EditText            android:id="@+id/txt_curency"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/curency"            />

        <EditText            android:id="@+id/txt_temp"            android:text="@string/temp"            android:layout_width="match_parent"            android:layout_height="wrap_content" />

        <EditText            android:id="@+id/txt_humidity"            android:text="@string/humidity"            android:layout_width="match_parent"            android:layout_height="wrap_content" />

        <EditText            android:id="@+id/txt_pressure"            android:text="@string/pressure"            android:layout_width="match_parent"            android:layout_height="wrap_content" />
    </LinearLayout>

</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="androiddemo.example.duyhoang.xmlparsedemo" >
    <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>
Thank's for watching. good luck!!!