Android -位图从URL添加到rootview



我在从url中提取位图时遇到了点麻烦。我在Stack上使用了另一个问题的例子,但它不会加载图像。下面是代码:

public class Image extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bitmap bitmap = DownloadImage("http://cogadget.com/cogadget/wp-content/uploads/2010/05/Android-Logo-50x50.jpg");
    ImageView img = (ImageView) findViewById(R.id.imageView1);
    img.setImageBitmap(bitmap);
}
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;
}

}

我正在尝试用url的位图填充ImageView。我可以在我的模拟器上连接到互联网,但在日志中它告诉我它不能建立连接。我还在清单中设置了互联网的权限。

您正在尝试在UI线程上运行网络操作(http连接)。你应该看看线程& &;Asynctasks: http://developer.android.com/guide/components/processes-and-threads.html

最新更新