使用Picasso无法在应用程序中更新图像

时间:2018-07-15 14:59:07

标签: android firebase firebase-realtime-database firebase-storage picasso

当我尝试更新应用中的图片时,它不是在更新,而是在Firebase存储中更新 我很习惯

  

Picasso.get()。load(image).placeholder(R.drawable.profile).into(profileImage);

我也尝试过

  

Picasso.with(SetupActivity.class).load(image).placeholder(R.drawable.profile).into(profileImage);

这些是我的依赖项

    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.2'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-storage:16.0.1'

    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.+'

    implementation 'com.squareup.picasso:picasso:2.71828'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
public class SetupActivity extends AppCompatActivity {


    private EditText userName, fullName, countryName;
    private Button saveInformationButton;
    private CircleImageView profileImage;

    private FirebaseAuth mAuth;
    private DatabaseReference userRef;
    private StorageReference userProfileImageRef;


    private ProgressDialog loadingBar;


    String currentUserID;
    final  static  int Gallery_Pick = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);

        getSupportActionBar().setTitle("User Details");


        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        userRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);

        userProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");

        userName =(EditText)findViewById(R.id.setup_username);
        fullName =(EditText)findViewById(R.id.setup_full_name);
        countryName =(EditText)findViewById(R.id.setup_country_name);
        saveInformationButton = (Button)findViewById(R.id.setup_information_button);
        profileImage = (CircleImageView)findViewById(R.id.setup_profile_image);

        loadingBar = new ProgressDialog(this);


        saveInformationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                SaveAccountSetupInformation();
            }
        });

        profileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, Gallery_Pick);

            }
        });

        userRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


                if(dataSnapshot.exists())
                {
                    if (dataSnapshot.hasChild("profileimage"))
                    {
                        String image = dataSnapshot.child("profileimage").getValue().toString();
                        Picasso.get().load(image).placeholder(R.drawable.profile).into(profileImage);
                    }
                    else
                    {
                        Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_SHORT).show();
                    }
                }


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
        {
            Uri ImageUri = data.getData();

            CropImage.activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);
        }

        if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if(resultCode == RESULT_OK)
            {
                loadingBar.setTitle("Profile Image");
                loadingBar.setMessage("Please wait, while we updating your profile image...");
                loadingBar.show();
                loadingBar.setCanceledOnTouchOutside(true);

                Uri resultUri = result.getUri();

                StorageReference filePath = userProfileImageRef.child(currentUserID + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task)
                    {
                        if(task.isSuccessful())
                        {
//                            Toast.makeText(SetupActivity.this, "Profile Image updated...", Toast.LENGTH_SHORT).show();

                            final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();

                            userRef.child("profileimage").setValue(downloadUrl)
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task)
                                        {
                                            if(task.isSuccessful())
                                            {
                                                Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
                                                startActivity(selfIntent);

                                                Toast.makeText(SetupActivity.this, "Profile Image Updated...", Toast.LENGTH_SHORT).show();
                                                loadingBar.dismiss();
                                            }
                                            else
                                            {
                                                String message = task.getException().getMessage();
                                                Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
                                                loadingBar.dismiss();
                                            }
                                        }
                                    });
                        }
                    }
                });
            }
            else
            {
                Toast.makeText(this, "Error Occured: Image not uploaded, Try Again.", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

在毕加索尝试.memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE)

答案 1 :(得分:0)

Picasso确实会缓存图像,但是如果您的图像具有不同的URI,则会下载它,但是仍在缓存前一个图像,您可以“无效”以删除前一个图像,然后加载最近的图像。

Picasso.with(bContext).invalidate(bFileURI); //invalidates files

如果您的结构是如此,以至于您使用相同的URI覆盖了图像,并且您根本不希望它缓存,那么请继续

Picasso.with(bContext) .load(bImage_url) .memoryPolicy(MemoryPolicy.NO_CACHE) .networkPolicy(NetworkPolicy.NO_CACHE) .placeholder(R.drawable.default_img) .into(bImageView);

(我宁愿使后者无效,因为后者不是离线使用的好习惯)

由于使用的是Firebase,因此您也可以考虑将其保存为SharePreference中的字符串作为字符串以供离线使用...仍然是错误的做法。

final long bOneMB = 1024 * 1024;                               //size 
userProfileImageRef.getBytes(bOneMB)                           //get byte
    .addOnSuccessListener(new OnSuccessListener<byte[]>() {       // add listener
        @Override
        public void onSuccess(byte[] bytes) {                     // called if successful
            Bitmap bBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
            profileImage.setImageBitmap(bBitmap);                // sets bitmap in image view
        }
    });