Android在按钮点击时从网址加载图片

时间:2011-05-04 08:58:06

标签: android

我想在点击按钮上加载来自网址的图片。在活动imageview上显示它。

怎么做? 我尝试以下代码,但它显示系统错误,如java.net.UnknownHostException主机已解决。

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();
    }

}
}

请告诉我我要改变的地方

5 个答案:

答案 0 :(得分:2)

这似乎只是为了在ImageView上显示很多代码。试试这个:

URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);

答案 1 :(得分:1)

使用以下代码,它将帮助您

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;     
    }
}

答案 2 :(得分:0)

  

我想在点击按钮上加载来自网址的图片。在活动imageview上显示它

您必须在onPageFinished内执行以下操作:

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

   view.getSettings().setLoadsImagesAutomatically(true); 
   wv.setVisibility(View.VISIBLE);   
}

答案 3 :(得分:0)

创建一个名为downloadButton的新onClick方法。

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();
        }

    }

创建一个名为downloadImage的类,该类扩展了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;
        }
    }

答案 4 :(得分:-1)

只需在按钮上调用以下方法:

   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);
    }

其中url是要传递的网址,而src_name是任何字符串(例如“src”)

希望这会对你有所帮助