Search code examples
androidpicasso

how to make picasso display default image when there is an invalid path


I am having one issue on display a default image name here R.drawable.avatar_placeholder. When the link from webservice is non empty, but error 404. means there isn't any image on that link path. Which if i run this function below, the string "path not empty" is shown, but it failed to display the image. Any suggestion is welcomed. Thanks.

private void loadProfileDetails() {
        Logger.d(UI_LoginFragmentWithPin.class, "loadProfileDetails profile image: " + PrefUtils.readString(Constant.PREF_PROFILE_IMAGE));
        if (!TextUtils.isEmpty(PrefUtils.readString(Constant.PREF_PROFILE_IMAGE))){
            Utils.println("path not empty");
            LPicasso.getInstance(getActivity())
                    .load(PrefUtils.readString(Constant.PREF_PROFILE_IMAGE))
                    .config(Bitmap.Config.RGB_565)
                    .resize(200, 200)
                    .centerCrop()
                    .into(imgProfile);
        }else {
            Utils.println("path empty");
            LPicasso.getInstance(getActivity())
                    .load(R.drawable.avatar_placeholder)
                    .config(Bitmap.Config.RGB_565)
                    .resize(200, 200)
                    .centerCrop()
                    .into(imgProfile);

        }
        tvEmail.setText(PrefUtils.readString(Constant.PREF_EMAIL));
        tvName.setText(PrefUtils.readString(Constant.PREF_USER_NAME) + " " + PrefUtils.readString(Constant.PREF_USER_SURNAME));
    }

Solution

  • Try this,

    Set error image as your place holder image

        if(!PrefUtils.readString(Constant.PREF_PROFILE_IMAGE).equals("")) 
        {
            Picasso.with(context).load(PrefUtils.readString(Constant.PREF_PROFILE_IMAGE)).resize(200,200).centerCrop().error(R.drawable.avatar_placeholder).into(imgProfile);
        }
        else
        {
            Picasso.with(context).load(R.drawable.avatar_placeholder).error(R.drawable.avatar_placeholder).resize(200,200).centerCrop().into(imgProfile);
        }
    

    gradle:

        compile 'com.squareup.picasso:picasso:2.5.2'