Android image didn't display to ImageView from image URL - java

I want to display image to ImageView from "http://i.imgur.com/4GLKF4Q.jpg" but The image in image URL didn't display to imageview. Can I do this?
AsyncTask
class DownloadImageTask extends AsyncTask<String, Void, byte[]> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected byte[] doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(byte[] result) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(result);
Bitmap bm = BitmapFactory.decodeStream(imageStream);
bmImage.setImageBitmap(bm);
}
}
in activity
new DownloadImageTask((ImageView) newView.findViewById(R.id.thumbnail))
.execute("http://i.imgur.com/4GLKF4Q.jpg");
The image in image URL didn't display to imageview.
in Logcat :
09-23 10:26:49.410 10591-10591/com.*** D/skia: --- SkImageDecoder::Factory returned null

Update from comment : changing image server to another one solve the issue. I guess it's a i.imgur.com issue.
You shouldn't use your own image loader task, it will leak somewhere.
Two good library exist :
- Fresco (from Facebook)
- Picasso (from Square up)
There is also UniversalImageLoader (UIL).

I would suggest you to checkout Image Management Library by Facebook that is Fresco that is pretty awesome and mature as compared to other Image Loading Library.
Fresco handles all the things caching of images with 3 Tier architecture ( BITMAP_MEMORY_CACHE, ENCODED_MEMORY_CACHE and DISK_CACHE). It also reduces OOM(Out Of Memory) issues. When image in a view goes out of screen it automatically recycles the bitmap, hence releasing the memory.

Now there is an official way to load an ImageView from a URL and that is NOT to use an ImageView.
NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.
Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.

Related

RecyclerView lags in scrolling

I have a recyclerview with cardview in it. Also having imageview, textview. I am decoding my images using Base64 decoding scheme and displaying images within the cardview.It loads the images but producing the lag effect
onBindViewHolder code
holder.iv_contestant_image.setImageBitmap(new ProcessImage().getBitmage(contestant.getContestant_image()));
ProcessImage code
byte[] decodedString = Base64.decode(strBitmap, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
Is something wrong am I doing ?
you can use any image loading libraries. Some of libraries are Picasso Glide Fresco
I do believe decoding process is not instant depending on the size of the bitmap. So, try perform decoding bitmap with AsyncTask
class BitmapWorkerTask extends AsyncTask<Void, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String base64Img;
public BitmapWorkerTask(ImageView imageView, String base64Img) {
imageViewReference = new WeakReference<ImageView>(imageView);
this.base64Img = base64Img;
}
#Override
protected Bitmap doInBackground(Void... params) {
byte[] decodedString = Base64.decode(base64Img, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
imageViewReference.get().setImageBitmap(bitmap);
}
}
Inside onBindViewHolder
new BitmapWorkerTask(holder.iv_contestant_image, stringBitmap).execute();
you can implement lazy image loading in your recycle view for fix this issue. http://blogs.innovationm.com/lazy-loading-and-memory-management-of-images-in-listview-in-android/

Duplicates picture on my android application

I have an Android application that loading some information and one picture like a blog, but sometimes I got duplicates picture, I don't know what is the problem, but sometimes it works good.
Someone here can help me ?
Here's the code below:
"endereco" is the URL of picture and "view" is the context that I pass on the class that extends activity"
public void loadImg(final View view , final String endereco){
Thread nova = new Thread()
{
public void run() {
Bitmap img = null;
try
{
URL url = new URL(endereco);
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
InputStream input = conexao.getInputStream();
img = BitmapFactory.decodeStream(input);
Log.i("Funcionou","Foto: " + endereco);
} catch (Exception ex){
Log.i("Erro",ex.toString());
}
final Bitmap imgAux = img;
handler.post(new Runnable() {
#Override
public void run() {
ImageView imageView = (ImageView) view.findViewById(R.id.txtfoto);
imageView.setImageBitmap(imgAux);
}
});
}
};
nova.start();
nova.currentThread().interrupt();
}
If you are downloading an image from a wbepage or server i wouldnt do it in a thread give it its own AsyncTask it gives you a whole load of methods that allow you to better control over what you are downloading and what to do with it after it has been downloaded.
Check out the Android dev Docs http://developer.android.com/reference/android/os/AsyncTask.html

Android Picaso - How to not cache images that are not downloaded through it?

So I am using Picaso to load some images and cache them like so:
ImageView logo = (ImageView)findViewById(R.id.image_logo);
Picasso.with(VenueDetailsActivity.this).load(url).into(logo);
However, I have other images that should not be cached. However, it seems like as soon as Picaso is running in any point in the app, then it starts caching all images no matter if I use Picaso loading on them or not.
How can I not cache certain images using Picasso?
** Does Picasso setups your app that any image loading is cached regardless of using Picasso or not?**
The method I use to download my images are:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
If you don't want Picasso to cache an image you can use .skipMemoryCache() like so:
Picasso.with(VenueDetailsActivity.this).load(url).skipMemoryCache().into(logo);
For more information you can view the documentation here

Why aren't my images downloading into ImageViews?

I'm pretty new to native Android development. What my app is currently doing:
Download a JSON of image urls from our server
Add an ImageView to a ListView for each image
I've gotten the JSON and am now working on using an ImageAdapter (extends BaseAdapter) to populate the ListView, but I'm running into an error:
I'm getting println needs a message during creation of the InputStream in my OpenHttpGETConnection function.
Here's my code (in order of highest to lowest with unnecessary code removed):
Once JSON Is loaded my onPostExecute code'll run to start the adapter:
private class DownloadImagesTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls){
return getImages(urls[0]);
}
#Override
protected void onPostExecute(String result){
JSONArray images = null;
images = new JSONArray(result);
// TURN images into array of imageviews
ListView listView = (ListView) findViewById(R.id.list);
#here----> listView.setAdapter(new ImageAdapter(getBaseContext(), images));
Log.d("DownloadTextTask", images.toString());
}
}
Here's my ImageAdapter code:
public class ImageAdapter extends BaseAdapter {
private Context context;
private JSONArray images;
public ImageAdapter(Context c, JSONArray i){
context = c;
images = i;
}
// returns an imageview view
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView = new ImageView(context);
try {
String url = "http://www.example.com/" + images.get(position);
#here----> imageView.setImageBitmap(getImageBitmap(url));
} catch (Exception e){
Log.d("LoadImage", e.getLocalizedMessage());
}
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
}
Here's my getImageBitmap function:
private Bitmap getImageBitmap(String url){
Bitmap bitmap = null;
InputStream in = null;
try {
#here----> in = OpenHttpGETConnection(url);
} catch (Exception e) {
#i_get
#this ----> Log.wtf("OpenGET", e.getMessage() + ": " + url );
#error
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
}
And finally, here's my OpenHttpGETConnection function:
public static InputStream OpenHttpGETConnection(String url){
InputStream inputStream = null;
HttpClient httpClient = null;
HttpResponse httpResponse = null;
httpClient = new DefaultHttpClient();
httpResponse = httpClient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
return inputStream;
}
And here's the pertaining LogCat line: (Happens for 3 images that came through the JSON file)
A/OpenGET﹕ println needs a message: http://www.example.com/image1.jpg
The weird thing is, I use the same OpenHttpGETConnection when I load my JSON data, so I'm pretty sure that's returning a correct InputStream object. Are there some caveats when using it for text vs. binary data (jpg)?
Thanks in advance!
First of all in the adapter, in the getView() method, you're not recycling the items. Have a look on the ViewHolder pattern (http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html).
Then, getImageBitmap() seems to be executed on the same thread, I wonder why it doesn't crash. I guess there you download the actual image. It should be done asynchronously, and you should send a reference of the ImageView and when the download is finished you should load it into it. Of course you'll have to care about if when you put the bitmap inside the ImageView you have the good ImageView on the screen (because it might have been recycled).
To get rid of all these concerns you could just use Picasso library (http://square.github.io/picasso/) and that will do all this for you.

InputStream freezes UI on Android

I am downloading images in background for a list. I have noticed that even with AsycTask the scrolling is not smooth. After some hours of debugging, I have came to conclusion that the InputStream is the guilty one.
doInBackground should be working on a non-ui thread, then why does it impact the UI?
If I comment out the InputStream code, the scrolling is smooth.
I have 3 images in a row, so usually 3 images are loaded at the same time.
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
final WeakReference<ImageView> imageViewReference;
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) {
InputStream is = null;
try {
is = (InputStream) new URL(params[0]).getContent();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
// REMOVED ON PURPOSE TO CONFIRM THAT INPUTSTREAM IS GUILTY
}
}

Categories