我不确定为什么会出现异常。我要做的就是获取文档的第一个描述标签(最终应该是“本周最佳曲目”)。
package com.example.rssparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlPullParser;
import com.example.rssparser.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Xml;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
new Parse().execute(new URL("http://staging.satelliterecords.com/hot_picks/rss"));
}catch(MalformedURLException e){
Toast.makeText(this, "Error: Malformed URL", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public String parseInputSource(InputSource inputSource) throws Exception{
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputSource.getCharacterStream());
int eventType = parser.getEventType();
String description = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
String tagName = parser.getName();
if (tagName.equalsIgnoreCase("description")){
description = parser.nextText();
return description;
}
break;
default:
break;
}
eventType = parser.next();
}
throw new RuntimeException("No description tag found in XML document");
}
private class Parse extends AsyncTask<URL, Void, String>{
protected String doInBackground(URL...url){
try{
InputSource inputSource = new InputSource(url[0].openStream());
String result = parseInputSource(inputSource);
return result;
}catch(IOException e){
return "Error IO";
}catch(Exception e){
return "Error PullParser";
}
}
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.helloyo);
txt.setText(result);
}
}
}
文本区域正在输出“Error PullParser”。我对 Java 比较陌生,甚至对 Android 开发人员也比较陌生,所以我的错误处理技能可能没有应有的好。另外我不知道如何阅读 LogCat,所以我不确定答案是否隐藏在那里。