Android - Load image from URL not working - android

please help me with these code, It doesn't show image from URL.
And another question, how to debug each functions such as "url.openConnection", "getInputStream".... to confirm they work well or not?
Thank you
public class MainActivity extends Activity {
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
// ImageView
ImageView imgView = new ImageView(this);
mainLayout.addView(imgView);
bitmap = loadImage("https://www.google.com.vn/logos/doodles/2014/dian-fosseys-82nd-birthday-5702250374627328-hp.jpg");
imgView.setImageBitmap(bitmap);
}
public Bitmap loadImage(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);
input.close();
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}

The problem is that you are doing network communications on the main thread, and assuredly getting a NetworkOnMainThreadException because of it.
While you could implement an AsyncTask to manage your network calls, I would strongly suggest using a networking-capable image library to do all the grunt work for you.
https://github.com/nostra13/Android-Universal-Image-Loader

Probably a good idea to choose ImageLoader library rather than doing all this nitty gritty stuff yourself. It is not optimised and error prone too.

Related

Android imageview flickering

In my app I have list view and each item in the list contains an Image view. The image is loaded from bitmap using
imageView.setImageBitmap(bitmap);
For handling concurrency i am using the method described in the following official documentation.
Processing Bitmaps Off the UI Thread
On high density devices the image view flickers. Any possible solution for this problem?
when i use handle concurrency then only the flickering happens and when i am using asynctask only then there is no flickering
Use Picasso , Picasso saves you all the problems with downloading, setting and caching images. The whole code needed for a simple example is:
Just use like this (from UI Thread) :
In listview , use this in getView() , it handles caching and else..
Picasso.with(context)
.load(url)
.into(imageView);
http://square.github.io/picasso/
or
ImageView tre = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...sdsdsd ...";
mChart.setTag(URL);
new DownloadImage.execute(tre);
public class DownloadImage extends AsyncTask<ImageView, Void,Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}

why my animations are not proper and image loading is taking more time in some of the images?

public class LoadImageActivity extends Activity {
ImageView image_view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image_view = (ImageView)findViewById(R.id.imageview);
me m1=new me();
m1.execute("http://wallbase1.org/thumbs/rozne/thumb-499842.jpg");
me m2=new me();
m2.execute( "http://wallbase1.org/thumbs/rozne/thumb-637449.jpg");
me m3=new me();
m3.execute( "http://wallbase1.org/thumbs/rozne/thumb-2509834.jpg");
me m4=new me();
m4.execute( "http://wallbase1.org/thumbs/rozne/thumb-2501884.jpg");
me m5=new me();
m5.execute( "http://wallbase1.org/thumbs/rozne/thumb-2514440.jpg");
};
class me extends AsyncTask<String, Integer, Bitmap> {
Bitmap b1;
// private MainActivity m1;
protected Bitmap doInBackground(String...params) {
// TODO Auto-generated method stub
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
b1=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
image_view.setImageBitmap(b1);
Animation rotation = AnimationUtils.loadAnimation(LoadImageActivity.this, R.anim.rotate);
image_view.startAnimation(rotation);
}
}}
I am trying to show an image from internet by decoding it into bitmap,i want to show multiple images from multiple urls.Is there any better way of implementing it?
The duration of a download depends on a lot of different stuff. You currently spawn 5 AsyncTasks and there is no guarantee that the order of delivery/execution will be the same order you spawned them. It is easily possible that the fifth image might be the first you received and this would result in a totally wrong order. So you should download all images first, possibly with just one AsyncTask. After that and if that succeeded, you should start the animation and switch between the images.
There're several better ways of doing it and all of them are far more complex than your code. But you do have a good start.
This video form Google I/O have some good techniques for image, check around 4:40 https://www.youtube.com/watch?v=gbQb1PVjfqM
It takes different times because they are different images with probably different sizes.
Please post your XML R.anim.rotate code so someone can try to check why the animation is not working.

Android: Load image on launch from URL

I am a learner and have been working on a home visitor app to get image from a URL of the visitor. Using the following code, which I found online, I was able to load image by adding an intent before the screen and adding a button on the screen saying "See Visitor Image" but now I want that my image should load as soon as the app launches. What changes could I make to do that? Thanks for your help.
OnClickListener getImageBtnOnClick = new OnClickListener() {
public void onClick(View view) {
Context context = view.getContext();
Editable ed = inputUrl.getText();
Drawable image = ImageOperations(context,ed.toString(),"image.jpg");
ImageView imgView = new ImageView(context);
imgView = (ImageView)findViewById(R.id.image1);
imgView.setImageDrawable(image);
}
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
inputUrl = ((EditText)findViewById(R.id.imageUrl));
inputUrl.setSingleLine();
inputUrl.setTextSize(11);
Button getImageButton = (Button)findViewById(R.id.getImageButton);
getImageButton.setOnClickListener(getImageBtnOnClick);
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view
Or on OnResume of ur activity start downloading the image form the url as u r doing now in the click listener of button in a separate thread to avoid blocking main UI thread. Once you completed the download you can update the image view using handler from the worker thread.
You can make use of async task also instead of creating your own thread and handler to update UI. for more infor about async task refer following link http://www.vogella.com/articles/AndroidPerformance/article.html

ImageView not updating with bitmap?

why my imageview is not updating in the for loop,only the image from last url is showing in the imageview not all the images,what i am doing wrong?
public class LoadImageActivity extends Activity {
ImageView image_view;
Bitmap bitmap;
String[] imageLocation={
"http://wallbase1.org/thumbs/rozne/thumb-499842.jpg",
"http://ns3002439.ovh.net/thumbs/rozne/thumb-2493796.jpg",
"http://ns3002439.ovh.net/thumbs/rozne/thumb-2486664.jpg" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image_view = (ImageView)findViewById(R.id.imageview);
for (int i = 0; i < 2; i++) {
bitmap = loadImage(imageLocation[i]);
image_view.setImageBitmap(bitmap);
Animation rotate = AnimationUtils.loadAnimation(LoadImageActivity.this, R.anim.rotate);
findViewById(R.id.imageview).startAnimation(rotate);
}
}
public Bitmap loadImage(String image_location){
URL imageURL = null;
try {
imageURL = new URL(image_location);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = HttpURLConnection)imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
Well, at first, how slow is you device that you would switch between images in two successing lines of code (effectively)?
Secondly, the system has to be layouted first which happens after onCreate() returns. What you did is:
-set reference to bitmap that will be shown when layouted
-changed that reference
-let the system do the layout (Question: Which reference will be read?)
It looks like you want to set the first bitmap, rotate it and then set the other bitmap.
What you need to do is:
-set bitmap
-start animation with an Animation.AnimationListener, which sets the second bitmap in onAnimationEnd().
#Thanks to Adam!
You can put an Animation.AnimationListener on your first animation, and you can load the next image and start the new transition in the onAnimationEnd(...) method of the listener.
Try setting the underlying object (Bitmap) and then updating the ImageView.
The method loadImage() is not in UI main Thread, use a Handler to update the ImageView with your new image.

Android image fetching

What is the simplest way to fetch an image from a url in an android program?
I would strongly recommend using an AsyncTask instead. I originally used URL.openStream, but it has issues.
class DownloadThread extends AsyncTask<URL,Integer,List<Bitmap>>{
protected List<Bitmap> doInBackground(URL... urls){
InputStream rawIn=null;
BufferedInputStream bufIn=null;
HttpURLConnection conn=null;
try{
List<Bitmap> out=new ArrayList<Bitmap>();
for(int i=0;i<urls.length;i++){
URL url=urls[i];
url = new URL("http://mysite/myimage.png");
conn=(HttpURLConnection) url.openConnection()
if(!String.valueOf(conn.getResponseCode()).startsWith('2'))
throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage());
rawIn=conn.getInputStream();
bufIn=new BufferedInputStream();
Bitmap b=BitmapFactory.decodeStream(in);
out.add(b);
publishProgress(i);//Remove this line if you don't want to use AsyncTask
}
return out;
}catch(IOException e){
Log.w("networking","Downloading image failed");//Log is an Android specific class
return null;
}
finally{
try {
if(rawIn!=null)rawIn.close();
if(bufIn!=null)bufIn.close();
if(conn!=null)conn.disconnect();
}catch (IOException e) {
Log.w("networking","Closing stream failed");
}
}
}
}
Closing the stream/connection and exception handling is difficult in this case. According to Sun Documentation you should only need to close the outermost stream, however it appears to be more complicated. However, I am closing the inner most stream first to ensure it is closed if we can't close the BufferedInputStream.
We close in a finally so that an exception doesn't prevent them being closed. We account for the possibility of the streams will being null if an exception prevented them from being initialised. If we have an exception during closing, we simply log and ignore this. Even this might not work properly if a runtime error occurs .
You can use the AsyncTask class as follows. Start an animation in onPreExecute. Update the progress in onProgressUpdate. onPostExecute should handle the actual images. Use onCancel to allow the user to cancel the operation. Start it with AsyncTask.execute.
It is worth noting that the source code and the license allow us to use the class in non-Android projects.
You do it many ways but the simplist way I can think of would be something like this:
Bitmap IMG;
Thread t = new Thread(){
public void run(){
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL("YOUR URL");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
IMG = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
// ...send message to handler to populate view.
mHandler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(DEB, "Remtoe Image Exception", e);
mHandler.sendEmptyMessage(1);
} finally {
}
}
};
t.start();
And then add a handler to your code:
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case 0:
(YOUR IMAGE VIEW).setImageBitmap(IMG);
break;
case 1:
onFail();
break;
}
}
};
By starting a thread and adding a handler you are able to load the images without locking up the UI during download.

Categories

Resources