4

我正在尝试完成“Sam's Teach Yourself Android Application Development in 24 Hours”并在第 12 小时内陷入困境。问题似乎出在这一部分:

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)。这是我的第一个问题,所以如果我未能提供任何信息,请告诉我。

4

2 回答 2

2

我会做以下事情,它可能会起作用:

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;
}

确保您在后台线程而不是主线程中执行此类繁重的操作,并且对您的应用程序清单具有 INERNET 权限。让我知道你的进展。

于 2012-11-06T19:17:01.547 回答
0

可能例外是因为您正在从应用程序 ui 线程建立网络连接。这适用于较旧的 Android 版本,但不适用于较新的 Android 版本。看看Android网络操作部分

要做的主要事情是使用AsyncTask

于 2012-11-06T18:51:29.650 回答