Designer 10.5 | webMethods Mobile Development | Code Snippets | Downloading an Image from a Remote Host
 
Downloading an Image from a Remote Host
Downloading an image from a server is a typical scenario for using AbstractThreadedOperation. First, you must subclass AbstractThreadedOperation. After this, you must open an HTTPConnection, and the result must be read using a DataInputStream.
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
import com.softwareag.mobile.runtime.toolkit.operations.AbstractThreadedOperation;

public class ImageLoaderOperation extends AbstractThreadedOperation {

private final String url;
private byte[] imageData = new byte[0];
public ImageLoaderOperation(final String url) {
this.url = url;
}
protected void runInternal() throws Exception {
HttpConnection hpc = null;
DataInputStream dis = null;
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
hpc = (HttpConnection) Connector.open(url);
final byte[] data = new byte[8192];
int read = 0;

final InputStream stream = hpc.openInputStream();
dis = new DataInputStream(stream);

while ((read = dis.read(data, 0, 8192)) > 0) {
output.write(data, 0, read);
}
imageData = output.toByteArray();
} finally {
if(dis != null) {
dis.close();
}
if(output != null) {
output.close();
}
}
}
public Image getImage() {
Image image = null;
if ((imageData != null) && (imageData.length > 0)) {
image = Image.createImage(imageData, 0, imageData.length);
}
return image;
}
}
Related Topics