简体   繁体   English

如何在Android中的ListView中显示已解析的html

[英]How to display parsed html in a ListView in Android

I'm trying to parse news titles from a website using jsoup and display them in a ListView. 我正在尝试使用jsoup解析来自网站的新闻标题并将其显示在ListView中。 I have been trying to solve this problem for a long time and have googled like crazy but i am unable to solve my problem or find a working solution. 我很久以来一直在尝试解决这个问题,并且疯狂地谷歌搜索,但是我无法解决我的问题或找到有效的解决方案。 I have a custom class that holds two variables the news title and the link to the article. 我有一个自定义类,其中包含两个变量,即新闻标题和文章链接。 It seems as if everything parses fine but I just can't get my ListView to display correctly or at all... it continually crashes and it seams that every time I get a different error. 似乎一切解析都很好,但我只是无法正确显示或完全不显示ListView ...它不断崩溃,并接缝着每当我遇到另一个错误时。 Maybe I am making it too hard on myself. 也许我对自己太难了。 I am frustrated and can't think logically anymore... I would really appreciate any and all tips or helpful answers. 我很沮丧,不能再逻辑思考了……我将不胜感激所有提示或有用的答案。

Feeds class: 提要类别:

public class Feeds {

private String mNewsTitle;
private String mNewsLink;

public Feeds(String newsTitle, String newsLink){
    mNewsTitle = newsTitle;
    mNewsLink = newsLink;
 }

public String getNewsTitle(){
    return mNewsTitle;
 }

public void setNewsTitle(String newsTitle){
    mNewsTitle = newsTitle;
 }

public String getNewsLink(){
    return mNewsLink;
 }

public void setNewsLink(String newsLink){
    mNewsTitle = newsLink;
 }
}

NewsFeeds class: NewsFeeds类:

public class NewsFeeds extends ListActivity {

private ArrayList<Feeds> mFeedDB = new ArrayList<Feeds>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news_feeds);

    HtmlParser htmlThread = new HtmlParser();
    htmlThread.execute();


} // end on create

public class HtmlParser extends AsyncTask<Void, Integer, ArrayList<Feeds>> {

    private static final int NETWORK_NO_ERROR = -1;
    private static final int NETWORK_HOST_UNREACHABLE = 1;
    private static final int NETWORK_NO_ACCESS_TO_INTERNET = 2;
    private static final int NETWORK_TIME_OUT = 3;

    Integer serverError = NETWORK_NO_ERROR;

    ProgressDialog dialog;

    protected void onPreExecute() {
        // example of setting up something
        dialog = new ProgressDialog(NewsFeeds.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("Retrieving News Feeds");
        dialog.show();
    } // end onPreExecute

    @Override
    protected ArrayList<Feeds> doInBackground(Void... params) {
        try {
            // need http protocol
            Document doc = Jsoup.connect("http://baseball-potsdam.de/news")
                    .get();

            // get news feed titles
            Elements newsFeed = doc.getElementsByClass("gdlr-blog-title");

            // get all links
            Elements links = newsFeed.select("a[href]");


            for (Element link : links) {
                // populate ArrayList with news titles and links
                mFeedDB.add(new Feeds(link.text(), link.attr("href")));
            }

            return mFeedDB;

            // } catch (IOException e) {
            // e.printStackTrace();
        } catch (ConnectException e) {
            serverError = NETWORK_NO_ACCESS_TO_INTERNET;
            return null;
        } catch (UnknownHostException e) {
            serverError = NETWORK_HOST_UNREACHABLE;
            return null;
        } catch (SocketTimeoutException e) {
            serverError = NETWORK_TIME_OUT;
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } // end try catch
        return null;

    } // end doInBackground

    protected void onProgressUpdate(Integer... progress) {

    } // end onProgressUpdate

    protected void onPostExecute(ArrayList<Feeds> result) {
        if (result != null) {

            ListView listview = (ListView) findViewById(R.id.list_view_news_feeds);
            listview.setAdapter(new ArrayAdapter<Feeds>(NewsFeeds.this, android.R.layout.simple_list_item_1 , mFeedDB));


            if (dialog.isShowing()) {
                dialog.dismiss();
            } // end if
        } else {
            switch (serverError) {
            case NETWORK_NO_ERROR:
                Toast.makeText(NewsFeeds.this,
                        "Probably, invalid response from server",
                        Toast.LENGTH_LONG).show();
                break;
            case NETWORK_NO_ACCESS_TO_INTERNET:
                // You can customize error message (or behavior) for
                // different type of error
            case NETWORK_TIME_OUT:
            case NETWORK_HOST_UNREACHABLE:
                Toast.makeText(NewsFeeds.this, "Error in Connection",
                        Toast.LENGTH_LONG).show();
                break;
            }
        } // end if else
        } // end onPostExecute
    } // end HtmlParser class
} // end NewsFeeds

activity_news_feeds.xml activity_news_feeds.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >   

    <ListView
        android:id="@+id/list_view_news_feeds"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:dividerHeight="0.1dp"
        android:divider="#0000CC"
    />
</LinearLayout>

NewsManifest.xml NewsManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kylehopeman.android.porcupinesnews"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.kylehopeman.android.porcupinesnews.MainMenu"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.kylehopeman.android.porcupinesnews.NewsFeeds"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.kylehopeman.android.porcupinesnews.NewsFeeds" />
             <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>      
    </application>
</manifest>

If you are getting an error with the ListView it looks like it only gets instantiated in the postExecute block. 如果您在使用ListView时遇到错误,则看起来它仅在postExecute块中实例化。 Is it possible to instantiate it in the onCreate() and have it declared where you declare mFeedDB? 是否可以在onCreate()上实例化它,并在声明mFeedDB的地方声明它?

After changing the first line in my NewsFeeds.java file from: 将NewsNewFeeds.java文件中的第一行从以下位置更改后:

public class NewsFeeds extends ListActivity

to: 至:

public class NewsFeeds extends Activity

the errors went away, the app compiled and worked just like I wanted it to. 错误消失了,应用程序像我希望的那样编译并运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM