我在解析來自URL的XML時遇到了問題。我創建一個天氣應用程序,我想從http://api.openweathermap.org/解析XML。我用這個AsyncTask,它不工作。這是我的代碼,謝謝你的回覆。只有ProgressDialog正在顯示,不再顯示。我也有清單中的互聯網許可。Android XML解析AsyncTask
Weather.java
public class Weather extends AsyncTask<String[],Void,String[]> {
private MainActivity activity;
private XmlPullParserFactory factoryObj;
private String url;
private ProgressDialog pDialog;
public Weather(MainActivity activity, String url) {
this.activity = activity;
this.url = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Loading...");
pDialog.setTitle("Please wait");
pDialog.show();
}
@Override
protected String[] doInBackground(String[]... params) {
try{
URL myurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
factoryObj = XmlPullParserFactory.newInstance();
XmlPullParser parser = factoryObj.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
parser.setInput(stream,null);
String[] result = parseXML(parser);
stream.close();
return result;
}catch(Exception e)
{
e.printStackTrace();
return null;
}
}
public String[] parseXML(XmlPullParser parser) throws IOException,XmlPullParserException{
int event;
String text=null;
String[] result =new String[1];
event = parser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
String name = parser.getName();
switch(event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
break;
case XmlPullParser.END_TAG:
if(name.equals("temperature"))
result[0] = parser.getAttributeValue(null,"value");
break;
}
parser.next();
}
return result;
}
@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
pDialog.dismiss();
activity.callBackData(result);
}
}
和MainActivity.java:
public class MainActivity extends Activity {
TextView temp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = (TextView) findViewById(R.id.temptextView);
String url ="http://api.openweathermap.org/data/2.5/weather?q=warsaw&mode=xml&appid=35fae97674d2f8032b66a35addf05450";
new Weather(this,url).execute();
}
public void callBackData(String[] result) {
temp.setText(result[0]);
}
}
這是拋出異常嗎? – Lino
不,應用從不停止。 – Mateusz