2

I am learning How to parse xml document in Android.I have full source code of XML parsing but it Shows Output on Console.But i want to show result data in ListView i dont know how to display data into listview.Could you help me to solve this issue.i am giving full source code here. MainActivity.java

public class MainActivity extends Activity {
    private ProgressDialog pDialog;
    private ItemXMLHandler myXMLHandler;
    private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
    private TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textview =(TextView)findViewById(R.id.textView1);
    }

    public void doParsing(View v)
    {

        if (isNetworkAvailable()) 
        {
            textview.setText("Loading...Please wait...");
            new AsyncData().execute(rssFeed);
        }
        else
        {
            showToast("No Network Connection!!!");
        }   
    }
    class AsyncData extends AsyncTask<String, Void, Void> 
    {

        @Override
        protected void onPreExecute() 
        {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setTitle("Loading....");
            pDialog.setMessage("Please wait...");
            pDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) 
        {

            try 
            {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();

                myXMLHandler = new ItemXMLHandler();
                xr.setContentHandler(myXMLHandler);

                URL _url = new URL(params[0]);

                xr.parse(new InputSource(_url.openStream()));

            } catch (ParserConfigurationException pce) 
            {
                Log.e("SAX XML", "sax parse error", pce);
            } catch (SAXException se) 
            {
                Log.e("SAX XML", "sax error", se);
            } catch (IOException e) 
            {
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);

            textview.setText("Done!!!");
            if (pDialog != null && pDialog.isShowing())
            {
                pDialog.dismiss();
            }

            ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
            //ArrayList<String> temp=new ArrayList<String>();

            if (null != itemsList && itemsList.size() != 0)
            {
                for (int index = 0; index < itemsList.size(); index++) 
                {
                    Bean objBean = itemsList.get(index);

                    /*System.out.println(">>>>>>>>>>>>>>>" + index);
                    System.out.println("ID :: " + objBean.getId());
                    System.out.println("TITLE :: " + objBean.getTitle());
                    System.out.println("DESC :: " + objBean.getDesc());
                    System.out.println("PUBDATE :: " + objBean.getPubDate());
                    System.out.println("LINK :: " + objBean.getLink());*/

                    // Store values in ArrayList and Pass to the Customer Adapter class 


                }
            }
        }
    }

    public void showToast(String msg) 
    {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
    }

    public boolean isNetworkAvailable() 
    {
        ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) 
        {
            return false;
        } 
        else 
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) 
            {
                for (int i = 0; i < info.length; i++) 
                {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) 
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

XmlHandlerclass

public class ItemXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = "";
    Bean item = null;
    private ArrayList<Bean> itemsList = new ArrayList<Bean>();

    public ArrayList<Bean> getItemsList()
    {
        return itemsList;
    }

    // Called when tag starts
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException 
   {

        currentElement = true;
        currentValue = "";

        if (localName.equals("item"))
        {
            item = new Bean();
        }

    }

    // Called when tag closing
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException 
    {

        currentElement = false;

        if (localName.equals("id")) 
        {
            item.setId(currentValue);
        } else if (localName.equals("title")) 
        {
            item.setTitle(currentValue);
        } else if (localName.equals("desc"))
        {
            item.setDesc(currentValue);
        } else if (localName.equals("pubDate")) 
        {
            item.setPubDate(currentValue);
        } else if (localName.equals("link"))
        {
            item.setLink(currentValue);
        } else if (localName.equals("item")) 
        {
            itemsList.add(item);
        }
    }

    // Called to get tag characters
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException 
   {

        if (currentElement) 
        {
            currentValue = currentValue + new String(ch, start, length);
        }
    }

}

BeanClass which storing Data

public class Bean {

    private String id;
    private String title;
    private String desc;
    private String pubDate;
    private String link;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

}
2

1 Answer 1

3

You will need a list view

In your main.xml have ListView. Customize the way you want.

      <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_alignParentLeft="true"
      >
     </ListView>

Declare ListView as class member

ListView lv;

Then in MainActivity onCreate initialize ListView

 lv = (ListView) findViewById(R.id.listView1);

In onPostExecute

  ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
  lv.setAdapter(new CustomAdapter(MainActivity.this,itemsList));

Have a row.xml. Customize according to your requirements.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="17dp"
            />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView2"
            android:layout_below="@+id/textView2"
            android:layout_marginTop="26dp"
             />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="24dp"
             />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView3"
            android:layout_below="@+id/textView3"
            android:layout_marginTop="23dp"
            />

    </RelativeLayout>

Then your CustomAdapter

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

class CustomAdapter extends BaseAdapter
{
    Context mContext;
    ArrayList<Bean> beandata;
    LayoutInflater mInflater;
    public CustomAdapter(Context context,ArrayList<Bean> itemList) 
    {
        mContext = context;
        beandata = itemList;
        mInflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return beandata.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder vh;
        if(convertView == null)
        {
            vh= new ViewHolder();
             convertView = mInflater.inflate(R.layout.row, 
                     parent, false);
            vh.tv1 = (TextView) convertView.findViewById(R.id.textView1);
            vh.tv2 = (TextView) convertView.findViewById(R.id.textView2);
            vh.tv3 = (TextView) convertView.findViewById(R.id.textView3);
            vh.tv4 = (TextView) convertView.findViewById(R.id.textView4);
            convertView.setTag(vh); 
        } else { 
            vh = (ViewHolder) convertView.getTag(); 
        }
            Bean objBean = beandata.get(position);
            vh.tv1.setText(objBean.getTitle());
            vh.tv2.setText(objBean.getDesc());
            vh.tv3.setText(objBean.getPubDate());
            vh.tv4.setText(objBean.getLink());

        return convertView;
    }
    static class ViewHolder
    {
        TextView tv1,tv2,tv3,tv4;
    }
}

You should use a listview with custom adapter. for each row in listview inflate a custom layout. Listview recycles views.

For smooth scrolling and performance use a view holder

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

It is better to use xmlpullparser as recommended by google

http://developer.android.com/training/basics/network-ops/xml.html

Snap shot. You need to customize ui according to your requirement.

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks yaar.Superb.Its Working.Thanks for clearing my concepts
if i face difficulty i will keep in touch with you.could you give your mail id.
How to parse Image and display into imageview
@user2522589 you need to make a http request download the image and display the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.