从Android中获取URL中的图像

从Android中获取URL中的图像

问题描述:

我正在尝试从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中是否有任何例外?代码是否不能编译?究竟是什么问题?请[编辑]您的问题告诉我们,以便我们能够准确地帮助您。 –

我试过了代码和错误是这样的:android.os.NetworkOnMainThreadException

所以解决的办法是,包括这在你的代码:

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

所致

+0

更好的解决方案是只是做一个单独的线程网络 – Soana

+0

更好的解决方案是使用排气和异步加载图像... –

+0

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