2012-07-11 58 views
0

我在一個新的線程(實現可運行的類,如下所示)中拉動rss提要我想使用從rss提要得到的字符串並將它們返回到主類。主類只是運行的線程像這樣如何從線程返回值

new Thread(new RssParse()).start();

我有一個很艱難的時期設法返回這些字符串中切出XML到主類。任何幫助表示感謝。

public class RssParse implements Runnable { 

      private static final String MY_DEBUG_TAG = "pfaff"; 


      public void run(){ 

      System.out.println("1"); 
      URL iotd; 
      try{ 

       iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");//set URl 
       BufferedReader in;//new BufferedReader 
       in = new BufferedReader(new InputStreamReader(iotd.openStream()));//get rss 

       XmlPullParserFactory factory; 
       factory = XmlPullParserFactory.newInstance();//new factory 


       factory.setNamespaceAware(true); 
       XmlPullParser xpp; 
       xpp = factory.newPullParser(); 
       xpp.setInput(in); 


       int eventType; 
       eventType = xpp.getEventType(); 

       System.out.println(eventType+"!!!!!!!!!!!!!!!!"); 

      while(eventType!=XmlPullParser.END_DOCUMENT){ 

       switch(eventType){ 

       case XmlPullParser.START_DOCUMENT: 
        break; 
       case XmlPullParser.START_TAG: 
        String tagName=xpp.getName(); 
        System.out.println(tagName+" "+xpp.getDepth()); 
        if(tagName.equals("title")&& xpp.getDepth()==4){//depth is specific to this certain rss feed, there are multiple tags with the same names 
         String title=xpp.nextText();// I want to return title and a few other strings but can't figure out how to do this when dealing with threads. 
         System.out.println(title); 
        } 

        break; 

       } 
       eventType=xpp.next(); 
      }//switch 


       in.close();//close BufferedReader 
      } catch (MalformedURLException e){ 
       e.printStackTrace(); 
      }catch(XmlPullParserException e1){ 
       e1.printStackTrace(); 
      }catch(IOException e2){ 
       e2.printStackTrace(); 
      }   
     }//method 


}//class 
+0

在Java 5中,您將使用「Future」。請參閱[這裏](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html)。 – OldCurmudgeon 2012-07-12 00:29:28

回答

4

我想提議AsyncTask。您必須在您的子類中覆蓋AsyncTask的doInBackground(Params...)onPostExecute(Result)

教程:Android Threads, Handlers and AsyncTask - Tutorial

+0

這看起來正是我所需要的,現在看着它,謝謝! – 2012-07-11 03:05:28

+0

谷歌的例子有點令人困惑。你知道有更好的嗎? – 2012-07-11 05:35:52

+0

@TylerPfaff - 看看編輯過的帖子。 – adatapost 2012-07-11 05:38:45

0

可以使用處理器將它張貼在主線程

Runnable runnable = new Runnable() 
{ 
    @Override 
    public void run() { 
    for (int i = 0; i <= 10; i++) { 
    handler.post(new Runnable() { 
     @Override 
      public void run() { 
       progress.setProgress(value); 
      } 
     }); 
    } 
} 

};

+0

你能告訴我它在哪裏適合我的代碼 – 2012-07-11 04:18:18

+0

在你的run方法裏面你想要發佈到主線程中的對象你可以放置這個代碼 – 2012-07-11 04:29:06