我正在处理一个项目,在该项目中我正在解析来自 Internet 的 XML 文件并在 TextView 中显示其内容。
过程: 当我单击按钮时,我将自己转到预测类,我在其中从互联网获取 xml,但现在我将异步进度对话框添加到其中。 编码没有错误,但是当我在模拟器中运行应用程序时,它显示捕获异常消息“错误”,它不显示在添加异步进度对话框之前显示的“信息”。
public class Prediction extends Activity{
static final String baseUrl = "http://astroyogi.in/testandroid/Tarot/Tarot_Android.xml";
TextView tv1;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.prediction);
grabURL("http://astroyogi.in/testandroid/Tarot/Tarot_Android.xml");
tv1 = (TextView) findViewById(R.id.tv1);
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(Prediction.this);
static final String baseUrl = "http://astroyogi.in/testandroid/Tarot/Tarot_Android.xml";
protected void onPreExecute() {
Dialog.setMessage("Downloading source..");
Dialog.show();
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
URL website = new URL(baseUrl);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
Handlingpastxml doingWork = new Handlingpastxml();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String information = doingWork.getInformation();
tv1.setText(information);
}
catch(Exception e){
tv1.setText(e.getMessage());
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
}
}
}
最佳答案
仅供引用, 您不能在 doInBackground() 方法中(直接)执行显示/更新 UI 类操作。
解决方案一:
从 doInBackground() 中删除以下行并将其粘贴到 onPostExecute()
tv1.setText(information);
方案二:
如果你想在 anyway 中的 doInBackground() 中显示/更新 UI,那么将这种操作写在 runOnUiThread()
:
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
tv1.setText(information);
}
});
关于安卓 : Text is not Showing in the TextView after applying Async Progress Dialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532331/