检索XML feed,解析它并将其放在listview上

时间:2015-04-26 21:31:55

标签: android xml listview listadapter

我一直在编写这个脚本以检索XML Feed并在webview上显示它(这里有成功教程网址:http://developer.android.com/training/basics/network-ops/xml.html),但是,我试图将feed的条目放在listview上。

public class ListFeed extends ListActivity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";

// Whether there is a Wi-Fi connection.
private static boolean wifiConnected = false;
// Whether there is a mobile connection.
private static boolean mobileConnected = false;
// Whether the display should be refreshed.
public static boolean refreshDisplay = true;
public static String sPref = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_list_feed);

    new DownloadXmlTask().execute(URL);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

   // Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private List loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
    InputStream stream = null;
    // Instantiate the parser
    StackOverFlowXmlParser stackOverflowXmlParser = new StackOverFlowXmlParser();
    List<StackOverFlowXmlParser.Entry> entries = null;
    String title = null;
    String url = null;
    String summary = null;
    Calendar rightNow = Calendar.getInstance();
    // Checks whether the user set the preference to include summary text
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean pref = sharedPrefs.getBoolean("summaryPref", false);

    // List to store the items
    List<String> feed = new ArrayList<String>();

    try {
        stream = downloadUrl(urlString);
        entries = stackOverflowXmlParser.parse(stream);
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
    for (StackOverFlowXmlParser.Entry entry : entries) {
        feed.add(entry.title);
    }

    return feed;
}

    // Implementation of AsyncTask used to download XML feed from stackoverflow.com.
private class DownloadXmlTask extends AsyncTask<String, Void, List> {
    @Override
    protected List doInBackground(String... urls) {
        try {
            return loadXmlFromNetwork(urls[0]);
        } catch (IOException e) {
            //return getResources().getString(R.string.connection_error);
            return null;
        } catch (XmlPullParserException e) {
            //return getResources().getString(R.string.xml_error);
            return null;
        }
    }

    @Override
    protected void onPostExecute(List result) {
        setContentView(R.layout.activity_list_feed);

        //pass the data to the view
        ListView listView = (ListView) findViewById(R.id.list);
        // create adapter to match data to view
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ListFeed.this,R.layout.activity_list_feed,result);

        setListAdapter(arrayAdapter);

    }
}

}

使用AsyncTask完成Feed提取,我想在onPostExecute方法的listview中输出。 我在logcat中得到“你的内容必须有一个ListView,其id属性为'android.R.id.list'”消息。

这是XML布局文件:

`<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</ListView>`

注意:替换为TextView会导致相同的错误 谢谢你的建议。

这是清单文件:     `

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
    </activity>
    <activity
        android:name=".WebviewTest"
        android:label="@string/title_activity_webview_test" >
    </activity>
    <activity
        android:name=".SimpleFeed"
        android:label="@string/title_activity_simple_feed" >
    </activity>
    <activity
        android:name=".ListFeed"
        android:label="@string/title_activity_list_feed" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>`

1 个答案:

答案 0 :(得分:0)

而不是android:id="@+id/list"

您需要android:id="@android:id/list"

这是android系统可以使用的已经生成的id,而不是你自己创建的具有相同名称的id。

请记住,XML中的所有id实际上都是用int值在Java中表示的。因此,每次创建新id时,都会创建新的int。在上面的示例中,android:id/list是系统的已知值,但您创建id/list是一个特定于您的应用的新数字,因此在扩展ListActivity(系统代码)时系统无法知道并且不能引用您的特定生成的id