我嘗試解碼從輸入流的URL bipmap的Android異步獲取圖像
公共類演示實現MVPmain.presenter {
String LOG_TAG = "Presenter: ";
private final MVPmain.view view;
String url = "https://jsonplaceholder.typicode.com/";
public Presenter(MVPmain.view view) {
this.view = view;
}
void photosUrl() {
String photoUrl = "http://placehold.it/600/92c952";
AsyncLoadImage asyncLoadImage = new AsyncLoadImage();
asyncLoadImage.execute(photoUrl);
}
}
@Override
public void button_photos_clicked() {
photosUrl();
}
Bitmap loadImage(String url) {
Bitmap bitmapImage = null;
URL imageUrl = null;
HttpURLConnection httpURLConnection = null;
try {
imageUrl = new URL(url.replaceAll("\\r|\\n", ""));
httpURLConnection = (HttpURLConnection) imageUrl.openConnection();
bitmapImage = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
Log.d(LOG_TAG, "Runneble: " + "OK");
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "image url error: " + e);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmapImage;
}
class AsyncLoadImage extends AsyncTask<String, Void, Bitmap> {
String LOG_TAG = "AsyncLoadImage: ";
Bitmap bitmapImage;
@Override
protected Bitmap doInBackground(String... strings) {
String request = "";
final URL imageUrl = null;
JSONObject jsonObject = null;
for (final String address : strings) {
Log.d(LOG_TAG, "img url: " + address);
bitmapImage = loadImage(address);
}
return bitmapImage;
}
@Override
protected void onPostExecute(Bitmap bitmapImg) {
view.setPhotos(bitmapImg);
}
}
}
它的代碼的一部分,在那裏我得到異常:httpURLConnection.getInputStream()中的連接被拒絕。我嘗試.getContent並得到這個錯誤。 請告訴我,我該如何做到這一點。
解決 此錯誤的情況下AdWay!)
您是否在Manifest中添加 –
是的。起初,我從這裏獲取照片的地址:https://jsonplaceholder.typicode.com/photos/3,asynctask使用此網址,但不能與圖片網址一起使用:http://placehold.it/600/92c952 。 例如,這個網址:https://image.flaticon.com/teams/slug/freepik.jpg工作... –