2011-06-27 38 views
1

叫做請看看我的代碼..從錯誤的線程異常

public class BseDemo extends Activity { 
    final String feedUrlString = "http://www.bseindia.com/sensex/xml-data/sensexrss.xml"; 
    Uri uri; 
    TextView tvs,tvd; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 


     Bse b = new Bse(); 
     b.start(); 


    } 
    class Bse extends Thread{ 
     public void run(){ 
      try { 
       tvs = (TextView)findViewById(R.id.text); 
       tvd = (TextView)findViewById(R.id.diff); 
       URL url = new URL(feedUrlString); 
       DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 
       DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 
       Document doc = docBuilder.parse (new InputSource(url.openStream())); 
       doc.getDocumentElement().normalize(); 
       Element e = doc.getDocumentElement(); 
       NodeList nl = e.getElementsByTagName("title"); 
       Node bse = nl.item(2); 
       String sen = bse.getFirstChild().getNodeValue(); 
       tvs.setText(sen.substring(0, sen.indexOf("*"))); 
       tvd.setText(sen.substring(sen.indexOf("*")+1)); 
       tvd.setBackgroundResource(R.drawable.plus); 
      } catch (Exception e) { 
       throw new RuntimeException(e); 
      } 
     } 
    } 
} 

我上面提到的代碼和我得到異常CalledFromWrongTreadException 請給一些解決方案。

+1

你在哪個行中發生異常?你能提一下嗎? –

回答

5

試圖實現一個AsyncTask獲得從文檔(在doInBackground)的字符串然後使用onPostExecute設置在TextViews文本。

是在不阻塞UI線程的情況下執行後臺邏輯的最佳方法。

4

試圖尋找到runUIThread(...)函數

當你編輯從其他線程一些UI組件比異常通常發生在「主」之一;我想這個問題是:

tvs.setText(sen.substring(0, sen.indexOf("*"))); 
tvd.setText(sen.substring(sen.indexOf("*")+1)); 
tvd.setBackgroundResource(R.drawable.plus); 
+0

這比我下面概述的方法簡單得多。 +1 – sparkymat

相關問題