Jsoup очень медленно читает изображения - PullRequest
0 голосов
/ 04 мая 2019

Я хочу загрузить изображения с веб-сайта и отобразить их в списке, но скорость загрузки очень низкая. Я предполагаю, что в моем коде есть проблема.

закрытый класс mAsyncTask расширяет AsyncTask {

    Bitmap bitmap;

    @Override
    protected Void doInBackground(Void... params) {

        try {
            // Connect to the web site
            Document document = Jsoup.connect(url).get();
            // Using Elements to get the class data
            Elements mElementDataSize1 = document.select("h5");
            for (int i = 0; i < mElementDataSize1.size(); i++) {
                Elements img = document.select("[class=product_list grid row] img[src]").eq(i);
                // Locate the src attribute
                String imgSrc = img.attr("src");
                // Download image from URL
                InputStream input = new java.net.URL(imgSrc).openStream();
                // Decode Bitmap
                bitmap = BitmapFactory.decodeStream(input);

                bitmapArray.add(bitmap); // Add a bitmap
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(Void result) {

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter mDataAdapter = new mAdapter(MainActivity.this,bitmapArray);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mDataAdapter);

    }
}

1 Ответ

0 голосов
/ 04 мая 2019

Это потому, что вы пытаетесь декодировать источник изображения в растровое изображение каждый раз, когда находите src с помощью:

InputStream input = new java.net.URL(imgSrc).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);

декодирование входного потока в растровое изображение является дорогостоящим и медленным процессом.

И тогда вы всегда будете ждать и накапливать время, необходимое для декодирования изображения для всех изображений:

for (int i = 0; i < mElementDataSize1.size(); i++) {

    ...
    String imgSrc = img.attr("src");

    // You accumulate the the time needed to decode the image here.
    bitmap = BitmapFactory.decodeStream(input);
    ...
}

Чтобы решить эту проблему, вам нужно только сохранить URL-адрес изображений и затем расшифровать их следующим образом:

// save the images url instead of the Bitmap.
private List<String> mImageUrls = new ArrayList<>();

@Override
protected Void doInBackground(Void... params) {
    try {

        // Connect to the web site
        Document document = Jsoup.connect(url).get();
        // Using Elements to get the class data
        Elements mElementDataSize1 = document.select("h5");
        for (int i = 0; i < mElementDataSize1.size(); i++) {
            Elements img = document.select("[class=product_list grid row] img[src]").eq(i);
            // Locate the src attribute
            String imgSrc = img.attr("src");

            // add the url
            mImageUrls.add(imgSrc);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return v;
}

затем используйте Glide, Picasso и т. Д. Для декодирования изображений в вашем адаптере RecyclerView.

...