请查看我的代码..
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
请给出一些解决方案。
答案 0 :(得分:5)
尝试实现AsyncTask以从文档中获取String(在doInBackground
中),然后使用onPostExecute
在TextView上设置Text。
在不阻塞UI线程的情况下,是执行后台逻辑的最佳方法。
答案 1 :(得分:4)
尝试查看runUIThread(...)函数
当您从其他线程编辑某些UI组件而非“主”线程时,通常会发生该异常;我想问题出在:
tvs.setText(sen.substring(0, sen.indexOf("*"))); tvd.setText(sen.substring(sen.indexOf("*")+1)); tvd.setBackgroundResource(R.drawable.plus);
答案 2 :(得分:1)
您无法从非UI线程更新UI(UI线程是调用Activity的onCreate的线程)。要实现您要执行的操作,您需要使用Handler将消息从当前线程发布到UI线程。请看这个答案:android: displaying progress dialog when waiting for connection