1

I want to load an image from url on a button click & to show it on activity imageview.

how to do it? I try the following code but it shows the system error like java.net.UnknownHostException Host is on resolved.

package com.v3.thread.fetchImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpException;
import org.apache.http.conn.HttpHostConnectException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainThreadActivity extends Activity {
    ImageView img_downloaded;
    Button btn_download;
    String fileurl = "http://variable3.com/files/images/email-sig.jpg";

Bitmap bmImg;
private ProgressDialog dialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //new MainThreadActivity().onPreExecute();

    img_downloaded = (ImageView) findViewById(R.id.imageView1);
    btn_download = (Button) findViewById(R.id.btnLoad);

    btn_download.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            try {
                downloadfile(fileurl);
            } catch (HttpHostConnectException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (HttpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}


public void AbstractProgressTask() {
    dialog = new ProgressDialog(this);
}

protected void onPreExecute() {new MainThreadActivity().onPreExecute();
    this.dialog.setMessage("Loading. Please wait...");
    this.dialog.show();
}

 /**
 * method is called after the work is done.
 *
 * @param success result of #doInBackground method.
 */

protected void onPostExecute(final Boolean success) {
    if (dialog.isShowing()) {
        dialog.dismiss();
    }
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {

  // here is your code
  return true;
}

void downloadfile(String fileurl) throws HttpException,HttpHostConnectException {
    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();
        int length = conn.getContentLength();
        if(length>0)
        {
            int[] bitmapData =new int[length];
            byte[] bitmapData2 =new byte[length];
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is);

          //img.setImageBitmap(bmImg);
        }
        else
        {
            int[] bitmapData =new int[length];
            byte[] bitmapData2 =new byte[length];
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is);
        }

    } 
    catch(IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

please tell me where i hav to change

Rajath
  • 11,787
  • 7
  • 48
  • 62
Harsha M V
  • 54,075
  • 125
  • 354
  • 529
  • possible duplicate of [Load an image from url on button click](http://stackoverflow.com/questions/5880191/load-an-image-from-url-on-button-click) – Vladimir Ivanov May 04 '11 at 09:47

5 Answers5

2

That seems like a lot of code just to show on an ImageView. Try this instead:

URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Rajath
  • 11,787
  • 7
  • 48
  • 62
1

Use the following code for that, it will help you

Drawable drawable = LoadImageFromWebOperations(backImgUrl);
bagImgBtn.setBackgroundDrawable(drawable);

private Drawable LoadImageFromWebOperations(String url) {
    // TODO Auto-generated method stub
    try
    {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    }catch (Exception e) {
        if (LogD) {
            Log.d(TAG, e.toString());
            e.printStackTrace();
        }
        return null;     
    }
}
Kev
  • 118,037
  • 53
  • 300
  • 385
Datta Kunde
  • 467
  • 6
  • 14
0

Create a new onClick method called downloadButton.

public void downloadButton(View view){

        Log.i("Button Status", "Button Pressed");

        downloadImage imagedownload = new downloadImage();
        Bitmap image;
        try {
            image = imagedownload.execute("Paste URL address of an image").get();
            imageView.setImageBitmap(image);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

Create a class called downloadImage which extends AysncTask.

public class downloadImage extends AsyncTask<String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... urls) {

            try {
                URL url = new URL(urls[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                InputStream inputStream = httpURLConnection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;

            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }

sophin
  • 583
  • 5
  • 11
-1

Just call the following method on Button Click:

   Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException 
    {
        return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
    }

where url is the url to pass and src_name is any String(say "src")

Hope this will help you

Dinesh Sharma
  • 11,533
  • 7
  • 42
  • 60
-1

I want to load an image from url on a button click & to show it on activity imageview

You have to do something like below within onPageFinished:

public void onPageFinished (WebView view, String url) {       
   wv.loadUrl(javascript);         

   view.getSettings().setLoadsImagesAutomatically(true); 
   wv.setVisibility(View.VISIBLE);   
}
RobinHood
  • 10,897
  • 4
  • 48
  • 97
  • This is all but an answer. Please put a bit more effort into your answer. Describe what the problem was or what your code does. – Octavian Helm May 24 '11 at 12:54
  • i think people find useful that why they vote up. as per the rules.-Reno at what basis you are blaming i don't know. – RobinHood Jun 11 '11 at 08:45