2013-09-03 5 views
0

Я использую объект XmlPullParserFactory для разбора некоторого XML, который я получаю с моего сервера. По какой-то причине он выходит из строя в заявлении while, и я не могу понять, почему это произойдет.Разбор XML с XmlPullParserFactory сбой во время выполнения

XML:

<?xml version="1.0" encoding="UTF-8"?> 
<body> 
<item> 
    <id>115240</id> 
    <title> 
    <![CDATA[Student Evangelism Team Leaves for Fiji]]> 
    </title> 
    <created>20130821-15:50</created> 
    <author> 
    <![CDATA[Staff Writer]]> 
    </author> 
    <summary> 
    <![CDATA[On August 21, Service, Justice, and Missions Coordinator Fabio Maia and ten 
     Pacific Union College students left for an eighteen-day evangelism mission in 
     Fiji with ShareHim and Quiet Hour Ministries.]]> 
    </summary> 
    <body_text> 
    <![CDATA[<p>On August 21, Service, Justice, and Missions Coordinator 
     Fabio Maia and ten Pacific Union College students left for an eighteen-day 
     evangelism mission in Fiji with ShareHim and Quiet Hour Ministries. Each 
     student will be placed in a specific community where they will present the 
     story of Christ’s love and sacrifice each evening. Many of the students are 
     active in the college’s praise and worship teams and brought their instruments 
     so they can share God’s love through music.</p> 
     <p>Before the group departed, the students gathered in 
     President Heather J. Knight’s office for a special blessing prayer led by 
     Pastor Mark Witas, the lead pastor of the PUC Church. Pastor Witas included 
     special prayer that God lead the group in doing good in His name. <a></a>The group also 
     bonded by sharing a meal together before heading to the airport for their 
     flight to Fiji.</p> 
     <p>For many PUC students, summer is the perfect opportunity to 
     devote time to ministry and service. While some students work at summer camps 
     or serve as literature evangelists, other groups get the experience of a 
     lifetime by sharing the gospel and serving local communities in places around 
     the world. The PUC community is invited to join in prayer for the team travelling 
     to Fiji as well as other student groups currently on short-term mission trips 
     to Nicaragua and Brazil.</p>]]> 
    </body_text> 
    <url>http://www.puc.edu/news/archives/2013/student-evangelism-team-leaves-for-fiji</url> 
    <images> 
    <image url="http://www.puc.edu/__data/assets/image/0014/115241/fiji.jpg" url_2x="http://www.puc.edu/__data/assets/image/0014/115241/varieties/2x.jpg" thumb_small="http://www.puc.edu/__data/assets/image/0014/115241/varieties/thumb.jpg" thumb_medium="http://www.puc.edu/__data/assets/image/0014/115241/varieties/thumb_large.jpg" thumb_large="http://www.puc.edu/__data/assets/image/0014/115241/varieties/thumb_large.jpg" /> 
    </images> 
    </item> 
... lots more item nodes 
</body> 

Java:

class PUCNewsItem 
{ 

    public String title; 
    public String summary; 
    public String body; 
    public String url; 
    public String imageUrl; 

} 

public class PUCDatasource extends Activity { 

    public static ArrayList<PUCNewsItem> getPUCNews() throws IOException { 

      String url = "http://api.mysite.com/list"; 
      InputStream is = downloadUrl(url); 
      XmlPullParserFactory pullParserFactory; 

      try { 
       pullParserFactory = XmlPullParserFactory.newInstance(); 
       XmlPullParser parser = pullParserFactory.newPullParser(); 
       parser.setInput(is, null); 

       ArrayList<PUCNewsItem> items = null; 
       int eventType = parser.getEventType(); 
       PUCNewsItem item = null; 
       Log.d("Debug: ", "Start"); 
       while (eventType != XmlPullParser.END_DOCUMENT){ 
        String name = null; 
        switch (eventType){ 
         case XmlPullParser.START_DOCUMENT: 
          Log.d("Debug: ", "Start doc"); 
          items = new ArrayList<PUCNewsItem>(); 
          break; 
         case XmlPullParser.START_TAG: 
          name = parser.getName(); 
          if (name == "item"){ 
           item = new PUCNewsItem(); 
          } else if (item != null){ 
           if (name == "title"){ 
            item.title = parser.nextText(); 
           } else if (name == "summary"){ 
            item.summary = parser.nextText(); 
           } else if (name == "body_text"){ 
            item.body = parser.nextText(); 
           } 
          } 
          break; 
         case XmlPullParser.END_TAG: 
          name = parser.getName(); 
          if (name.equalsIgnoreCase("item") && item != null) { 
           items.add(item); 
          } 
          break; 
        }//end switch 

        eventType = parser.next(); 

       }//end while 

       return items; 

      } catch (XmlPullParserException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return null; 

     }//end 

}//end class 

Ошибки:

09-03 16:31:50.100: W/System.err(16727): Invalid stream or encoding: java.io.IOException: Stream is closed (position:START_DOCUMENT [email protected]:1) caused by: java.io.IOException: Stream is closed; nested exception is: 
09-03 16:31:50.108: W/System.err(16727): java.io.IOException: Stream is closed 
09-03 16:31:50.108: W/System.err(16727): at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:158) 
09-03 16:31:50.108: W/System.err(16727): at libcore.io.Streams.readSingleByte(Streams.java:41) 
09-03 16:31:50.108: W/System.err(16727): at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:128) 
09-03 16:31:50.108: W/System.err(16727): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1623) 
09-03 16:31:50.108: W/System.err(16727): at com.puc.mobile.PUCDatasource.getPUCNews(PUCDatasource.java:40) 
09-03 16:31:50.108: W/System.err(16727): at com.puc.mobile.MainActivity$DownloadPUCNews.doInBackground(MainActivity.java:94) 
09-03 16:31:50.108: W/System.err(16727): at com.puc.mobile.MainActivity$DownloadPUCNews.doInBackground(MainActivity.java:1) 
09-03 16:31:50.108: W/System.err(16727): at android.os.AsyncTask$2.call(AsyncTask.java:264) 
09-03 16:31:50.108: W/System.err(16727): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
09-03 16:31:50.108: W/System.err(16727): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
09-03 16:31:50.108: W/System.err(16727): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 
09-03 16:31:50.108: W/System.err(16727): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
09-03 16:31:50.108: W/System.err(16727): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
09-03 16:31:50.108: W/System.err(16727): at java.lang.Thread.run(Thread.java:856) 
09-03 16:31:50.108: D/AndroidRuntime(16727): Shutting down VM 
09-03 16:31:50.108: W/dalvikvm(16727): threadid=1: thread exiting with uncaught exception (group=0x40aba210) 
09-03 16:31:50.108: E/AndroidRuntime(16727): FATAL EXCEPTION: main 
09-03 16:31:50.108: E/AndroidRuntime(16727): java.lang.NullPointerException 
09-03 16:31:50.108: E/AndroidRuntime(16727): at com.puc.mobile.MainActivity$DownloadPUCNews.onPostExecute(MainActivity.java:103) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at com.puc.mobile.MainActivity$DownloadPUCNews.onPostExecute(MainActivity.java:1) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.os.AsyncTask.finish(AsyncTask.java:602) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.os.AsyncTask.access$600(AsyncTask.java:156) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.os.Handler.dispatchMessage(Handler.java:99) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.os.Looper.loop(Looper.java:137) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at android.app.ActivityThread.main(ActivityThread.java:4697) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at java.lang.reflect.Method.invokeNative(Native Method) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at java.lang.reflect.Method.invoke(Method.java:511) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554) 
09-03 16:31:50.108: E/AndroidRuntime(16727): at dalvik.system.NativeStart.main(Native Method) 

Любые идеи о том, почему авария происходит? Должен ли я каким-то образом указывать имя моего узла роута?

+0

И трассировка стека/исключение? –

+0

Извините, только что добавил. –

ответ

1

Проблема не является циклом while, согласно трассировке стека.

09-03 16:31:50.108: W/System.err(16727): java.io.IOException: Stream is closed 
09-03 16:31:50.108: W/System.err(16727): at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:158) 
09-03 16:31:50.108: W/System.err(16727): at libcore.io.Streams.readSingleByte(Streams.java:41) 
09-03 16:31:50.108: W/System.err(16727): at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:128) 
09-03 16:31:50.108: W/System.err(16727): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1623) 

Он генерирует исключение в setInput() в коде перед циклом while.

Главной причиной здесь может быть много чего. Я бы начал с просмотра кода downloadUrl() и посмотрел, есть ли причина, по которой он может вернуть поток, который уже закрыт.

+0

Похоже, вы были правы. Я закрывал поток в функции downloadUrl(). Благодаря! –