Pulling images from Web - android

I'm using the following code to grab images from the web. It uses Gridview and depending on position, picks a URL from an array. It works but the loading of images is often hit or miss. Almost every time I start the app, a different number of images load.
It also has issues when changing from portrait to landscape view, 5 out of 10 images may be displayed then I'll turn the device and usually lose all the images. Sometimes a few do show up though.
Any ideas on making this more robust?
try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "error...");
}
return null;

One thing I read is that there's a known bug with decoding Bitmaps from an InputStream, and the suggested fix from Google was to use a FlushedInputStream (example in below URL):
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
Also, I'd put the download code into an AsyncTask. Here's what I currently use for mine:
public static Bitmap loadImageFromUri(URI uri)
{
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
Log.v("URL Exception", "MalformedURLException");
return null;
}
try
{
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(new FlushedInputStream(input));
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
I just pass in a URI due to the way I've got the rest of my code set up, you could pass in a URL instead and skip the first part. This will keep the download from tying up your UI thread.

Related

Load image from Google Places in Android

I'm having trouble with loading an image from a URL into my Android app using the Google Places API.
I got the part with the API working and I can see the image if I type the URL in my browser. The code fails in the below line:
Bitmap myBitmap = BitmapFactory.decodeStream(input);
The strange thing is, it simply jumps to the return null in the catch clause without executing the println commands.
I should also explain that I'm using two URL's since the first URL in the google API is a redirect page.
I assume that the problem is that the final page that's being loaded isn't actually a "real" image (I mean it looks like
https://lh4.googleusercontent.com/XXX/s1600-w400/
rather than something like
http://something/image.jpg)
Below is the entire method I'm using:
public Bitmap getImageData(Place p) {
try {
String src= "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="+
p.getPhoto_reference()+
"&key="+
this.context.getResources().getString(places_api);
Log.d("srcsrc", src);
URL url = new URL(src);
HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
HttpsURLConnection connection = (HttpsURLConnection) secondURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Bitmap exception" + e);
return null;
}
}
Appreciate your help.
use Picasso like this :
Picasso.with(context).load(src).into(imageView );
It will do the following:
Handling ImageView recycling and download cancelation in an adapter.
Complex image transformations with minimal memory use.
Automatic memory and disk caching.

cookies with getBitmapFromURL()

I am passing the url to get the images from the server e.g.
getBitmapFromURL("http://abc.xyz.in/logo.jpg");
But it is not returning anything. Saying that images are private. So my question is that is there anyway to pass the cookie to getBitmapFromURL() method. So that i can get the images. Or any other alternative is there? Thanks a lot.
2014, if the answer is feasible to you please raise the answer and points
This should do the trick:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Don't forget to add the internet permission and any other permission which is needed in your manifest.
I got my answer. I can do this by using following line:
connection.addRequestProperty("key", value);

Load image from url. emulator work well but device not work

I had develop a mobile apps to load image from URL path.
Here is my code.
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e)
{
System.out.println("Exc="+e);
return null;
}
}
This method is work well in emulator which android API 10 but cannot work in android device. The device i use test is API 16 and 17.
Kindly look for help. Thanks.
Have you done this?:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and yes, you must be connected to the internet.
Try to move this code to a thread or AsyncTask. Http requests can't be done from main thread because of strict mode.Here check AsyncTask.
LotusUNSW is right, you have to add INTERNET permission but if it's working on emulator it seems that this permission is set .
EDIT :
Alternatively, you can try using this method :
(last code was a stupid copy paste without checking, available here)
Don't forget to do this in a separate thread (using AsyncTask for example)
But try this thing instead
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
and then
Bitmap b = getImageBitmap("http://sdsdsdsdsdsdsds");
if (b != null)
myImageView.setImageDrawable(d);
Source :here

Trying to display images from a website in Android

below is my code... but only a blank screen shows up, anyone know what's up?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
URL url;
try {
url = new URL("http://pennapps.com/biblioteka/images/C.jpg");
URLConnection conn=url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
ImageView image = new ImageView(this);
image.setImageBitmap(bm);
setContentView(image);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Without seeing the logs, it's tough to say, but a common pitfall is forgetting to request the INTERNET permission. In addition, it's highly recommended that you do not make web requests on the main (UI) thread. There is an excellent article on Multithreading for Performance that also covers the topic of image downloading.
You forgot the permission tag , else the code seems to be working

How to work with an image using url in android?

Given a Url for an image, I want to downoload it and paste it onto my canvas in android. How do I retrieve the image into my app ?
Please help.
Thanks,
de costo.
Dont forget to give the app the permission to connect to the Web,
in the AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
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();
Requires the following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
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

Categories

Resources