Reputation: 421
I am trying to perform a very simple task (loading image to ImageView in the background), but can't make it to work. Any help much appreciated.
Here is what I have so far: This is how I call the class in on create in the main thread:
LoadImage newImage=new LoadImage();
newImage.execute(myImgeView);
Next I created the class:
public class LoadImage extends AsyncTask<ImageView, Void, ImageView> {
ImageView imageView;
@Override
protected ImageView doInBackground(ImageView... params) {
Log.e("myTag",": Can it see this class from where I call it? Yes it does" );
imageView.setImageResource(R.drawable.myNewImage);
return imageView;
}
}
I can't figure out how to set it up correctly. It crashes saying something like: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference.
Thanks in advance for your help.
Upvotes: 0
Views: 616
Reputation: 244
You should not use AsyncTask anymore, since it is deprecated like jesusd0897 already mentioned. If you need to load images from a remote resource (e.g. API) then Glide or other libraries do the job for you.
But for this simple case you don't need an asynchronous task. Just do it on the main thread in your Activity/Fragment etc:
imageView.setImageResource(R.drawable.myNewImage)
Upvotes: 0
Reputation: 55
AsyncTask is deprecated. For this type of operations it is recommended to use some library and make things easier: Picasso, Glide, Fresco...etc
Upvotes: 1
Reputation: 474
The problem lies in this code:
imageView.setImageResource(R.drawable.myNewImage);
The variable
imageView
can't be seen from the AsyncTask
Class, the imageView you want is inside the params
array so you can reference it with params[0]
. So replace the above code with:
ImageView imageView = params[0];
imageView.setImageResource(R.drawable.myNewImage);
return imageView;
Upvotes: 0