解码位图流失败



我正在尝试通过"山姆在24小时内自学的Android应用程序开发" 。在本节中:

private Drawable getQuestionImageDrawable(int questionNumber) {
    Drawable image;
    URL imageUrl;
    try {
        // Create a Drawable by decoding a stream from a remote URL
        imageUrl = new URL(getQuestionImageUrl(questionNumber));
        InputStream stream = imageUrl.openStream();
        Bitmap bitmap = BitmapFactory.decodeStream(stream);
        image = new BitmapDrawable(getResources(), bitmap);
    } catch (Exception e) {
        Log.e(TAG, "Decoding Bitmap stream failed");
        image = getResources().getDrawable(R.drawable.noquestion);
    }
    return image;
}

questionNumbergetQuestionImageUrl()已进行了测试,并且正在返回我认为是正确的值(1和http://www.perlgurl.org/Android/BeenThereDoneThat/Questions/q1.png)。该网址有一个图像,但我总是会得到例外。我尝试了几种变体,但是当它们都没有工作时,我从书中回到了此代码。我在这里做错了什么?

我是Java和Android的新手,所以我可能缺少简单的东西。我在书中的代码和网站上的更新代码(所有这些都已在此处或developer.android.com解决)中还有许多其他问题。这是我的第一个问题,因此,如果我没有提供任何信息,请告诉我。

我会做以下操作,它可能有效:

private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
    // Create a Drawable by decoding a stream from a remote URL
    imageUrl = new URL(getQuestionImageUrl(questionNumber));
    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream stream = conn.getInputStream();
    Bitmap bitmap = BitmapFactory.decodeStream(stream);
    image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
    Log.e(TAG, "Decoding Bitmap stream failed");
    image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}

请确保您在主台面的背景线程中进行此类重型操作,并已允许您的应用程序清单。让我知道您的进度。

可能例外是因为您正在制作网络连接表单ui线程。它适用于较旧的Android版本,但在更新的情况下不行。查看Android网络操作部分。

主要要做的是使用asynctask

最新更新