Android async get image

时间:2017-10-08 07:52:59

标签: android bitmap android-asynctask

I try to decode to bipmap from input stream URL

public class Presenter implements 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);
    }

}

}

it's a part of code, where I get exception: Connection refused in httpURLConnection.getInputStream(). I try .getContent and get this error too. Please, tell me, how I can do this.

SOLVED This error cases AdWay!)

1 个答案:

答案 0 :(得分:0)

您的代码在我的设备中完美运行。

确保您的互联网连接正常工作,并直接从Android设备中的浏览器打开图片网址,以验证您是否有权访问该网址。