0
我想分析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();
但似乎運行方法沒有被調用本身。有人可以幫助我找出我在這裏錯過了什麼。
編輯: 以下是有關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函數內。
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 android.os.Handler.<init>(Handler.java:200)
它看起來像run方法運行fine..but我得到異常:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
能有人幫...
是什麼讓你覺得它沒有被叫? – Savior
在't.start()'後添加't.join()' –
@ElliottFrisch只是好奇t.join()會如何區別? – Jois