3

I am trying to make a mobile app using Java and codename one plugin. My question is - what's the simples way to populate an image from a URL to a label? I Googled it and all I found was this piece of code:

Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE); 

But I have no idea how to use it. What is a placeholder? It asks an EncodedImage parameter, but if I do:

EncodedImage image = new EncodedImage(10, 10);

I get the error that EncodedImage is protected.

I simply want to populate an image from a URL to my desired label in a form.

I am using GUI builder.

1 Answer 1

4

The placeholder image is the image that should show while the image from URL is being downloaded and it's an EncodedImage.

If your Label already have an icon as a placeholder, you can use its icon, otherwise you can create a new placeholder image. Below are 3 options to create an EncodedImage and a URLImage usage example:

Method 1:

//generate a grey placeholder that matches the size of the label's icon
Image placeholder = Image.createImage(label.getIcon().getWidth(), label.getIcon().getWidth(), 0xbfc9d2);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);

Method 2:

//Convert the label icon to EncodedImage
EncodedImage encImage = (EncodedImage)label.getIcon();

Method 3:

//Create a fresh grey EncodedImage when label doesn't have any icon set initially
int deviceWidth = Display.getInstance().getDisplayWidth();
Image placeholder = Image.createImage(deviceWidth / 10, deviceWidth / 10, 0xbfc9d2); //square image set to 10% of screen width
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);

Usage Example:

It's a good practice to use the URL as the cached image name in storage. If you have a multiple sizes of the same image, just prefix them with a unique string like "Large" + URL

 label.setIcon(URLImage.createToStorage(encImage, "Medium_" + "http://xxx/myurl.jpg", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.