Hi,
Given a Url for an image, I wanted to downoload it and paste it onto my canvas in android. How do I retrieve the image to my app ??
Please help.
Thanks, de costo.
Hi,
Given a Url for an image, I wanted to downoload it and paste it onto my canvas in android. How do I retrieve the image to my app ??
Please help.
Thanks, de costo.
There is a an HTTP client library that might be supported in Android now, but for any fine grain control you can use URL & HttpURLConnection. the code will look something like this:
URL connectURL = new URL(<your URL goes here>);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn);
where getResponse() looks something like this, in your case you are getting a pile of binary data back you might want to change the StringBuffer to a byte array and chunk the reads by a larger increment.
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e(TAG, "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
As you are talking about image data which can be large, other things you need to be assiduous about in Android is making sure you release your memory as soon as you can, you've only got 16mb of heap to play with for all apps and it runs out fast and the GC will drive you nuts if you aren't really good about giving back memory resources
You can use the following code to download an image:
URLConnection connection = uri.toURL().openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
Bitmap bmp = BitmapFactory.decodeStream(bis);
bis.close();
is.close();