How to apply this code in AsyncTask in Android? - java

I have a code that decodes an image from a filepath, however, it takes up too much space and processing in the main thread. I have no idea how to adapt this into an AsyncTask class.
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
SetBitmapOptions(bitmapOptions);
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
viewImage.setImageBitmap(bitmap);
I wanted to use the code found here in Android Developer
http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
Code
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
I have no idea what resId is and how to pass my bitmap variable to it

You can pass parameters through the constructor in the Async_BitmapWorkerTask class. You may want to read up on simpler AsyncTask Examples such as this example.
someMethod() {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
SetBitmapOptions(bitmapOptions);
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
// Run the AsyncTask with the bitMap and imageview as a parameters
new Async_BitmapWorkerTask(bitmap, imageView).execute();
}
class Async_BitmapWorkerTask extends AsyncTask<Integer, Void, String> {
private final Bitmap bitmap;
private final ImageView imageView;
private int data = 0;
// Constructor
public Async_BitmapWorkerTask(Bitmap bitmap, ImageView imageView) {
this.bitmap = bitmap;
this.imageView = imageView;
}
// Compress and Decode image in background.
#Override
protected String doInBackground(Integer... params) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
return image_str;
}
// This method is run on the UI thread
#Override
protected void onPostExecute(String string) {
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitMap);
}
}
}

Use this :
class LoadImage extends AsyncTask<Object, Void, Bitmap>{
private ImageView imv;
private String path;
public LoadImage(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString();
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (!imv.getTag().toString().equals(path)) {
/* The path is not same. This means that this
image view is handled by some other async task.
We don't do anything and return. */
return;
}
if(result != null && imv != null){
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
imv.setVisibility(View.GONE);
}
}
}

Related

Generating thumbnail for videos in ImageView at a given position

The below code is working good, its generating image thumbnail for the video from the given url, but i want to know, is it possible to generate video thumbnail at suppose 100 milliseconds because by default its generating thumbnail at the beginning position so if in beginning the video screen is black then the thumbnail is also showing black so its looking quite odd. So is there any possibility to get the thumbnail by skipping some milliseconds.
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String path;
public DownloadImage(ImageView bmImage, String path) {
this.bmImage = (ImageView ) bmImage;
this.path=path;
}
protected Bitmap doInBackground(String... urls) {
Bitmap myBitmap = null;
MediaMetadataRetriever mMRetriever = null;
try {
mMRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mMRetriever.setDataSource(path, new HashMap<String, String>());
else
mMRetriever.setDataSource(path);
myBitmap = mMRetriever.getFrameAtTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mMRetriever != null) {
mMRetriever.release();
}
}
return myBitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
You can use other overloaded methods of MediaMetadataRetriever to get frame of a particular time.
public Bitmap getFrameAtTime(long timeUs, int option) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime(long timeUs) {
throw new RuntimeException("Stub!");
}
public Bitmap getFrameAtTime() {
throw new RuntimeException("Stub!");
}

android out of memory error after multiple reloads

hey guys having a problem after reloading an activity multiple times i get an out of memory exception and crashes out of the app i am using the developer google documentation example to load multiple images from what i see i have to recycle the bitmap once i am done with it but i am a bit unsure where to do this considering i have multiple bitmaps and calling the bitmap from an external class
Here is my load bitmap class
public class bitmapHTTP{
Context ctx;
private LruCache<String, Bitmap> mMemoryCache;
int iv;
public bitmapHTTP(Context c){
ctx = c;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if(getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
public void loadBitmap(String resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
iv = imageView.getWidth();
Bitmap bitmap = getBitmapFromMemCache(imageKey);
if(bitmap != null) {
imageView.setImageBitmap(bitmap);
}else{
if(cancelPotentialWork(imageKey, imageView)){
Bitmap loading = decodeSampledBitmapFromResource(ctx.getResources(), R.drawable.whiteseetrough, imageView.getWidth(), imageView.getWidth());
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
AsyncDrawable asyncDrawable = new AsyncDrawable(ctx.getResources(), loading, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(resId);
}
}
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String data = null;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
data = params[0];
final BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap;
if(data.equals("null")){
bitmap = decodeSampledBitmapFromResource(ctx.getResources(), R.drawable.whiteseetrough, iv, iv);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}else{
bitmap = getBitmapFromMemCache(data);
if(bitmap == null){
// Process as normal
try {
URL url = new URL(data);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
options.inSampleSize = calculateInSampleSize(options, iv, iv);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(input, null, options);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
}
return bitmap;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask =
getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask && imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap,
BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
public static boolean cancelPotentialWork(String data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.data;
// If bitmapData is not yet set or it differs from the new data
if(bitmapData == null || bitmapData != data) {
// Cancel previous task
bitmapWorkerTask.cancel(true);
} else {
// The same work is already in progress
return false;
}
}
// No task associated with the ImageView, or an existing task was cancelled
return true;
}
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
}
this is how i call the bitmap to load to an imageView
bitmapHTTP getBitmap = new bitmapHTTP(this);
getBitmap.loadBitmap(imageUrl, 1), imageView1);
getBitmap.loadBitmap(imageUrl, 1), imageView2);
getBitmap.loadBitmap(imageUrl, 1), imageView3);
Thats a lot of code. Quickly I would ask: Are you recycling your bitmaps after not needing them? Bitmaps need to be recycled and RAM released especially when loading them via loops and the like and keeping references to them.
Check your code to make sure you recycling properly. I didn't see anything of the kind (releasing the reference is not enough if you want to do a low of bitmaping).
Also, keep in mind that you need to make sure your bitmaps are loaded in properly in available memory and resized so that they don't kill the memory. I believe you are doing it somewhere in there.

Memory Leak with Bitmaps and Custom Image Views (Android)

In my Android app, I am using a custom ImageView class (Banner) to display images pulled from Facebook Events. While running the app, I notice that there is a large heap size (120 MB) while running the app. I used MAT and I think I've narrowed it down to byte[] and then finally to ImageView. Please check the pictures below to see how I came to this conclusion.
Now, I've read similar posts and I tried recycling my bitmap, using WeakReferences, creating a cache, but nothing seems to be reducing the memory size. However, recycling my bitmap threw me an error which said that I can't use a recycled bitmap (I feel like that may be a hint because it's keeping my bitmap in memory?).
The app isn't running slowly on my phone (It even only says a CPU usage of 1.5% even though the memory is on average 100 MB). I will post my Banner subclass and how I download the images to see if anyone can help me.
Banner.java:
public class Banner extends ImageView {
public Banner(Context context) {
super(context);
}
public Banner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Banner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = 400;
if (getDrawable() != null && getDrawable().getIntrinsicWidth() != 0){
height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
if (height < 500)
height = 700;
}
setMeasuredDimension(width, height);
setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
}
public void onDestroy(){
Drawable drawable = this.getDrawable();
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
bitmap.recycle();
}
this.setImageBitmap(null);
}
}
BannerLoader.java:
public class BannerLoader{
private String url;
private WeakReference<ImageView> cover;
private LruCache<String, WeakReference<Bitmap>> mMemoryCache;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
public BannerLoader(String cover_url, WeakReference<ImageView> cover, Drawable defaultDrawable) {
this.url = cover_url;
this.cover = cover;
cover.get().setBackground(defaultDrawable);
mMemoryCache = new LruCache<String, WeakReference<Bitmap>>(cacheSize) {
#Override
protected int sizeOf(String key, WeakReference<Bitmap> bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.get().getByteCount() / 1024;
}
};
new DownloadImage().execute();
}
public void addBitmapToMemoryCache(String key, WeakReference<Bitmap> bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public WeakReference<Bitmap> getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
class DownloadImage extends AsyncTask<Void, Void, WeakReference<Bitmap>>{
protected WeakReference<Bitmap> doInBackground(Void... params){
try {
final WeakReference<Bitmap> cachedBitmap = getBitmapFromMemCache(url);
if (cachedBitmap != null){
return cachedBitmap;
} else{
URL pictureURL = new URL(url);
HttpGet httpRequest = null;
httpRequest = new HttpGet(pictureURL.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
WeakReference<Bitmap> bitmap = new WeakReference<Bitmap>(BitmapFactory.decodeStream(input));
addBitmapToMemoryCache(url, bitmap);
return bitmap;
}
} catch(Exception ex){
ex.printStackTrace();
}
return null;
}
public void onPostExecute(WeakReference<Bitmap> image){
if (image != null && cover.get() != null){
cover.get().setImageBitmap(image.get());
}
}
}
}
So, as an example, I download an image like this:
new BannerLoader(tempEvent.getCover_url(), new WeakReference<ImageView>(thumb_image), context.getResources().getDrawable(R.drawable.placeholder));
Thanks for the help!

pause one class and start another class ans vice versa in android

im beginner in android.
i have 2 class in 2 .java file. first:Mainacivity and second:ImageDownloader.
imagedownloader downloads bitmap with it's function getBitmapFromURL(String url), i give string to this function and it works well, but i wanna download more than 1 bitmap one after another.
my main activity:
public class MainActivity extends Activity implements View.OnClickListener
{
private Button download, downloadBG, save;
private ImageView img;
private ProgressBar pb;
private EditText etUrl;
private TextView percent;
private ImageDownloader mDownloader;
private static Bitmap bmp;
private FileOutputStream fos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*--- initialize layout compinents ---*/
private void initViews() {
download = (Button) findViewById(R.id.btnDownload);
downloadBG = (Button) findViewById(R.id.btnDownloadBackground);
save = (Button) findViewById(R.id.btnSave);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
download.setOnClickListener(this);
downloadBG.setOnClickListener(this);
save.setOnClickListener(this);
save.setEnabled(false);
img = (ImageView) findViewById(R.id.image);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
etUrl = (EditText) findViewById(R.id.etUrl);
percent = (TextView) findViewById(R.id.tvPercent);
percent.setVisibility(View.INVISIBLE);
}
#Override
public void onClick(View v) {
/*--- determine which button was clicked ---*/
switch (v.getId())
{
case R.id.btnDownload:
{
/*--- we use trim() to remove whitespaces which could be entered ---*/
bmp = ImageDownloader.getBitmapFromURL(URLbuilder(0, 0, 0));
img.setImageBitmap(bmp);
save.setEnabled(true);
break;
}
case R.id.btnDownloadBackground:
for(int a = 0 ; a < 4 ; a++)
{
/*--- check whether there is some Text entered ---*/
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(URLbuilder(a, a, a), a,pb, save, img, percent, MainActivity.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
MainActivity.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
break;
}
}
public String URLbuilder(int x , int y , int z)
{
String myurl = "http://khm0.google.com/kh/v=132&hl=EN&x={0}&y={1}&z={2}&s=";
String.format(myurl, x,y,z);
return String.format(myurl, x,y,z);
}
}
if i click on DownloadBackground button it should download 4 bitmap from it's url.
i know that each download take some time but i cannot stop this function untill first bitmap download.
my imagedownloader:
public class ImageDownloader extends AsyncTask<Void, Integer, Void>
{
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
FileOutputStream fos;
int Counter = 0;
/*--- constructor ---*/
public ImageDownloader(String url,int counter, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
//this.Counter = Integer.toString(counter);
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
#Override
protected void onPreExecute() {
progress = 0;
pb.setVisibility(View.VISIBLE);
percent.setVisibility(View.VISIBLE);
Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
while (progress < 100) {
progress += 1;
publishProgress(progress);
/*--- an image download usually happens very fast so you would not notice
* how the ProgressBar jumps from 0 to 100 percent. You can use the method below
* to visually "slow down" the download and see the progress bein updated ---*/
//SystemClock.sleep(200);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
saveImageToSD();
save.setEnabled(true);
Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
public static Bitmap getBitmapFromURL(String link)
{
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}
private void saveImageToSD()
{
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDownloadedImage" + Integer.toString(Counter) + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Counter++;
}
i need to stop for loop in onclick method in main activity until each image download. i did every things that i knew but every time it crashed.
later i have to put image downloader in a thread but i dont know how to stop thread for a while.
pls help me. ty
You can use Handler
new Handler().postDelayed(new Runnable(){
public void run() {
//some job to do delayed 3s
}}, 3000);
Hope it helps!

Call AsyncTask class with additional parameters in order to check where to show image

I am using an AsyncTask class to download images for my quiz application. This is the class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//--------------------------------------------------
}
}
The image is getting downloaded and I am putting the image inside my Question TextView like this:
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
I am giving a call to this class from my activity like this:
//image download
String imageURL = "http://cache.daylife.com/imageserve/074efG3gPV4oK/50x50.jpg";
image_downloadView.setTag(imageURL);
new DownloadImagesTask().execute(image_downloadView);
I want to pass some extra parameters in order to identify whether I am downloading the image for the question or answer TextViews.
How do I achieve this?
Thanks in advance!
P.S.: I have one question and four options in the application for every set of question.
You can pass parameters to your AsyncTask Constructor.
DownLoadImagesTask dt= new DownLoadImagesTask("hello",1); //passing string and integer value
dt.execute(image_downloadView);
In asynctask
String s;
int value;
public DownLoadImagesTask(String string, int i) {
// TODO Auto-generated constructor stub
s=string;
value=1;
}
You can change the type of your first param to an Object (Or create a custom parameter class/hash - the best option) and pass multiple items to it.
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
String param = "parameter";
MyAsyncTask task = new MyAsyncTask();
task.execute(param, imgView);
private class MyAsyncTask extends AsyncTask<Object, Void, Void> {
private String parameter;
private ImageView imgView;
#Override
protected Void doInBackground(Object... params) {
//Looping option
for (Object object : params) {
if (object instanceof String) {
this.parameter = (String) object;
//do_something
} else if (object instanceof ImageView) {
//do_something_else
}
}
//Direct access option
this.parameter = (String) params[0];
this.imgView = (ImageView) params[1];
return null;
}
}
In your case, you can pass a View
new DownloadImagesTask().execute(image_downloadView, question_resultView);
private class DownloadImagesTask extends AsyncTask<View, Void, Bitmap> {
TextView questionView = null;
ImageView imageView = null;
#Override
protected Bitmap doInBackground(View... views) {
for (View view : views) {
if (view instanceof ImageView) {
this.imageView = (ImageView) view;
} else if (view instanceof TextView) {
this.questionView = (TextView) view;
}
}
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
questionView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
}

Categories