I am trying to download images from the net in my android application, it works most of the times but some pictures are failing to download and the Bitmap is null. The link to the images is always being there however. Any ideas what is causing this?
private class GetImage extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
int len = 500;
try {
URL url = new URL(urls[0]);
Log.v("url",urls[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
int response = connection.getResponseCode();
inputstream = connection.getInputStream();
System.out.println(inputstream.toString());
bitmap = BitmapFactory.decodeStream(inputstream);
if(bitmap==null)
Log.v("Bitmap","fail");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputstream != null) {
try {
inputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "some string since it bitmap is sometimes null";
You can't always count on the network. You can use an http library like okhttp or volley that will allow you to do retries easily (or you could just retry yourself). Those libraries do a bunch of things to smooth out the http experience over using raw HttpUrlConnection.
Depending on how critical the image is, you could always hide the image in onPostExecute if it fails.
Related
Given the URL of a website I want to retrieve the logo and background image of the website and display it in an android app. For example from this link I would want the background image and the hack western logo.
EDIT: I forgot to mention I am trying to achieve this effect for a list of URL's of undetermined size until run time
Use this AsyncTask for loading image from URL
public class LoadImageTask extends AsyncTask<Void, Void, Void>{
private Bitmap mMyBitmap;
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://hackwestern.com/images/logo_vert_spons.png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
mMyBitmap = BitmapFactory.decodeStream(input);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mImageView.setImageBitmap(mMyBitmap);
}
}
Then call it on OnCreate or somewhere you need:
new LoadImageTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I'm currently trying to send an http request from an android app to google-app-engine, this request should be received by the server who will use the parameters passed in the URL to add a new item to the datastore.
I wrote this code:
private class AsyncConnection extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
// creating the url
URL url = new URL(params[0]);
// opening the connection
URLConnection connection;
connection = url.openConnection();
// get data about the connection
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
// connection was properly established
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream input = httpConnection.getInputStream();
return input.toString();
} else {
Log.d("CONNECTION", "connection not HTTP_OK");
}
} catch (MalformedURLException e) {
Log.d("SMARTGAN", "MalformedURLException" ,e);
} catch (IOException e) {
Log.d("SMARTGAN", "IOException" ,e);
} catch (Exception e) {
Log.d("SMARTGAN", "Exception" ,e);
} finally { }
return null;
}
}
but when I try to execute it I don't see any new item in the datastore.
The URL itself and the code on the server are fine, when I tried and sent the URL using it worked. I don't see any error message of "connection not ok" message in the log.
Mostly probably could be with hostname, have tried this solution How to make http post from android to google app engine server?
Also refer to https://developers.google.com/appengine/docs/java/tools/devserver#Command_Line_Arguments
I am trying to set image on imageview but image is not show.
I am reading image url from json data and then trying to set it on ImageView but my image is not visible. No any exception occur.
Here is my code
HotelList.class
static final String TAG_DISHIMAGEURL = "dishimageurl";
......
String imageUrl = dishResult.getString(TAG_DISHIMAGEURL);
map.put(TAG_DISHIMAGEURL, imageUrl);
.....
dishimageurl1 = hm.get(TAG_DISHIMAGEURL).toString();
intent.putExtra("background", dishimageurl1);
HotelDetails.class
......
String dishimageurl = bundle.getString("background");
Bitmap bimage= getBitmapFromURL(dishimageurl);
imageView.setImageBitmap(bimage);
....
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
Toast.makeText(this, "showing image", Toast.LENGTH_LONG).show();
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Toast.makeText(this, "showing exception", Toast.LENGTH_LONG).show();
return null;
}
}
I don't understand what happen with this code. No any exception but my image is not visible.
Please give me any reference.
Please Use below code for get image from url and display into imageview.
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
RelativeLayout mRlayout1 = (RelativeLayout) findViewById(R.id.mRlayout1);
Drawable d=new BitmapDrawable(bitmap);
mRlayoutLogin.setBackgroundDrawable(d);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
you can view image by using this code.
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It seems you are downloading the image from UI thread. this will block the UI thread and will give you not responding error. as an easy way, you can use a library like Universal Image Loader
Universal Image Loader - GitHub
this will manage the image loading for you and avoid problems like incorrect urls, Out Of Memory error.
I used the code as follows to show up facebook avatar to ImageView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.imgAvatar);
img.setImageBitmap(getBitmapFromURL("http://graph.facebook.com/"+"100002394015528"+"/picture"));
}
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;
}
}`
But does it not work. Please help me.
http://graph.facebook.com/id/picture doesn't return an image. It returns some response headers including a 302 redirect, and a location header.
Your example for instance redirects to: http://profile.ak.fbcdn.net/hprofile-ak-snc4/211619_100002394015528_568817_q.jpg
So instead of
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
You need to get the headers from the request, follow the location and then do what you were doing before. I don't know Android, or what language that is. (Java?) So I can't help with that, but I think this might be enough information to get you headed in the right direction.
Use this function for get real URL to avatar:
public static String getUrlFacebookUserAvatar(String name_or_idUser )
{
String address = "http://graph.facebook.com/"+name_or_idUser+"/picture";
URL url;
String newLocation = null;
try {
url = new URL(address);
HttpURLConnection.setFollowRedirects(false); //Do _not_ follow redirects!
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
newLocation = connection.getHeaderField("Location");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newLocation;
}
I need to load, and update image from URL.
Using AsyncTask, Iam able to load image from URL bt i need to reload image from url for every 10 secs.
Please help me how i can solve this issue.
Thanks in advance
#Praveenb
try following ,
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
// it will decode the input stream and will load the bitmat in bmImg variable
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
following code works fine for me,
class DownloadImage extends AsyncTask<Void, Void, Drawable>{
#Override
protected Drawable doInBackground(Void... params) {
return Util.getImageFromURL(imageURL);
}
#Override
protected void onPostExecute( Drawable d ) {
getImageIcon().setImageDrawable(d);
}
}
new DownloadImage().execute();
and if you are showing image in list view you should follow this
http://github.com/commonsguy/cwac-thumbnail