Showing posts with label Parse XML in Android App. Show all posts
Showing posts with label Parse XML in Android App. Show all posts

Wednesday, November 16, 2016

Parsing XML response in your Android App @ Mini App / Calling WebServices

Dear All

In the previous post i had uploaded how to generate XML response from Database.
Now in this post i am going to upload an android code by which you can fetch data into a ListView from any file which is generating XML response .
These kind of files are generally termed as web services.
To see please visit a live resource on

http://services.hanselandpetal.com/feeds/flowers.xml

So how you can parse such kind of response in your Android App. Below mentioned code is little bit tricky don't get confused.
I had create
A. Layout
     a. Layout for MainActivity
     b. Layout for a single row
B. Java Code
     a. ConnManager Class to read the data from given url in a string format
     b. A class to hold information in a manner as generated by XML  - Person
     c.  A Parser class to parse data from generated string in step-a into proper format like List
          PersonXMLParser
     d. An Adapter to provide data to ListView PersonAdapter
     e. MainActivity to work as a Controller
C. Output

So i think you understand the project structure lets see the code
A. Layout code
    a.

<ListView    android:id="@android:id/list"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_below="@+id/button"

    android:layout_marginTop="10dp">

</ListView>
<ProgressBar

    android:id="@+id/progressBar1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_centerHorizontal="true"

    android:layout_centerVertical="true" />

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Click for Data"

    android:id="@+id/button"

    android:onClick="loadData"

    android:layout_alignParentTop="true"

    android:layout_centerHorizontal="true" />


b. Single Row
<TextView    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="New Text"

    android:id="@+id/name"

    android:gravity="center_vertical"

    android:layout_alignParentTop="true"

    android:layout_alignParentStart="true" />

<TextView

    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="New Text"

    android:id="@+id/address"

    android:gravity="center_vertical"

    android:layout_alignParentTop="true"

    android:layout_centerHorizontal="true" />


B. Java Code 
  a. ConnManager
package com.example.ravigodara.parsejsonxml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/** * Created by Ravi Godara on 10/9/2016. */public class ConnManager {
    public static String getData(String uri)
    {
        BufferedReader reader=null;
        try {
            URL url=new URL(uri);
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            StringBuilder sb=new StringBuilder();
            reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            while ((line=reader.readLine())!=null) {
                sb.append(line+"\n");
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        finally{
            if(reader!=null)
            {
                try {
                    reader.close();
                } catch (IOException e) {

                    e.printStackTrace();
                    return null;
                }
            }
        }
    }
}

b. Person Class
package com.example.ravigodara.parsejsonxml;

public class Person
{
    private int my_id;
    private String fname;
    private String address;
    public int getMy_id() {
        return my_id;
    }

    public void setMy_id(int my_id) {
        this.my_id = my_id;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

c. XML Parser class as 

package com.example.ravigodara.parsejsonxml;

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

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class PersonXMLParser {
    public static List<Person> parseFeed(String content)
    {
        try        {
            boolean inDataItemTag=false;
            String currentTagName="";
            Person person=null;
            List<Person> personList=new ArrayList<>();
            XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
            XmlPullParser parser=factory.newPullParser();
            parser.setInput(new StringReader(content));
            int eventType=parser.getEventType();
            while(eventType!=XmlPullParser.END_DOCUMENT)
            {
              
                switch(eventType)
                {
                    case XmlPullParser.START_TAG:
                        currentTagName=parser.getName();
                        if(currentTagName.equals("personal"))
                        {
                            inDataItemTag=true;
                            person=new Person();
                            personList.add(person);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if(parser.getName().equals("personal"))
                        {
                            inDataItemTag=false;
                        }
                        currentTagName = "";
                        break;

                    case XmlPullParser.TEXT:
                        if(inDataItemTag && (person != null)){

                            switch(currentTagName)
                            {
                                case "uid":
                                  person.setMy_id(Integer.parseInt(parser.getText()));
                                    break;
                                case "first_name":
                                    person.setFname(parser.getText());
                                    break;
                                case "address":
                                    person.setAddress(parser.getText());
                                    break;

                                default:
                                    break;
                            }
                        }
                        break;
                }
                eventType=parser.next();
            }
            return personList;
        }catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

}

d. Adapter as 
package com.example.ravigodara.parsejsonxml;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


public class PersonAdapter extends ArrayAdapter<Person> {
    private Context context;
    private List<Person> personList;


    public PersonAdapter(Context context, int resource, List<Person> objects)
     {
        super(context, resource, objects);
        this.context = context;
        this.personList = objects;
    }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)
                  context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.single_person, parent, false);
        Person person = personList.get(position);
        TextView textView1 = (TextView) view.findViewById(R.id.name);
        TextView textView2 = (TextView) view.findViewById(R.id.address);
        textView1.setText(person.getFname());
        textView2.setText(person.getAddress());

        return view;

    }
}

e. MainActivity as 

package com.example.ravigodara.parsejsonxml;

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    ProgressBar pb;
    List<MyTask> tasks;
    List<Person> personList;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb=(ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);
        tasks=new ArrayList<>();
    }
    public void loadData(View view)
    {
        requestData("http://10.0.2.2/anddb/xmlres.php");
    }
    private void requestData(String uri) {
        MyTask task=new MyTask();
        task.execute(uri);
    }
   
    private class MyTask extends AsyncTask<String, String, String> {

        @Override        protected void onPreExecute() {
            
            if(tasks.size()==0)
            {
                pb.setVisibility(View.VISIBLE);
            }
            tasks.add(this);
        }
        @Override        protected String doInBackground(String... params) {
            String content=ConnManager.getData(params[0]);
            return content;
        }
        @Override        protected void onPostExecute(String result) {
          
            personList=PersonXMLParser.parseFeed(result);
            updateDisplay();
            tasks.remove(this);
            if(tasks.size()==0)
            {
                pb.setVisibility(View.INVISIBLE);
            }

        }
        @Override        protected void onProgressUpdate(String... values) {
            //updateDisplay(values[0]);        }
    }
    protected void updateDisplay() {
      
        PersonAdapter adapter = new PersonAdapter(this,
                              R.layout.single_person, personList);
        setListAdapter(adapter);
    }
}

C. output as 




**** Don't forget t add Internet Permission in manifest file