2013-04-23 93 views
0

我想解析一個網站使用Jsoup,把我得到的信息和填充ListView。該HTML看起來像這樣:使用Jsoup填充ListView

<ul class="list_view"> 
    <li> 
    <a href="/username/" > 
     <table class="pinner"> 
     <tbody> 
      <tr> 
      <td class="first_td"> 
       <img src="http://myimgurl.com/img.jpg">           
      </td> 
      <td> 
       <span class="user_name">User Name</span> 
      </td> 
      </tr> 
     </tbody> 
     </table> 
    </a> 
    </li> 
</ul> 

所以,從這個HTML,我需要從一個標籤獲得href,也是span.user_name文本。我需要把這兩個元素都存儲在一個HashMap(我認爲??)現在,我有這樣的AsyncTask像這樣(但我不認爲我這樣做是正確的方式):

private class MyTask extends AsyncTask<Void, Void, List<HashMap<String, String>>> { 

    @Override 
    protected List<HashMap<String, String>> doInBackground(Void... params) { 

     List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map = new HashMap<String, String>(); 
     try { 
      Document doc = Jsoup.connect("http://myurl.com").get(); 
      Elements formalNames = doc.select("li a table tbody tr td span.user_name"); 
      Elements userNames = doc.select("li a"); 

      for (Element formalName : formalNames) { 
       map.put("col_1", formalName.text()); 
       fillMaps.add(map); 

       System.out.println(formalName.text()); 

      } 
      for (Element userName : userNames) { 
       map.put("col_2", userName.attr("href").toString()); 
       fillMaps.add(map); 

       System.out.println(userName.attr("href").toString()); 
      } 

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

    } 

    @Override 
    protected void onPostExecute(List<HashMap<String, String>> result) { 

     String[] from = new String[] {"col_1", "col_2"}; 
     int[] to = new int[] { R.id.text1, R.id.text2 }; 
     ListView _listview = (ListView)findViewById(R.id.listView1); 

     SimpleAdapter _adapter = new SimpleAdapter(FriendsActivity.this, fillMaps, R.layout.friends, from, to); 
     _listview.setAdapter(_adapter); 
    } 
} 

這成功地打印出我想要的信息,但它不填充ListView。我已經嘗試重新安排等,但仍然沒有運氣。我會非常感激任何幫助。

回答

0

在SimpleAdapter類中檢查getView()。 getView()返回的視圖應正確顯示每個項目。

你可以叫_adapter.notifyDataSetChanged()時,該過程後

更新

好,我想我發現ü可能引用的例子。 問題是,您一次又一次地使用相同的HashMap。 如果您一次又一次地將任何字符串放在任何鍵(「col_1」或「col_2」)上,它只會保存最後一個字符串。 因此,當你在屏幕上顯示它時(在onPostExecute之後),所有視圖都會顯示最後一個formalName和userName,因爲你列表中添加的所有HashMap都只保存最後一個(它們實際上是同一個HashMap) 。

我建議你每次在fillMaps中添加新的HashMap。

+0

感謝您的回覆@tjPark。我的代碼中沒有getView()。也許這是問題的一部分?你有沒有我可以如何實現這個的例子? – Shan 2013-04-24 03:00:30

+0

@Shan我的回覆可能是錯誤的,現在我看到你的構造函數有點不同了..但是,本教程非常適合listview:[http://www.vogella.com/articles/AndroidListView/article.html](http ://www.vogella.com/articles/AndroidListView/article.html) – tjPark 2013-04-24 13:54:11

+0

我從List更改爲Map,並且它現在填充ListView,但它只是一次又一次地添加最後一組col_1,col_2。 – Shan 2013-04-25 00:18:37