繁体   English   中英

Android-使用JSOUP实现AsyncTask的ListView

[英]Android - ListView with AsyncTask implementation using JSOUP

我需要一些建议,因为这件事使我花了足够的时间来对自己的知识缺乏生气……我试图使由JSOUP提取的数据填充的ListView。 JSOUP部分在AsyncTask中。 这是我的代码:

public class ListaActivity extends ActionBarActivity {

    private List<String> mList = new ArrayList<>();
    private ListView mListView;
    private ListAdapter mAdapter;

    public Elements job;

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

        mListView = (ListView) findViewById(R.id.list);

        new NewThread().execute();
        mAdapter = new ListAdapter(this, mList);
        mListView.setAdapter(mAdapter);
    }

    public class NewThread extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... arg) {

            Document doc;
            try {
                doc = (Document) Jsoup.connect("http://www.somewebsite.com")
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();

                title = doc.select("h3.something-to-extract a[href]");

                for (Element titles : title) {
                    mList.add(titles.text()+"\n");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
}

IMO是JSOUP的一部分,因为当我擦除od doInBackground所有内容并放入其中时,

mList.add("Something 1");
mList.add("Something 2");

然后就可以了。 请以某种方式帮助我。

编辑:我想从这个html片段解析数据:

<h2 class="title">
      <a href="/jstpl/london/11697582"  
               title="You just have to wait" class="titles">
                    Nothing else to say
       </a>

我想将“ Nothing else to say ”存储到mList ,例如我的html代码中存在的其他标题。 单独的解析部分也很好。

您必须在适配器上调用notifyDataSetChanged

在提供给适配器的列表中反映更改。 要做到这一点 -

在您的NewThread重写onPostExecute并调用mAdapter.notifyDataSetChanged()

        @Override
        protected void onPostExecute(String result) {
            mAdapter.notifyDataSetChanged();
        }  

注意: onPostExecute在主UI线程而非NewThread上运行,而doInBackgroundNewThread内部运行。 并且在后台线程完成处理后调用onPostExecute 现在,由于我们已经用新项目更新了列表。 我们将通知适配器在主线程上运行。 希望能帮助到你。

暂无
暂无

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

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