0

我在从 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。我可以在我的模拟器上连接到互联网,但在 logcat 中它告诉我它无法建立连接。我还在清单中为互联网设置了权限。我对这可能很容易解决的问题感到目瞪口呆。

4

1 回答 1

0

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

于 2013-03-16T00:53:52.383 回答