2016-06-11 99 views
0

我正在嘗試從Url獲​​取圖像,但我收到了I/O異常。 我真的不知道爲什麼。從Android中獲取URL中的圖像

try { 
     URL profilePicUrl = new URL("http://houssup.netau.net/vivek_thumbnail.jpg"); 

     HttpURLConnection connection =(HttpURLConnection) profilePicUrl.openConnection(); 

     connection.setDoInput(true); 


     connection.connect(); 

     InputStream inputStreamImage = connection.getInputStream(); 

     Bitmap profileImage = BitmapFactory.decodeStream(inputStreamImage); 

     holder.profilePic.setImageBitmap(profileImage); 


    } catch (MalformedURLException e) { 
     Log.e("Profile Image","Error in URL"); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     Log.e("Profile Image","Error in IO"); 
     e.printStackTrace(); 
    } 

此外,我要特別強調,HttpURLConnection的是在我的應用隨處亂扔異常點。我的意思是在每個班級中,我都無法使用這門課程。

+0

您是否嘗試過使用像畢加索這樣的合適圖像加載庫?這將大大簡化這裏的問題 –

+0

好吧,我會嘗試。但仍然需要解決問題 –

+2

目前尚不清楚問題是什麼。該網址是好的,那麼在logcat中是否有任何例外?代碼是否不能編譯?究竟是什麼問題?請[編輯]您的問題告訴我們,以便我們能夠準確地幫助您。 –

回答

0

我試過了代碼和錯誤是這樣的:android.os.NetworkOnMainThreadException

所以解決的辦法是,包括這在你的代碼:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
      .permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

所致

+0

更好的解決方案是隻是做一個單獨的線程網絡 – Soana

+0

更好的解決方案是使用排氣和異步加載圖像... –

+0

@FranciscoCastro thanx兄弟,你剛剛救了我的命.. –