Android-从URL添加到rootview的位图

Android-从URL添加到rootview的位图,android,Android,从url中提取位图时遇到了一些问题。我在堆栈中使用了另一个问题的示例,但它不会加载图像。代码如下: public class Image extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Bitmap bitmap

从url中提取位图时遇到了一些问题。我在堆栈中使用了另一个问题的示例,但它不会加载图像。代码如下:

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。我可以在模拟器上连接到internet,但在logcat中它告诉我它无法建立连接。我还在清单中为internet设置权限。这可能是一个简单的修复方法,我很惊讶。

您正试图在UI线程上运行网络操作(http连接)。您应该看看threads&asynctasks:

Quanturium回答的是一个开始。但是你真的应该发布日志,看看你遇到了什么问题。谢谢你给我指出了正确的方向。另外,我明天回去工作的时候一定会发布日志。当你的bug被修复了一周后,别忘了将这个主题标记为已解决。我现在又回到这个案子上了。线程和进程页面实际上是我的桌面背景。