【问题标题】:Loading image with Picasso does not always display用毕加索加载图像并不总是显示
【发布时间】:2016-11-08 00:32:27
【问题描述】:

我正在尝试将图像加载到我的视图中。有时它起作用,有时它不起作用。我正在 API 级别 19 模拟器上进行测试。新目标内部的故障块永远不会被调用。我看到prepareLoad,然后:

  1. 调用onBitmapLoaded,图片会显示
  2. 图片不会显示

为什么会这样?

这发生在模拟器上。在物理设备上,Q&A 报告了 100% 的失败率。在其他设备上,我看到间歇性故障率。这是怎么回事?

public void setBackground() {
    final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);

    final Context context = this;
    final String imagePath = getStore().backgroundImageURI;    

    if (getStore().backgroundImageNumber > 0) {
        mainLayout.setBackground(context.getResources().getDrawable(getStore().backgroundImageNumber));
        return;
    }
    if (imagePath == null) {
        mainLayout.setBackground(context.getResources().getDrawable(R.drawable.sk_collection_bg_default));
        return;
    }
    Picasso.with(this).load(imagePath).into(new Target(){
        @Override
        public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
            Log.v("Biscuit-width", String.valueOf(bitmap.getWidth()));
            Log.v("Biscuit-height", String.valueOf(bitmap.getHeight()));

            mainLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
        }

        @Override
        public void onBitmapFailed(final Drawable errorDrawable)
        {
            Log.d("BISCUIT", "FAILED" + errorDrawable.toString());

        }

        @Override
        public void onPrepareLoad(final Drawable placeHolderDrawable) {
            Log.d("TAG", "Prepare Load");
        }
    });
}

【问题讨论】:

    标签: android picasso


    【解决方案1】:

    我已经有一段时间没有使用毕加索了,但在过去,目标是弱引用,你必须保持对它的硬引用(如果不再是这种情况,请原谅我,但杰克沃顿非常坚定关于“你必须保持一个硬引用或目标将被垃圾收集”的事情;可能是因为他被问了超过 9000 次同样的事情(包括我自己)。

    所以看看这个堆栈溢出响应似乎是同样的问题......

    https://stackoverflow.com/a/26918731/2684

    正如其他受访者(@lukas 和@mradzinski)所指出的,Picasso 只保留了对 Target 对象的弱引用。虽然您可以在其中一个类中存储强引用目标,但如果目标以任何方式引用视图,这仍然会出现问题,因为您还将有效地保持对该视图的强引用(这是其中之一毕加索明确帮助您避免的事情)。

    如果您遇到这种情况,我建议将目标标记到视图。

    【讨论】:

    • 所以我需要做的就是在我的 Activity 中保留一个 Target 作为成员变量,然后引用它?
    • 是的,例如。 :)
    • 拯救我的一天。请接受这个答案,它真的很有用
    【解决方案2】:

    我也遇到了这个问题,你应该用毕加索之类的...

    Picasso.Builder builder = new Picasso.Builder(this);
            builder.listener(new Picasso.Listener()
            {
                @Override
                public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception)
                {
                    exception.printStackTrace();
                }
            });
            builder.build().load(imgURL)
            .placeholder(R.drawable.ic_launcher)
            .into(imageIMG);
    

    【讨论】:

    • 我没有看到任何异常记录
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2018-08-20
    • 2014-05-04
    • 2018-09-02
    相关资源
    最近更新 更多