I am working on a image downloader , which is a async downloader. I call it whenever need to display the image on the internet
Image async downloader (Input are the target imageview, image url)
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
public InputStream input;
public ImageView view;
public String imageURL;
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
imageURL = (String) params[1];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
view.setImageBitmap(result);
view.setBackgroundResource(android.R.color.transparent);
view.getBackground().setAlpha(255);
}
}
}
And the structure of my app is a tabhost , when I switch to a particular tab e.g. at the section 4 , there is a gridview and it will trigger the imageloader asynctask
The fragment:
gridView.setAdapter(new GalleryAdapter(getActivity() , images));
The adapter:
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<GalleryImage> images;
// Constructor
public GalleryAdapter(Context c, ArrayList<GalleryImage> _images) {
mContext = c;
images = _images;
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object getItem(int position) {
return images.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if( convertView == null ){
convertView = (ImageView)new ImageView(mContext);
int size = (int)(Utility.getScreenWidth(mContext) / 3) - 1;
AbsListView.LayoutParams params = new AbsListView.LayoutParams(size, size);
convertView.setLayoutParams(params);
convertView.setBackgroundResource(android.R.color.darker_gray);
convertView.getBackground().setAlpha(204); // = 0.8 alpha
}
new ImageLoader().execute(convertView,images.get(position).thumbUrl);
return convertView;
}
}
I would like to know are there any way to cancel the downloading task when I change the tab? (Since the user leave the tab before all the download is finish , so it is unnecessary to download anymore)
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
In your case, there is no loop in your doInBackground() code. In fact it would be better if you turn it into a loop by reading the response stream buffered. This would be more performant and enable you to call isCancelled() in the loop.
Example: Use ByteArrayOutputStream to read bytes in chunks and check isCancelled() periodically in the loop.
protected Bitmap doInBackground(Object... params) {
try {
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
input = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteChunk = new byte[4096];
int n;
while ( (n = input.read(byteChunk)) > 0 ) {
if(isCancelled()) {
return null;
}
baos.write(byteChunk, 0, n);
}
Bitmap myBitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Of course you should keep a reference to your AsyncTask object to be able to call cancel method on it.
private ImageLoader loader;
...
...
loader = new ImageLoader();
loader.execute();
...
...
loader.cancel()
Related
I am working on a tabhost with 2 fragment,
the first one is a main page, the other is setting page
For the first fragment, there are a image view as well as a listview with imageviews on it
Those images are get from the internet, that is doing some asynctask, then get the link,
and calling another asynctask to download image and set it as bitmap
I found a problem , when I am at main page, after I finish the asynctask and get the links, I switch to setting page, when I go back main page again, the imageview are not update, only when I go to setting page and go back main page again , it update. How to fix it? thanks
ImageLoader
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
private InputStream input;
private ImageView view;
private String imageURL;
private String type;
private MyApp gs;
private Context ctx;
public ImageLoader(Activity _ctx,String _type){
ctx = _ctx;
gs = (MyApp) _ctx.getApplication();
type = _type;
}
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
//handle Chinese characters in file name
String[] imgUrlArray = ((String) params[1]).split("/");
String fileName = imgUrlArray[imgUrlArray.length - 1];
String newfileName = URLEncoder.encode(fileName,"utf-8");
imageURL = ((String) params[1]).replace(fileName, newfileName);
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
view.setImageBitmap(result);
if (type.equals("video"))
gs.setVideoImg(result);
else if (type.equals("latestPub"))
gs.setlatestPubImg(result);
else if (type.equals("book"))
gs.addBookImgList(result);
else if (type.equals("poster"))
gs.addPosterList(result);
else if (type.equals("other"))
gs.addOtherList(result);
} else if (type.equals("book")){
gs.addBookImgList(BitmapFactory.decodeResource(ctx.getResources(),R.drawable.ic_launcher));
} else if (type.equals("poster")){
gs.addPosterList(BitmapFactory.decodeResource(ctx.getResources(),R.drawable.ic_launcher));
} else if (type.equals("other")){
gs.addOtherList(BitmapFactory.decodeResource(ctx.getResources(),R.drawable.ic_launcher));
}
}
}
In your TabActivity class set OnTabChangedListener like this:
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (getCurrentActivity() instanceof main) {
((yourTabActivity) getCurrentActivity()).yourUpdateMethod();
}
}
}
and write yourUpdateMethod() in main class to update imaeg with asyncTask.
I'm trying to handle an image loading at the background.
Now, I've look at the next link - here
And I've got few things I don't understand -
1) I've made the next CursorAdapter for the listview items-
public class ChatCursorAdapter extends CursorAdapter implements OnClickListener {
public ChatCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public int getCount() {
return getCursor() == null ? 0 : super.getCount();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int _position) {
Cursor cursor = (Cursor) getItem(_position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
String sender = cursor.getString(2);
SharedPreferences userPref = PreferenceManager
.getDefaultSharedPreferences(MainChat.this);
String saveUser = userPref.getString("user", "");
if (saveUser.equalsIgnoreCase(sender)){
return 0;
}else{
return 1;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
holder = (ViewHolder) view.getTag();
holder.mesg.setText(getSmiledText(MainChat.this,msg));
holder.mesg2.setText(getSmiledText(MainChat.this,msg2));
holder.myImage.setTag(picPath);
holder.myImage.setImageBitmap(setImageToImageView(picPath));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View itemLayout = null;
switch(getItemViewType(cursor)){
case 0:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item1,parent, false);
break;
case 1:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item13, parent,false);
break;
}
itemLayout.setTag(holder);
holder.mesg = (TextView) itemLayout.findViewById(R.id.text_start);
holder.mesg2 = (TextView) itemLayout.findViewById(R.id.text_end);
holder.myImage = (ImageView) itemLayout.findViewById(R.id.imageView_msgpic);
return itemLayout;
}
Now i wnat to use the info from the link.
But i don't understand - What i need to pass into the and what to AsyncTask leave at CursorAdapter?
Also the sample code uses -
.execute(holder);
Can't I call to the AsyncTask like this -
new AsyncTask().execute();
And how and where should i call the AsyncTask, I don't understand it?
Thanks for any kind of help
You could always use an external lib like Universal-Image-Loader or Picasso to achieve what you are trying to do =)
Take a look at AsyncTask. You must Override doInBackground method. You may define a constructor to supply view in which you want to put downloaded image.
public class ImageDownloader extends AsyncTask<String, Void, List<Bitmap>> {
private ImageView ivImageHolder;
private Context context;
public ImageDownloader(Context context, ImageView imageHolder) {
this.ivImageHolder = imageHolder;
this.context = context;
}
...
#Override
protected List<Bitmap> doInBackground(String... params) {
//This happens in background
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (String url : params) {
Bitmap bitmap = DownloadImage(url);
bitmaps.add(bitmap);
}
return bitmaps;
}
....
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
...
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
#Override
protected void onPostExecute(List<Bitmap> bitmaps) {
super.onPostExecute(bitmaps);
for (int i = 0; i < bitmaps.size(); i++) {
final Bitmap bitmap = bitmaps.get(i);
ivImageHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new ImageViewActivity(context, bitmap).show();
}
});
// iv.setImageBitmap(bitmap);
ivImageHolder.setImageBitmap(bitmap);
ivImageHolder.setVisibility(ImageView.VISIBLE);
}
}
if you write your asyntask method I can say how can you use it, If it need to string value
you can use like this:
new your_async(context).execute(url) ;
But in my advice : you should use lazyadapter to use bitmaps on listview because there is a mermory issue if you do not pay attention properties of images.
here is link : stackoverfow
I am filling a GridView with my facebook friends' photo.
When I use my account of tester with few friends my application works good. But when I use my main account and I scroll quickly my application I get This error:
AndroidRuntime(6131): java.util.concurrent.RejectedExecutionException: Task android.os.AsyncTask$3#42230f20 rejected from java.util.concurrent.ThreadPoolExecutor#4206af70[Running, pool size = 128, active threads = 128, queued tasks = 10, completed tasks = 61]
otherwise
If i scroll a lot i get this error:
java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299)
Caused by: java.lang.NullPointerException at it.alfonso.utils.GetImageFromUrlAsyncTask.downloadImage(GetImageFromUrlAsyncTask.java:62)
if (facebookAdapter == null) {
facebookAdapter = new ImageAdapterFacebook(this, facebookResponses);
gridview.setAdapter(facebookAdapter);
}
else {
gridview.setAdapter(facebookAdapter);
}
My adapeter for my GridView
public class ImageAdapterFacebook extends BaseAdapter {
private Context mContext;
private FacebookResponses facebookFrinds;
public ImageAdapterFacebook(Context c, FacebookResponses facebookFrinds) {
mContext = c;
this.facebookFrinds = facebookFrinds;
}
public int getCount() {
return facebookFrinds == null ? 0 : facebookFrinds.getData().length;
}
public Object getItem(int position) {
return facebookFrinds == null ? null
: facebookFrinds.getData()[position];
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View amico, ViewGroup parent) {
final ImmageViewHolder viewHolder;
if (amico == null) { // if it's not recycled, initialize some attributes
LayoutInflater li = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
amico = li.inflate(R.layout.details_img_facebook_user, parent,
false);
viewHolder = new ImmageViewHolder();
viewHolder.userImage = (ImageView) amico
.findViewById(R.id.userLikesimg);
amico.setTag(viewHolder);
} else {
viewHolder = (ImmageViewHolder) amico.getTag();
}
if (facebookFrinds != null) {
viewHolder.userImage.setImageResource(R.drawable.image_loader);
String imgUserurl = facebookFrinds.getData()[position]
.getPic_square();
// Create an object for subclass of AsyncTask
GetImageFromUrlAsyncTask task = new GetImageFromUrlAsyncTask(
mContext, new DownloadImageLister() {
#Override
public void onDownloadImageSucces(Bitmap immagine) {
viewHolder.userImage.setImageBitmap(immagine);
}
#Override
public void onDownloadImageFail() {
System.out.print("errore");
}
});
task.execute(imgUserurl);
}
return amico;
}
public class ImmageViewHolder {
ImageView userImage;
}
}
My AsyncTask
public class GetImageFromUrlAsyncTask extends AsyncTask<String, Void, Bitmap> {
private Context contesto;
private DownloadImageLister listenerImage;
public GetImageFromUrlAsyncTask(Context context,
DownloadImageLister listener) {
contesto = context;
listenerImage = listener;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null ) {
listenerImage.onDownloadImageSucces(result);
}
if (result == null ) {
listenerImage.onDownloadImageFail();
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
Since you are performing so many requests for each image load your app is crashing. You could use the Volley Android library and its NetworkImageView. This is what several Google apps are using for async image loading and http requests. There is a good tutorial explaining how to use it here: http://www.captechconsulting.com/blog/clinton-teegarden/android-volley-library-tutorial.
Hope that helps!
I have been reading through a lot of answers of questions that are similar to mine, but still having problem fixing my issue. I have a project that is an RSS Reader that loads in images in the background with an AsyncTask class. The program works, except if the user scrolls quickly then the images sometimes do not load in my rows. They never load in the incorrect spot, it just seems like they are skipped if the user scrolls quickly. Also, on start-up, only 2 or 1 of the images in my listview load out of the 4 rows that the user can see.
I know the problem has something to do with the WeakReference object that I use, but I am not sure how to implement it in a better way...
This is my RssListAdapter, which contains my Async class as well.
public class RssListAdapter extends ArrayAdapter<JSONObject>
{
TextView textView;
ImageView imageView;
JSONObject jsonImageText;
ProgressDialog progressDialog;
Activity activity2;
View rowView;
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts)
{
super(activity, 0, imageAndTexts);
activity2 = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = (View) inflater
.inflate(R.layout.image_text_layout, null);
jsonImageText = getItem(position);
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// The next section we update at runtime the text - as provided by the
// JSON from our REST call
// //////////////////////////////////////////////////////////////////////////////////////////////////
textView = (TextView) rowView.findViewById(R.id.job_text);
imageView = (ImageView) rowView.findViewById(R.id.feed_image);
BitmapDownloaderTask task = new BitmapDownloaderTask();
Spanned text;
try
{
text = (Spanned) jsonImageText.get("text");
textView.setText(text);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
task.execute();
return rowView;
}
public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap>
{
private String url;
private RssListAdapter adapter;
private WeakReference<ImageView> imageViewReference = null;
#Override
// Actual download method, run in the task thread
protected Bitmap doInBackground(String... params)
{
imageViewReference = new WeakReference<ImageView>(imageView);
Bitmap img = null;
try
{
if (jsonImageText.get("imageLink") != null)
{
System.out.println("XXXX Link found!");
String url = (String) jsonImageText.get("imageLink");
URL feedImage = new URL(url);
HttpURLConnection conn = (HttpURLConnection) feedImage
.openConnection();
InputStream is = conn.getInputStream();
img = BitmapFactory.decodeStream(is);
}
}
catch (MalformedURLException e)
{
// handle exception here - in case of invalid URL being parsed
// from the RSS feed item
}
catch (IOException e)
{
// handle exception here - maybe no access to web
}
catch (JSONException e)
{
// textView.setText("JSON Exception");
}
return img;
}
#Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Bitmap bitmap)
{
if (isCancelled())
{
bitmap = null;
}
if (imageViewReference != null)
{
ImageView imageView = imageViewReference.get();
if (imageView != null)
{
imageView.setImageBitmap(bitmap);
}
}
}
#Override
// Before images are loaded
protected void onPreExecute()
{
if (imageViewReference == null)
{
imageView.setImageResource(R.drawable.stub);
}
}
}
}
You should check the official Android "Displaying Bitmaps Efficiently" tutorial on how to load and display bitmaps efficiently. It comes with a ready to use piece of code.
i want to display images from mysql server(testing in localhost) using imageurl,i have images in a filder on my server,in an android client app as gridview along with text.how do i use imageurl in my code?
mymainmenu.java
public class MainMenu extends Activity {
GridView gridView;
static final String[] MOBILE_OS = new String[] {
"Android", "iOS","Windows", "Blackberry" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu_list);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.grid_item_label))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
my imageadapter.java:
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from list.xml
gridView = inflater.inflate(R.layout.list, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mobileValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String mobile = mobileValues[position];
if (mobile.equals("Windows")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("iOS")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("Blackberry")) {
imageView.setImageResource(R.drawable.imggrid);
} else {
imageView.setImageResource(R.drawable.imggrid);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
I dnt know how to use the following in my code:
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
img.setImageBitmap(bitmap);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Put the image downloading code in a AsyncTask. Here is the explanation.
Execute one instance of asynctask in your getView method, i.e to fetch one image everytime.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mImageView;
public void setImageView(ImageView img) {
mImageView = img;
}
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Call task.setImageView(yourImageViewinGrid) before executing your AsyncTask to let it know where to set the image after downloading.
To get the image, you have to do something like :
URL new_url = new URL("your url");
Bitmap image_bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); ImageView image_view = new ImageView(this);
image_view.setImageBitmap(image_bitmap);
Anyway, it's better to download the image as background task. What I actually do is to create a custom view with one private inner class that extend AsyncTask to download the image for you.
I dnt know how to use the following in my code:
that code will download the image for you, you can place in separate thread either AsyncTask or Thread and set the downloaded image in the imageview... simple as that. There are so many example on the web you can google it out
EIDTED
code to download the image
public class AsyncFetchImage extends AsyncTask<String, Void, Bitmap>{
private WeakReference<ImageView> imageReference;
// private WeakReference<Dialog> dialogReferance;
public AsyncFetchImage(ImageView imageview) {
imageReference = new WeakReference<ImageView>(imageview);
// dialogReferance = new WeakReference<Dialog>(dialog);
}
#Override
protected Bitmap doInBackground(String... s) {
return downloadImage(s[0]);
}
private Bitmap downloadImage(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Nixit");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = null;
try{
is = entity.getContent();
final Bitmap bit = BitmapFactory.decodeStream(is);
return bit;
}finally{
if(is != null)
is.close();
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally{
if(client != null){
client.close();
}
}
Log.i("Image Fetch","Image Fetch Complete");
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
if(isCancelled()){
result = null;
}
if(imageReference != null){
ImageView imageView = imageReference.get();
// Dialog di = dialogReferance.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// di.show();
}
}
}
}
How to use:-
imageView = (ImageView)dialog.findViewById(R.id.imageView1);
AsyncFetchImage fetchImage = new AsyncFetchImage(imageView);
fetchImage.execute(url);
You can use this in getview method of adapter
Hope that help