I have a ListView than contains a list of image created from web link (e.g. http://www...image.jpg) with the istruction:
Drawable d = LoadImageFromUrlWeb(TopTen_LinkImg);
imageTopTenView.setImageDrawable(d);
I have created a custom ArrayAdapter (both simple and optimized with “holder” same result).
The problem is that each image when appear in the display is uploaded from web and browse the page list is impossible (too slow).
There is a code that assign to ImageView the permanent image.
The code is:
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row_top_ten, null);
ImageView imageTopTenView = (ImageView)rowView.findViewById(R.id.imageTopTen);
String TopTen = (String)ArrayDatiTopTen.get(position);
String[] ArrayTopTen=TopTen.split(",");
String TopTen_LinkImg=(String)ArrayTopTen[0];
Drawable d = LoadImageFromUrlWeb(TopTen_LinkImg);
imageTopTenView.setImageDrawable(d);
return rowView;
}
Perhaps the solution is populate the listView using programmatically code:
ListView listView=(ListView) findViewById(R.id.listView);
...
listView.addView(...)
...
SOLVED
I have solved creating an Drawable array and filling this array with the image before use in ArrayAdapter
// Define:
Drawable imageCache[]=new Drawable[100];
then:
//loop to popolate array
imageCache[ct]=LoadImageFromUrlWeb(Link);
In the ArrayList I use:
...
imageTopTenView.setImageDrawable(imageCache[position]);
return rowView;
...
From url string to drawable:
private Drawable LoadImageFromUrlWeb(String url)
{
try
{
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
Log.w("LoadImageFromUrlWeb",e.toString());
return null;
}
}
Brett’s answer is only half the solution, yes image downloading should be done asynchronously but you’ll end up repeatedly downloading the same image over and over again every time you scroll the listview due to the optimization of the listview.
It reuses views so even if you downloaded an image and set it, if you scroll down several items that view will be reused and the image will have to be downloaded again when you scroll back up.
To prevent this you will need image caching too. See this post on the android developer blog.
Happily enough the code on the blog provides both asynchronous image downloading and image caching. Source code can be gotten from here
(Note: You’ll need to make a slight change to the source code)
Change Line 58 from
to