2015-05-14 56 views
0

我需要一些建議,因爲這件事讓我有足夠的時間因缺乏知識而對自己生氣......我嘗試製作由JSOUP提取的數據填充的ListView。 JSOUP部分在AsyncTask中。這裏是我的代碼:Android-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代碼存在。解析部分本身也很好。

+0

您能否提供您正試圖提取的標題的HTML樣本? –

+0

我認爲問題在於你沒有在'mAdapter'上調用'notifyDataSetChanged'。我發佈了下面的答案.. –

回答

1

你必須調用notifyDataSetChanged在適配器

反映提供的適配器列表中的變化。要做到這一點 -

覆蓋onPostExecuteNewThread並呼籲mAdapter.notifyDataSetChanged()

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

注:onPostExecute主UI線程上運行,而不是你的NewThread,那裏的doInBackground運行您NewThread內。當後臺線程完成處理時調用onPostExecute。現在我們已經用新項目更新了列表。我們將通知在主線程上運行的適配器。希望能幫助到你。

+0

我自己想通了,我的適配器不知道列表更改,但感謝告訴我如何通知它:)謝謝你的一切! – Edmundo

+0

我很高興幫助!祝你今天愉快 :)) –

相關問題