2012-11-06 34 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