gpt4 book ai didi

android - 从错误的线程异常调用

转载 作者:行者123 更新时间:2023-11-29 14:25:37 24 4
gpt4 key购买 nike

请看我的代码..

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请给出一些解决方案。

最佳答案

尝试实现 AsyncTask从文档中获取字符串(在 doInBackground 中)然后使用 onPostExecute 在 TextView 上设置文本。

这是在不阻塞 UI 线程的情况下执行后台逻辑的最佳方法。

关于android - 从错误的线程异常调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6489382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com