Android JSOUP ListView Images And Texts From HTML Tables Tutorial

In this tutorial, you will learn how to extract elements from a HTML table using JSOUP Library. JSOUP provides a very convenient API for extracting and manipulating data, using DOM, CSS, and jquery-like methods. JSOUP allows you to scrape and parse HTML from a URL, file, or string and many more. We will create a ListView on the main view and populate it with extracted HTML elements from a HTML table provided. So lets begin…

Before you proceed with this tutorial, download the latest JSOUP library from here.

Paste your downloaded Jsoup file into your project libs folder as shown on the image below.

JsoupListView_Library

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project JsoupListViewTutorial.

Application Name : JsoupListViewTutorial

Project Name : JsoupListViewTutorial

Package Name : com.androidbegin.jsouplistviewtutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.jsouplistviewtutorial;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.ListView;

public class MainActivity extends Activity {
	ListView listview;
	ListViewAdapter adapter;
	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	static String RANK = "rank";
	static String COUNTRY = "country";
	static String POPULATION = "population";
	static String FLAG = "flag";
	// URL Address
	String url = "https://www.androidbegin.com/tutorial/jsouplistview.html";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from listview_main.xml
		setContentView(R.layout.listview_main);
		// Execute DownloadJSON AsyncTask
		new JsoupListView().execute();

	}

	// Title AsyncTask
	private class JsoupListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MainActivity.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Android Jsoup ListView Tutorial");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylist = new ArrayList<HashMap<String, String>>();

			try {
				// Connect to the Website URL
				Document doc = Jsoup.connect(url).get();
				// Identify Table Class "worldpopulation"
				for (Element table : doc.select("table[class=worldpopulation]")) {
					
					// Identify all the table row's(tr)
					for (Element row : table.select("tr:gt(0)")) {
						HashMap<String, String> map = new HashMap<String, String>();
						
						// Identify all the table cell's(td)
						Elements tds = row.select("td");
						
						// Identify all img src's
						Elements imgSrc = row.select("img[src]");
						// Get only src from img src
						String imgSrcStr = imgSrc.attr("src");
						
						// Retrive Jsoup Elements
						// Get the first td
						map.put("rank", tds.get(0).text());
						// Get the second td
						map.put("country", tds.get(1).text());
						// Get the third td
						map.put("population", tds.get(2).text());
						// Get the image src links
						map.put("flag", imgSrcStr);
						// Set all extracted Jsoup Elements into the array
						arraylist.add(map);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Locate the listview in listview_main.xml
			listview = (ListView) findViewById(R.id.listview);
			// Pass the results into ListViewAdapter.java
			adapter = new ListViewAdapter(MainActivity.this, arraylist);
			// Set the adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog
			mProgressDialog.dismiss();
		}
	}

}

In this MainActivity, we have created an AsyncTask to connect to the website URL . Then we used the Jsoup selector to select the appropriate Table Rows and Table Cells. You can read more about Jsoup Selectors using this link. Then we map the captured results into an Array list and passed into the ListViewAdapter.

I’ve created a sample table for this tutorial. Visit https://www.androidbegin.com/tutorial/jsouplistview.html with any preferred Internet browser on your PC. Right click and select View Page Source. Now try to understand the structures on how a table is built.

<!doctype html>
<html>
	<head>
		<link rel="Shortcut Icon" type="image/x-icon" href="https://www.androidbegin.com/wp-content/uploads/2013/04/favicon1.png" />
		<link rel="stylesheet" type="text/css" href="https://www.androidbegin.com/tutorial/jsouplistview.css" media="screen, projection" />
			<title>Android JSOUP ListView Tutorial</title>
	</head>
		<body>
			<div class="center-align">
				<img src="https://www.androidbegin.com/wp-content/uploads/2013/08/Web-Logo364.png"/>
				<table class="worldpopulation">
					<tbody>
						<tr>
							<th>Rank</th>
							<th>Country</th>
							<th>Population</th>
							<th>Flag</th>
						</tr>
						<tr>
							<td>1</td>
							<td>China</td>
							<td>1,354,040,000</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/china.png"/></td>
						</tr>
						<tr>
							<td>2</td>
							<td>India</td>
							<td>1,210,193,422</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/india.png"/></td>
						</tr>
						<tr>
							<td>3</td>
							<td>United States</td>
							<td>315,761,000</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/unitedstates.png"/></td>
						</tr>
						<tr>
							<td>4</td>
							<td>Indonesia</td>
							<td>237,641,326</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/indonesia.png"/></td>
						</tr>
						<tr>
							<td>5</td>
							<td>Brazil</td>
							<td>193,946,886</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/brazil.png"/></td>
						</tr>
						<tr>
							<td>6</td>
							<td>Pakistan</td>
							<td>182,912,000</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/pakistan.png"/></td>
						</tr>
						<tr>
							<td>7</td>
							<td>Nigeria</td>
							<td>170,901,000</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/nigeria.png"/></td>
						</tr>
						<tr>
							<td>8</td>
							<td>Bangladesh</td>
							<td>152,518,015</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/bangladesh.png"/></td>
						</tr>
						<tr>
							<td>9</td>
							<td>Russia</td>
							<td>143,369,806</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/russia.png"/></td>
						</tr>
						<tr>
							<td>10</td>
							<td>Japan</td>
							<td>127,360,000</td>
							<td><img src="https://www.androidbegin.com/tutorial/flag/japan.png"/></td>
						</tr>
						
					</tbody>
				</table>
			</div>
		</body>
</html>

Next, create an XML graphical layout for your listview. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file listview_main.xml and paste the following code.

listview_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

Output:

Jsoup ListView Main XML

Next, create a custom listview adapter. Go to File > New > Class and name it ListViewAdapter.java. Select your package named com.androidbegin.jsouplistviewtutorial and click Finish.

Open your ListViewAdapter.java and paste the following code.

ListViewAdapter.java

package com.androidbegin.jsouplistviewtutorial;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	HashMap<String, String> resultp = new HashMap<String, String>();

	public ListViewAdapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		TextView rank;
		TextView country;
		TextView population;
		ImageView flag;

		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View itemView = inflater.inflate(R.layout.listview_item, parent, false);
		// Get the position
		resultp = data.get(position);

		// Locate the TextViews in listview_item.xml
		rank = (TextView) itemView.findViewById(R.id.rank);
		country = (TextView) itemView.findViewById(R.id.country);
		population = (TextView) itemView.findViewById(R.id.population);

		// Locate the ImageView in listview_item.xml
		flag = (ImageView) itemView.findViewById(R.id.flag);

		// Capture position and set results to the TextViews
		rank.setText(resultp.get(MainActivity.RANK));
		country.setText(resultp.get(MainActivity.COUNTRY));
		population.setText(resultp.get(MainActivity.POPULATION));
		// Capture position and set results to the ImageView
		// Passes flag images URL into ImageLoader.class
		imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
		// Capture ListView item click
		itemView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Get the position
				resultp = data.get(position);
				Intent intent = new Intent(context, SingleItemView.class);
				// Pass all data rank
				intent.putExtra("rank", resultp.get(MainActivity.RANK));
				// Pass all data country
				intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
				// Pass all data population
				intent.putExtra("population",resultp.get(MainActivity.POPULATION));
				// Pass all data flag
				intent.putExtra("flag", resultp.get(MainActivity.FLAG));
				// Start SingleItemView Class
				context.startActivity(intent);

			}
		});
		return itemView;
	}
}

In this custom listview adapter class, string arrays are passed into the ListViewAdapter and set into the TextViews and ImageViews followed by the positions. On listview item click will pass the string arrays and position to a new activity.

Next, create an XML graphical layout for your listview item. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file listview_item.xml and paste the following code.

listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ranklabel" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ranklabel" />

    <TextView
        android:id="@+id/countrylabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ranklabel"
        android:text="@string/countrylabel" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank"
        android:layout_toRightOf="@+id/countrylabel" />

    <TextView
        android:id="@+id/populationlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/countrylabel"
        android:text="@string/populationlabel" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country"
        android:layout_toRightOf="@+id/populationlabel" />

    <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:padding="1dp" />

</RelativeLayout>

Output:

Jsoup ListView Item XML

Next, create an imageloader class. Go to File > New > Class and name it ImageLoader.java. Select your package named com.androidbegin.jsouplistviewtutorialand click Finish.

Open your ImageLoader.java and paste the following code.

ImageLoader.java

package com.androidbegin.jsouplistviewtutorial;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

	MemoryCache memoryCache = new MemoryCache();
	FileCache fileCache;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	ExecutorService executorService;
	// Handler to display images in UI thread
	Handler handler = new Handler();

	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}

	final int stub_id = R.drawable.temp_img;

	public void DisplayImage(String url, ImageView imageView) {
		imageViews.put(imageView, url);
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null)
			imageView.setImageBitmap(bitmap);
		else {
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	private void queuePhoto(String url, ImageView imageView) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		executorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmap(String url) {
		File f = fileCache.getFile(url);

		Bitmap b = decodeFile(f);
		if (b != null)
			return b;

		// Download Images from the Internet
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			Utils.CopyStream(is, os);
			os.close();
			conn.disconnect();
			bitmap = decodeFile(f);
			return bitmap;
		} catch (Throwable ex) {
			ex.printStackTrace();
			if (ex instanceof OutOfMemoryError)
				memoryCache.clear();
			return null;
		}
	}

	// Decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f) {
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			FileInputStream stream1 = new FileInputStream(f);
			BitmapFactory.decodeStream(stream1, null, o);
			stream1.close();

			// Find the correct scale value. It should be the power of 2.
			// Recommended Size 512
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			FileInputStream stream2 = new FileInputStream(f);
			Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
			stream2.close();
			return bitmap;
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			try {
				if (imageViewReused(photoToLoad))
					return;
				Bitmap bmp = getBitmap(photoToLoad.url);
				memoryCache.put(photoToLoad.url, bmp);
				if (imageViewReused(photoToLoad))
					return;
				BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
				handler.post(bd);
			} catch (Throwable th) {
				th.printStackTrace();
			}
		}
	}

	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// Used to display bitmap in the UI thread
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else
				photoToLoad.imageView.setImageResource(stub_id);
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}

}

An imageloader is class that helps you download, display and cache images. By using an imageloader, images will be unloaded automatically if the device memory is low and it makes sure that the images are sized appropriately, and cached in the memory. Insert a temporary image for the imageloader to display when an image is unavailable or its still loading. For this tutorial, we have prepared a sample temporary image. Insert your downloaded sample image into your res drawable-hdpi.

Temporary Image

[wpfilebase tag=file id=85 tpl=download-button /]

Next, create a memory cache class. Go to File > New > Class and name it MemoryCache.java. Select your package named com.androidbegin.jsouplistviewtutorial and click Finish.

Open your MemoryCache.java and paste the following code.

MemoryCache.java

package com.androidbegin.jsouplistviewtutorial;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;

public class MemoryCache {

	private static final String TAG = "MemoryCache";

	// Last argument true for LRU ordering
	private Map<String, Bitmap> cache = Collections
			.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));

	// Current allocated size
	private long size = 0;

	// Max memory in bytes
	private long limit = 1000000;

	public MemoryCache() {
		// Use 25% of available heap size
		setLimit(Runtime.getRuntime().maxMemory() / 4);
	}

	public void setLimit(long new_limit) {
		limit = new_limit;
		Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
	}

	public Bitmap get(String id) {
		try {
			if (!cache.containsKey(id))
				return null;
			return cache.get(id);
		} catch (NullPointerException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public void put(String id, Bitmap bitmap) {
		try {
			if (cache.containsKey(id))
				size -= getSizeInBytes(cache.get(id));
			cache.put(id, bitmap);
			size += getSizeInBytes(bitmap);
			checkSize();
		} catch (Throwable th) {
			th.printStackTrace();
		}
	}

	private void checkSize() {
		Log.i(TAG, "cache size=" + size + " length=" + cache.size());
		if (size > limit) {
			// Least recently accessed item will be the first one iterated
			Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, Bitmap> entry = iter.next();
				size -= getSizeInBytes(entry.getValue());
				iter.remove();
				if (size <= limit)
					break;
			}
			Log.i(TAG, "Clean cache. New size " + cache.size());
		}
	}

	public void clear() {
		try {
			cache.clear();
			size = 0;
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
	}

	long getSizeInBytes(Bitmap bitmap) {
		if (bitmap == null)
			return 0;
		return bitmap.getRowBytes() * bitmap.getHeight();
	}
}

This memory cache class will limit the memory usage when loading images. Which means, the images will be removed if not shown within the content view.

Next, create a file cache class. Go to File > New > Class and name it FileCache.java. Select your package named com.androidbegin.jsouplistviewtutorial and click Finish.

Open your FileCache.java and paste the following code.

FileCache.java

package com.androidbegin.jsouplistviewtutorial;

import java.io.File;
import android.content.Context;

public class FileCache {

	private File cacheDir;

	public FileCache(Context context) {
		// Find the dir to save cached images
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"JsonParseTutorialCache");
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
	}

	public File getFile(String url) {
		String filename = String.valueOf(url.hashCode());
		// String filename = URLEncoder.encode(url);
		File f = new File(cacheDir, filename);
		return f;

	}

	public void clear() {
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}

}

This file cache class saves temporary images into the device internal storage to prevent the images to be downloaded repeatedly.

Next, create an utility class. Go to File > New > Class and name it Utils.java. Select your package named com.androidbegin.jsouplistviewtutorial and click Finish.

Open your Utils.java and paste the following code.

Utils.java

package com.androidbegin.jsouplistviewtutorial;
import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

Next, create an activity to display results. Go to File > New > Class and name it SingleItemView.java. Select your package named com.androidbegin.jsouplistviewtutorial and click Finish.

Open your SingleItemView.java and paste the following code.

SingleItemView.java

package com.androidbegin.jsouplistviewtutorial;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleItemView extends Activity {
	// Declare Variables
	String rank;
	String country;
	String population;
	String flag;
	String position;
	ImageLoader imageLoader = new ImageLoader(this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from singleitemview.xml
		setContentView(R.layout.singleitemview);

		Intent i = getIntent();
		// Get the result of rank
		rank = i.getStringExtra("rank");
		// Get the result of country
		country = i.getStringExtra("country");
		// Get the result of population
		population = i.getStringExtra("population");
		// Get the result of flag
		flag = i.getStringExtra("flag");

		// Locate the TextViews in singleitemview.xml
		TextView txtrank = (TextView) findViewById(R.id.rank);
		TextView txtcountry = (TextView) findViewById(R.id.country);
		TextView txtpopulation = (TextView) findViewById(R.id.population);

		// Locate the ImageView in singleitemview.xml
		ImageView imgflag = (ImageView) findViewById(R.id.flag);

		// Set results to the TextViews
		txtrank.setText(rank);
		txtcountry.setText(country);
		txtpopulation.setText(population);

		// Capture position and set results to the ImageView
		// Passes flag images URL into ImageLoader.class
		imageLoader.DisplayImage(flag, imgflag);
	}
}

In this activity, strings are retrieved from the ListViewAdapter by using Intent and sets into the TextViews and an image URL into ImageLoader class to load images into the ImageView.

Next, create an XML graphical layout for your SingleItemView. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file singleitemview.xml and paste the following code.

singleitemview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ranklabel" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ranklabel" />

    <TextView
        android:id="@+id/countrylabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ranklabel"
        android:text="@string/countrylabel" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank"
        android:layout_toRightOf="@+id/countrylabel" />

    <TextView
        android:id="@+id/populationlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/countrylabel"
        android:text="@string/populationlabel" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country"
        android:layout_toRightOf="@+id/populationlabel" />
    
     <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:padding="1dp" />

</RelativeLayout>

Output:

 

Jsoup ListView singleitem XML1

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Jsoup ListView Tutorial</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="ranklabel">"Rank : "</string>
    <string name="countrylabel">"Country : "</string>
    <string name="populationlabel">"Population : "</string>
</resources>

In your AndroidManifest.xml, we need to declare permissions to allow the application to write an external storage and connect to the Internet. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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=".SingleItemView" >
        </activity>
    </application>

</manifest>

Output:

Jsoup ListView sc

Source Code

[purchase_link id=”8031″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Great Tutorial...But, if i would take data like "info", "descProgram", "time" from a DOM HTML more complex like this, where i could have 20 ol data-channel: Rai 1 TG 1 Notte TG 1 Notte del 04/03/2017 01:00 iTG 1 Notte How could retrieve the data in ArrayList

Gigi Castellana

Android JSOUP ListView Images And Texts From HTML Tables Tutorial

Great Tutorial Working Wellhow can i add paragraph text instead of word. Insted of population i hv description option Thank You

Vinayak Parab

Android JSOUP ListView Images And Texts From HTML Tables Tutorial

I Want to put an image from html to a toolbar how can I do that

Christian Munch Hammervig

Android JSOUP ListView Images And Texts From HTML Tables Tutorial

sir, how I can get this information and how I must to fix the code from doInBackground function

Gia Lin

Android JSOUP ListView Images And Texts From HTML Tables Tutorial