正在从 Android 中的 url 获取图像
Fetching image from url in Android
我正在尝试从 Url 中获取图像,但出现 I/O 异常。
我真的不知道为什么。
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 在我的应用程序中随处抛出异常。我的意思是在每个 class 中,我无法使用这个 class。
我试过那个代码,错误是这样的:
Caused by: android.os.NetworkOnMainThreadException
因此解决方案是将其包含在您的代码中:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
我正在尝试从 Url 中获取图像,但出现 I/O 异常。 我真的不知道为什么。
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 在我的应用程序中随处抛出异常。我的意思是在每个 class 中,我无法使用这个 class。
我试过那个代码,错误是这样的:
Caused by: android.os.NetworkOnMainThreadException
因此解决方案是将其包含在您的代码中:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);