Reputation: 3
I am trying to parse a website using Jsoup, take the info I get and populate a ListView
. The HTML looks like this:
<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>
So, from this HTML, I need to get the href
from the a tag, and also the span.user_name text. I need to take both of these elements and store them in a HashMap
(I think??) Right now, I have this in an AsyncTask
like so (but I don't think I am doing this the correct way):
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);
}
}
This successfully prints out the info I want, but it does not populate the ListView
. I am have tried rearranging, etc. but still, no luck. I would be mighty grateful for any help at all.
Upvotes: 0
Views: 838
Reputation: 308
check getView() in your SimpleAdapter class. the returned view by getView() should show one each item properly.
You can call _adapter.notifyDataSetChanged() when the process finished
updated
ok i guess i found the example u might referenced. The problem is, you are using the same HashMap again and again. if you put any String on any key("col_1" or "col_2") again and again, it will only save the last one. So when the time you show it on the screen(after onPostExecute), the all views will show the last formalName and userName, because all HashMap added on your list are saving the same last one only(they are actually the one same HashMap).
I suggest you to make new HashMap for each time you add it on the fillMaps.
Upvotes: 1