我写了下面这段代码。从互联网上找到它。这是我第一次使用XML Parsers。
public class MainActivity extends ListActivity {
List headlines;
List links;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
headlines = new ArrayList();
links = new ArrayList();
try {
URL url = new URL("http://www.sportlarissa.gr/feed/");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG &&
xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
private InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse((String) links.get(position));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
xml文件如下。我很讨厌我在那里做错了什么,并且没有看到它!!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Logcat输出:
06-13 08:01:09.147: E/AndroidRuntime(1392): FATAL EXCEPTION: main
06-13 08:01:09.147: E/AndroidRuntime(1392): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.rssfeederproject/com.example.rssfeederproject.MainActivity}:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is
'android.R.id.list'
我有ListView,声明为
android:id="@+android:id/list"
为什么会这样?非常感谢提前:))
答案 0 :(得分:0)
删除+
:必须将ID声明为"@android:id/list"
。