How do I set an Image component with an image url?

Having trouble with setting an image url to an image view. I have this, but it doesn't work:

try {
		URL url = new URL(pathToImage);
		InputStream is = new BufferedInputStream(url.openStream());
		Bitmap bmp = BitmapFactory.decodeStream(is);
		is.close();
		imageView.setImageBitmap(bmp);
    }  
catch (Exception e) {
		Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
	}

Also tried this:

try {
    URL url = new URL(pathToImage);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    Bitmap bitmap = BitmapFactory.decodeStream(input);
    imageView.setImageBitmap(bitmap);
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

but get a runtime error telling me I must either set a text or a view?

Another test which returns an empty runtime error message:

@SimpleFunction("loads image from url in image component")
	public void GetImage(Image imageComponent, String imageUrl) {
		ImageView imageView = (ImageView) imageComponent.getView();
		try {
			InputStream is = new java.net.URL(imageUrl).openStream();
			Bitmap bitmap = BitmapFactory.decodeStream(is);

			imageView.setImageBitmap(bitmap);

		} catch (IOException e) {
			Toast.makeText(context, "Could not load Bitmap from url", Toast.LENGTH_SHORT).show();

		}
	}

I have tried a few other methods on offer as well, and these fail too.

Also, I need to put working code into an async task.

Without image caching:


    new Thread(() -> {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            URL url = new URL(pathToImage);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setDoInput(true);
            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);

                imageView.post(() -> {
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (Exception ignored) {}
            if (connection != null) connection.disconnect();
        }
    }).start();

with caching:

   

    Bitmap cachedBitmap = memoryCache.get(pathToImage);
    if (cachedBitmap != null) {
        imageView.setImageBitmap(cachedBitmap);
        return;
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            Context context = imageView.getContext();
            String fileName = String.valueOf(imageUrl.hashCode());
            File cacheFile = new File(context.getCacheDir(), fileName);

            if (cacheFile.exists()) {
                final Bitmap diskBitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
                if (diskBitmap != null) {
                    memoryCache.put(imageUrl, diskBitmap);
                    imageView.post(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(diskBitmap);
                        }
                    });
                    return;
                }
            }

            HttpURLConnection connection = null;
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(imageUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                connection.setDoInput(true);
                connection.connect();

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    is = connection.getInputStream();
                    fos = new FileOutputStream(cacheFile);

                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                    fos.flush();

                    final Bitmap downloadedBitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
                    if (downloadedBitmap != null) {
                        memoryCache.put(pathToImage, downloadedBitmap);
                        imageView.post(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(downloadedBitmap);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fos != null) fos.close();
                    if (is != null) is.close();
                } catch (Exception ignored) {}
                if (connection != null) connection.disconnect();
            }
        }
    }).start();


I used this second code in the ListView fix.

2 Likes

Tested and working! Many thanks.

1 Like

I also got the third example I posted to work using your async code:

	@SimpleFunction("loads image from url in image component")
	public void GetImage(Image imageComponent, String imageUrl) {
		ImageView imageView = (ImageView) imageComponent.getView();

		new Thread(() -> {
			InputStream is = null;
			try {
				is = new URL(imageUrl).openStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);

				imageView.post(() -> {
					if (bitmap != null) {
						imageView.setImageBitmap(bitmap);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (is != null) is.close();
				} catch (Exception ignored) {}
			}
		}).start();
		}