在按钮单击时从URL加载图像

时间:2011-05-04 07:45:13

标签: android

如何在按钮点击时从网址加载图像,该图像将显示在活动本身上?

我尝试以下代码,但它显示系统错误,如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)
        {
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is);
            img_download.setImageBitmap(bmImg);
        }
        else
        {
            InputStream is = conn.getInputStream();
            bmImg = BitmapFactory.decodeStream(is);
        }

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

}
}

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

}
}

}

2 个答案:

答案 0 :(得分:2)

您应该在按钮点击时启动AsyncTask ProgressDialog有界(请参阅example)。这是通过在按钮上设置onClickListener来实现的。在那个AsyncTask中你应该下载一张图片(见here)。下载后,只需从onPostExecute()调用您的活动上的方法即可显示图片。

答案 1 :(得分:1)

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.x);

    Button butt = (Button) this.findViewById(R.id.Button01);
    imageView =(ImageView) findViewById(R.id.ImageView01);
    Bitmap image;

    butt.setOnClickListener(new OnClickListener(){
        public void onClick(View v)  {
            URL url = null;
            try {
                url = new URL("http://lh5.ggpht.com/_hepKlJWopDg/TB-_WXikaYI/AAAAAAAAElI/715k4NvBM4w/s144-c/IMG_0075.JPG");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                image = BitmapFactory.decodeStream(url.openStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageView.setImageBitmap(image);
        }
        });
}

如果您从网上下载图片,请不要忘记包含以下权限。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>