Jsoup速度非常慢,无法读取图像

时间:2019-05-04 13:56:49

标签: java android jsoup

我想从网站上下载图像并将其显示在列表中,但是下载速度非常慢,我认为我的代码存在问题。

私有类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 :(得分:0)

这是因为每次使用以下方法找到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 Adapter中解码图像。