Search code examples
javaxmlandroid-studiorssxmlpullparser

issues parsing data with XMLPullParser


Hi everyone after answering a question yesterday from a user living in the same country i decided to start playing around with the xml data he had asked his question on. I've been able to pull this data in correctly but now that i am trying to parse it I am receiving an error that I hoped one of you would know a solution to.

MainActivity.java snippet

public void run()
        {

            URL aurl;
            URLConnection yc;
            BufferedReader in = null;
            String inputLine = "";


            Log.e("MyTag","in run");

            try
            {
                Log.e("MyTag","in try");
                aurl = new URL(url);
                yc = aurl.openConnection();
                in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                //
                // Throw away the first 2 header lines before parsing
                //
                //
                //
                while ((inputLine = in.readLine()) != null)
                {
                    result = result + inputLine;
                    Log.e("MyTag",inputLine);
                }
                in.close();
            }

            catch (IOException ae)
            {
                Log.e("MyTag", "ioexception");
            }



            //@Override
            //public boolean onCreateOptionsMenu(Menu menu) {
            //Inflate the menu; this adds items to the action bar if it is present.
                    //getMenuInflater().inflate(R.menu.activity_main, menu);
            //return true;
        //}

            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Log.d("UI thread", "I am the UI thread");
                    ListView listView = (ListView) findViewById(R.id.listView1);
                    List<TravelIssue> travelIssues = null;
                    try {
                        XmlPullParserHandler parser = new XmlPullParserHandler();
                        InputStream is= getAssets().open(result);
                        travelIssues = parser.parse(is);

                        ArrayAdapter<TravelIssue> adapter =new ArrayAdapter<TravelIssue>(MainActivity.this,android.R.layout.simple_list_item_1, travelIssues);
                        listView.setAdapter(adapter);
                        urlInput.setText("");
                        urlInput.setText(is.toString());
                    } catch (IOException e) {e.printStackTrace();}

                }

            });
        }

    }



XmlPullParserHandler
    int eventType = parser.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    String tagname = parser.getName();
                    switch (eventType) {
                        case XmlPullParser.START_TAG:
                            if (tagname.equalsIgnoreCase("item")) {
                                // create a new instance of travelIssue
                                travelIssue = new TravelIssue();
                            }
                            break;

                        case XmlPullParser.TEXT:
                            text = parser.getText();
                            break;

                        case XmlPullParser.END_TAG:
                            if (tagname.equalsIgnoreCase("item")) {
                                // add travelIssue object to list
                                travelIssues.add(travelIssue);
                            }else if (tagname.equalsIgnoreCase("title")) {
                                travelIssue.setTitle(text);
                            }  else if (tagname.equalsIgnoreCase("description")) {
                                travelIssue.setDescription(text);
                            } else if (tagname.equalsIgnoreCase("link")) {
                                travelIssue.setLink(text);
                            } else if (tagname.equalsIgnoreCase("georss:point")) {
                                travelIssue.setGeorss(text);
                            } else if (tagname.equalsIgnoreCase("author")) {
                                travelIssue.setAuthor(text);
                            } else if (tagname.equalsIgnoreCase("comments")) {
                                travelIssue.setComments(text);
                            } else if (tagname.equalsIgnoreCase("pubDate")) {
                                travelIssue.setPubDate(text);
                            }
                            break;

                        default:
                            break;

Android Monitor output

    <?xml version="1.0" encoding="iso-8859-1"?>
    02-07 01:00:18.215 7212-7352/? E/MyTag: <rss version="2.0" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">
    02-07 01:00:18.215 7212-7352/? E/MyTag:   <channel>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <title>Traffic Scotland - Current Incidents</title>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <description>Current incidents on the road network e.g. accidents</description>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <link>https://trafficscotland.org/currentincidents/</link>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <language />
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <copyright />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <managingEditor />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <webMaster />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <lastBuildDate>Tue, 06 Feb 2018 22:41:52 GMT</lastBuildDate>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <docs>https://trafficscotland.org/rss/</docs>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <rating />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <generator>Traffic Scotland | www.trafficscotland.org</generator>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <ttl>5</ttl>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <item>
    02-07 01:00:18.216 7212-7352/? E/MyTag:       <title>Lothian &amp; Borders and South-West Scotland - Low temperature</title>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <link>http://tscot.org/01a8157</link>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <georss:point>55.634505 -3.418843</georss:point>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <author />
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <comments />
    02-07 01:00:18.220 7212-7352/? E/MyTag:       <pubDate>Tue, 06 Feb 2018 21:34:33 GMT</pubDate>
    02-07 01:00:18.220 7212-7352/? E/MyTag:     </item>
    ead: I am the UI thread
02-07 01:00:18.249 7212-7212/? W/System.err: java.io.FileNotFoundException: <?xml version="1.0" encoding="iso-8859-1"?><rss version="2.0" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">  <channel>    <title>Traffic Scotland - Current Incidents</title>    <description>Current incidents on the road network e.g. accidents</description>    <link>https://trafficscotland.org/currentincidents/</link>    <language />    <copyright />    <managingEditor />    <webMaster />    <lastBuildDate>Tue, 06 Feb 2018 22:41:52 GMT</lastBuildDate>    <docs>https://trafficscotland.org/rss/</docs>    <rating />    <generator>Traffic Scotland | www.trafficscotland.org</generator>    <ttl>5</ttl>    <item>      <title>Lothian &amp; Borders and South-West Scotland - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8157</link>      <georss:point>55.634505 -3.418843</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:34:33 GMT</pubDate>    </item>    <item>      <title>Strathclyde - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8158</link>      <georss:point>55.85579 -4.258607</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:35:15 GMT</pubDate>    </item>    <item>      <title>Central, Tayside and Fife  - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8159</link>      <georss:point>56.139467 -3.654317</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:36:02 GMT</pubDate>    </item>    <item>      <title>Grampian - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8160</link>      <georss:point>57.163647 -2.321385</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:36:27 GMT</pubDate>    </item>    <item>      <title>M77 Lanes from M77 to M8 J22 - Closure</title>      <description>There is no access from the M77 Northbound to the M8 Eastbound at Junction 22 due to essential overnight roadworks. Motorists are advised to use the available signed diversion route and should allow extra time for their journey.</description>      <link>http://tscot.org/01c189481</link>      <georss:point>55.848812447526 -4.29817817744965</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 19:55:04 GMT</pubDate>    </item>    <item>      <title>M8 J2 Westbound - slip off - Closure</title>      <description>M8(W) J2 Claylands exit slip to M9 is closed.  Drivers are advised to approach with caution and allow for longer than normal journey times.</description>      <link>http://tscot.org/01c189482</link>      <georss:point>55.9255161091877 -3.39157029498306</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 20:10:23 GMT</pubDate>    </item>    <item>      <title>M80 M8 Slip - M80 Main Carriageway - Closure</title>      <description>The M80 is closed Southbound at Junction 1 due to essential overnight roadworks.Motorists are advised to use the available signed diversion route and should allow extra time for their journey</description>      <link>http://tscot.org/01c189483</link>      <georss:point>55.8747347613743 -4.19821267415898</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 20:23:55 GMT</pubDate>    </item>   

    02-07 01:00:18.250 7212-7212/? W/System.err:     at android.content.res.AssetManager.openAsset(Native Method)
    02-07 01:00:18.250 7212-7212/? W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:360)
    02-07 01:00:18.251 7212-7212/? W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:334)
    02-07 01:00:18.251 7212-7212/? W/System.err:     at labstuff.gcu.owencannon.org.assignment.MainActivity$Task$1.run(MainActivity.java:148)

The program displays nothing when the appropriate buttons to pull in data are pressed, I am new to android studio (actually just started to learn it because i need to use it later in the year) so any help from people who know more would be appreciated thanks!

EDIT: Feel like i should add this line 148 that the android monitor refers to is this line

InputStream is= getAssets().open(result);

Solution

  • as stated in the comment above i managed to fix the parsing issue by changing the runnable method to the following.

    MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            Log.d("UI thread", "I am the UI thread");
                            try{
                                ListView lv = (ListView) findViewById(R.id.listView1);
                                SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                                SAXParser parser = parserFactory.newSAXParser();
                                DefaultHandler handler = new DefaultHandler(){
                                    String currentValue = "";
                                    boolean currentElement = false;
                                    public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
                                        currentElement = true;
                                        currentValue = "";
                                        if(localName.equals("item")){
                                            rss = new HashMap<>();
                                        }
                                    }
                                    public void endElement(String uri, String localName, String qName) throws SAXException {
                                        currentElement = false;
                                        if (localName.equalsIgnoreCase("title"))
                                            rss.put("title", currentValue);
                                        else if (localName.equalsIgnoreCase("description"))
                                            rss.put("description", currentValue);
                                        else if (localName.equalsIgnoreCase("link"))
                                            rss.put("link", currentValue);
                                        else if (localName.equalsIgnoreCase("georss:point"))
                                            rss.put("georss:point", currentValue);
                                        else if (localName.equalsIgnoreCase("author"))
                                            rss.put("author", currentValue);
                                        else if (localName.equalsIgnoreCase("comments"))
                                            rss.put("comments", currentValue);
                                        else if (localName.equalsIgnoreCase("pubDate"))
                                            rss.put("pubDate", currentValue);
                                        else if (localName.equalsIgnoreCase("item"))
                                            RSSList.add(rss);
                                    }
                                    @Override
                                    public void characters(char[] ch, int start, int length) throws SAXException {
                                        if (currentElement) {
                                            currentValue = currentValue +  new String(ch, start, length);
                                        }
                                    }
                                };
                                parser.parse(new InputSource(new StringReader(result)), handler);
                                ListAdapter adapter = new SimpleAdapter(MainActivity.this, RSSList, R.layout.list_row,new String[]{"title","description","link","georss:point","author","comments","pubDate"},
                                        new int[]{R.id.title, R.id.description, R.id.link, R.id.georss, R.id.author, R.id.comments, R.id.pubdate});
                                lv.setAdapter(adapter);
                            }
                            catch (IOException e) {
                                e.printStackTrace();
                            } catch (ParserConfigurationException e) {
                                e.printStackTrace();
                            } catch (SAXException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }