2012-11-06 35 views
2

我试图通过工作我的“Sam的自学Android应用开发在24小时内”,已经成为卡在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解决了这些问题)存在许多其他问题。这是我的第一个问题,所以如果我没有提供任何信息,请告诉我。

+1

确保您没有忘记将INTERNET权限添加到您的清单文件中。 – Egor

+0

谢谢你Egor!我没有添加INTERNET许可,并且回顾了这本书,我没有看到它告诉我的任何地方。到目前为止,http://developer.android.com/training/index.html是比本书更好的学习工具。 – Pepelluepe

+0

欢迎来到Stackoverflow。不得不说,看到有人以结构化的方式学习,并且小心谨慎地花时间来构建一个好问题令人耳目一新。为了将来的参考,尽管在这种情况下不需要,但有关异常的问题通常应包括logcat输出的相关部分。 +1来帮助你在旅途中祝你好运。 – Simon

回答

1

我会做以下,它可能工作:

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

确保你的后台线程insteaad做这种重操作主要的一个,并且拥有应用程序清单的INERNET权限。 让我知道你的进步。

+0

伊戈尔首先得到它,但缺乏互联网许可是问题所在。也感谢有用的演示。 – Pepelluepe

+0

更新:此解决方案在模拟器中完美工作,但在设备上进行测试时仍然会出现异常。我现在正在进行更多测试。 – Pepelluepe

0

可能是例外,因为您正在从应用程序ui线程进行网络连接。这适用于较旧的Android版本,但不适用于较新的版本。 看看Android network operation section

主要的事情是使用AsyncTask

+0

谢谢。叶戈尔原来在上面的评论中有立即的解决方案,但是你的信息也很有用。我还没有得到多线程,但现在我确实看到它可能会有多大用处。 – Pepelluepe