未在线程中调用java运行方法
我正在尝试使用一个单独的线程解析xml。整个代码的小代码段如下所示:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
c=c1;
URL url = new URL(url1);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
InputStream i= con.getInputStream();
xf=XmlPullParserFactory.newInstance();
xp=xf.newPullParser();
xp.setInput(i,null);
parseXML(xp,c);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.start();
但似乎run方法本身并没有被调用。有人能帮我找出我在这里遗漏了什么吗
编辑: 以下是与XML相关的全部代码:
public void fetchXml(String u,final Context c1) throws IOException, XmlPullParserException, InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
c=c1;
URL url = new URL(url1);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
InputStream i= con.getInputStream();
xf=XmlPullParserFactory.newInstance();
xp=xf.newPullParser();
xp.setInput(i,null);
parseXML(xp,c);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.start();
t.join();
}
public void parseXML(XmlPullParser xp,Context c) throws XmlPullParserException, IOException {
int event;
String text=null;
Toast.makeText(c, "inside parse", Toast.LENGTH_LONG).show();
event=xp.getEventType();
while(event!=XmlPullParser.END_DOCUMENT)
{
String name=xp.getName();
switch(event)
{
case XmlPullParser.START_TAG :
break;
case XmlPullParser.TEXT :
text=xp.getText();
break;
case XmlPullParser.END_TAG :
if(name.equals("country")){
country=text;
Toast.makeText(c, "Country"+country, Toast.LENGTH_LONG).show();
}
else if(name.equals("humidity")){
humidity=xp.getAttributeValue(null,"value");
Toast.makeText(c, "humidity"+humidity, Toast.LENGTH_LONG).show();
}
else if (name.equals("pressure"))
{
pressure=xp.getAttributeValue(null,"value");
Toast.makeText(c, "pressure"+pressure, Toast.LENGTH_LONG).show();
}
else{}
break;
}
event=xp.next();
}
parsingcomplete=true;
}
另外,当我检查logcat时,我在上面的parsexml函数中编写的Toast语句出现以下错误
04-11 07:59:08.891 31361-31580/com.example.hp.xmlparsing W/System.err: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-11 07:59:08.892 31361-31580/com.example.hp.xmlparsing W/System.err: at 安卓.os.Handler.<init>(Handler.java:200)
看起来run方法运行得很好。。但我得到了一个例外:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
有人能帮忙吗
# 1 楼答案
跑
内部GUI线程: