我正在尝试使用XML文件中的项目填充ListView
。
我知道它因为我使用Fragments
,但我真的不知道如何解决它。
栈跟踪
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iklikla.codetechblog/com.iklikla.codetechblog.FrontpageActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ListActivity.onContentChanged(ListActivity.java:243)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:273)
at android.app.Activity.setContentView(Activity.java:1881)
at com.iklikla.codetechblog.FrontpageActivity.onCreate(FrontpageActivity.java:56)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
我的活动:
public class FrontpageActivity extends ListActivity {
// All static variables
static final String URL = "http://blog.codetech.de/rss";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_LINK = "link";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frontpage);
ActionBar actionBar = getActionBar();
actionBar.setDisplayUseLogoEnabled(true);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list,
new String[] { KEY_TITLE, KEY_LINK }, new int[] {
R.id.textView, R.id.textView2 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.textView)).getText().toString();
String link = ((TextView) view.findViewById(R.id.textView2)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), WebViewActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_LINK, link);
startActivity(in);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.frontpage, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int itemId = item.getItemId();
switch (itemId)
{
case R.id.action_reload:
Intent intent_reload = new Intent(this, FrontpageActivity.class);
startActivity(intent_reload);
break;
case R.id.action_about:
Intent intent_about = new Intent(this, AboutActivity.class);
startActivity(intent_about);
break;
default:
break;
}
return true;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_frontpage, container, false);
return rootView;
}
}
}
我的片段XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.iklikla.codetechblog.FrontpageActivity$PlaceholderFragment"
android:background="@color/background_grey">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/tutorialTitle"
android:background="@drawable/card"/>
</RelativeLayout>
编辑:这是我的activity_frontpage.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.iklikla.codetechblog.FrontpageActivity"
tools:ignore="MergeRootFrame" />
答案 0 :(得分:0)
public class FrontpageActivity extends ListActivity
在activity_frontpage.xml
中,您的活动应该延伸ListActivity
并且setContentView(R.layout.activity_frontpage)
中有onCreate
<ListView android:id="@android:id/list"
编辑:
如果您需要ListView
中的Fragment
。你弄错了。 Fragment
由Activity
托管。您需要将所有代码移动到片段并使用asynctask从服务器获取gettign xml。休息一切都是我自己解释的。
你应该检查的链接
http://developer.android.com/training/basics/network-ops/xml.html http://developer.android.com/reference/android/app/ListActivity.html http://developer.android.com/reference/android/os/AsyncTask.html
public class FrontpageActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frontpage);
ActionBar actionBar = getActionBar();
actionBar.setDisplayUseLogoEnabled(true);
getFragmentManager().beginTransaction()
.add(R.id.container, new MyFragment())
.commit();
}
}
MyFragment
public class MyFragment extends ListFragment {
static final String URL = "http://blog.codetech.de/rss";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_LINK = "link";
private static final String ns = null;
ListView lv;
List<Entry> all = new ArrayList<Entry>();
ProgressDialog pd;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment1, container, false);
pd = new ProgressDialog(getActivity());
pd.setMessage("Getting xml and parsing...");
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
lv = getListView();
new TheTask(getActivity()).execute();
}
class TheTask extends AsyncTask<Void,ArrayList<Entry>,ArrayList<Entry>>
{
Context context;
TheTask(Context context)
{
this.context = context;
}
@Override
protected void onPostExecute(ArrayList<Entry> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
CustomAdapter cus = new CustomAdapter(context,result);
lv.setAdapter(cus);
lv.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(context, "text", Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.show();
}
@Override
protected ArrayList<Entry> doInBackground(Void... params) {
// TODO Auto-generated method stub
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(URL);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _respons=EntityUtils.toString(resEntity);
InputStream is = new ByteArrayInputStream(_respons.getBytes());
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
all =readFeed(parser);
}catch(Exception e)
{
e.printStackTrace();
}
return (ArrayList<Entry>) all;
}
}
private List<Entry> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
List<Entry> all = null ;
parser.require(XmlPullParser.START_TAG, ns, "rss");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// Starts by looking for the entry tag
if (name.equals("channel")) {
all= readItem(parser);
} else {
skip(parser);
}
}
return all;
}
private List<Entry> readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
List<Entry> entries = new ArrayList<Entry>();
parser.require(XmlPullParser.START_TAG, ns, "channel");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// Starts by looking for the entry tag
if (name.equals("item")) {
entries.add(readEntry(parser));
} else {
skip(parser);
}
}
return entries;
}
private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "item");
String title = null;
String link = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} else if (name.equals("link")) {
link = readLink(parser);
} else {
skip(parser);
}
}
return new Entry(title, link);
}
// Processes title tags in the feed.
private String readTitle(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
Log.i("..............",title);
return title;
}
// Processes link tags in the feed.
private String readLink(XmlPullParser parser) throws IOException, XmlPullParserException {
String link = "";
parser.require(XmlPullParser.START_TAG, ns, "link");
// String tag = parser.getName();
link =readText(parser);
// String relType = parser.getAttributeValue(null, "rel");
// if (tag.equals("link")) {
// if (relType.equals("alternate")){
// link = parser.getAttributeValue(null, "href");
// parser.nextTag();
// }
// }
parser.require(XmlPullParser.END_TAG, ns, "link");
Log.i("..............",link);
// map.put(KEY_LINK, link);
return link;
}
// For the tags title and summary, extracts their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
my_fraagment1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.iklikla.codetechblog.FrontpageActivity$PlaceholderFragment"
>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Entry.java
public class Entry {
public final String title;
public final String link;
Entry(String title, String link) {
this.title = title;
this.link = link;
}
}
CustomAdapter
public class CustomAdapter extends BaseAdapter {
private LayoutInflater minflater;
ArrayList<Entry> entry;
public CustomAdapter(Context context, ArrayList<Entry> result) {
// TODO Auto-generated constructor stub
minflater = LayoutInflater.from(context);
this.entry=result;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return entry.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
convertView =minflater.inflate(R.layout.list_item, parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder= (ViewHolder) convertView.getTag();
}
holder.tv1.setText(entry.get(position).title);
holder.tv2.setText(entry.get(position).link);
return convertView;
}
static class ViewHolder
{
TextView tv1,tv2;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="38dp"
android:text="TextView" />
</RelativeLayout>
快照