【问题标题】:I am unable to load two different pictures in two different Image Views我无法在两个不同的图像视图中加载两个不同的图片
【发布时间】:2021-02-20 21:04:19
【问题描述】:

应该发生什么:

  • 用户应该能够将图片上传到 Image View_1。
  • 用户应该能够将图片上传到 Image View_2。
  • 应同时显示两张不同的图片。

实际发生了什么:

  • 如果用户将图片上传到 Image View_1,则 Image View_1 和 Image View_2 会变为同一张图片。
  • 如果用户将图片上传到 Image View_2,则 Image View_2 和 Image View_1 会变为同一张图片。

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import de.hdodenhof.circleimageview.CircleImageView;


public class Personal_Wall_Edit extends AppCompatActivity {
    private String currentUserID;
    private DatabaseReference UsersReference;
    private CircleImageView profile_image;
    private StorageReference UserProfileImageRef;
    private FirebaseAuth mAuth;
    private ImageButton edit_banner_button;
    private ImageButton edit_profile_button;
    private ProgressBar mProgressBar;
    private ImageView bannerimage;
    private StorageReference UserBannerImageRef;
    private DatabaseReference mDatabaseRef;
    final static int Gallery_Pick = 1;
    final static int Gallery_Pick2 = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal__wall__edit);
        Toolbar toolbar = findViewById(R.id.toolbar2);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Back to Profile");
        getSupportActionBar().setLogo(R.drawable.ic_arrow_left_black);
        toolbar.setClickable(true); //this tells our system to actually use the toolbar as the actionbar.
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
        edit_banner_button = findViewById(R.id.edit_profile_banner_button);
        edit_profile_button = findViewById(R.id.edit_profile_pic_button);
        mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");


        //Banner Image Section for Firebase//
        UserBannerImageRef = FirebaseStorage.getInstance().getReference().child("bannerimages");
        bannerimage = findViewById(R.id.temporary_banner_edit);
        //Banner Image Section for Firebase//


        //Profile Image Section for Firebase//
        UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
        profile_image = findViewById(R.id.profile_place_holder_edit);
        //Profile Image Section for Firebase//






        /////Profile Banner Editing//////////////////////////////////////////////////////

        edit_banner_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*"); //this will only choose images from the gallery and not videos, etc...//
                startActivityForResult(galleryIntent, Gallery_Pick);

            }
        });

        /////Profile Banner Editing//////////////////////////////////////////////////////










        /////Profile Picture Editing//////////////////////////////////////////////////////
        edit_profile_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent2 = new Intent();
                galleryIntent2.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent2.setType("image/*"); //this will only choose images from the gallery and not videos, etc...//
                startActivityForResult(galleryIntent2, Gallery_Pick2);

            }
        });


        /////Profile Picture Editing//////////////////////////////////////////////////////










        // (Below) In the toolbar, there is a button that will send the user back to the profile page from the edit profile page.//
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Send_User_Back_to_Profile_Page_View_Activity();

            }
        });
        // (Above) In the toolbar, there is a button that will send the user back to the profile page from the edit profile page.//








        //(Below) This should pull in the profile picture was taken on the ad-more_info after registration page//
        UsersReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {

                    String myProfileImage = dataSnapshot.child("profileimage").getValue().toString();
                    Picasso.get().load(myProfileImage).placeholder(R.drawable.profile_place_holder).into(profile_image);


                }


            }

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

            } //Above is the Value Event Listener. This is what you can use to retrieve data (or in this case- images that have already been stored into the Firebase Database.//

        });
        // (Above) This should pull in the profile picture was taken on the ad-more_info after registration page//


////////[BANNERE-PICTURE]-Below is the method for saving the Banner Image- like retrieving it from Firebase//
        UsersReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    if (dataSnapshot.hasChild("banner_images")) {

                        String myBannerImage = dataSnapshot.child("banner_images").getValue().toString();
                        Picasso.get().load(myBannerImage).placeholder(R.drawable.ic_hapana_banner_2).into(bannerimage);


                    } else {
                        Toast.makeText(Personal_Wall_Edit.this, "Please select profile image first.", Toast.LENGTH_SHORT).show();
                    }
                }


            }

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

            } //Above is the Value Event Listener. This is what you can use to retrieve data (or in this case- images that have already been stored into the Firebase Database.//

        });
        /////[BANNER_PICTURE]-(Above) This should pull in the banner picture that the user selected//









        ////////[PROFILE_PICTURE]-Below is the method for saving the Profile Image- like retrieving it from Firebase//
        UsersReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    if (dataSnapshot.hasChild("profileimage")) {

                        String myProfileImage = dataSnapshot.child("profileimage").getValue().toString();
                        Picasso.get().load(myProfileImage).placeholder(R.drawable.profile_place_holder).into(profile_image);


                    } else {
                        Toast.makeText(Personal_Wall_Edit.this, "Error", Toast.LENGTH_SHORT).show();
                    }
                }


            }

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

            } //Above is the Value Event Listener. This is what you can use to retrieve data (or in this case- images that have already been stored into the Firebase Database.//

        });
        //////[PROFILE_PICTURE]- (Above) This should pull in the Profile picture that the user selected//


    }









//////Sending User Back To the Personal Wall Activity////////////////////////////////////////////////////////
    private void Send_User_Back_to_Profile_Page_View_Activity() {
        Intent send_back_profile_page = new Intent(Personal_Wall_Edit.this, Personal_Wall.class);
        startActivity(send_back_profile_page);
        finish();
    }

//////Sending User Back To the Personal Wall Activity////////////////////////////////////////////////////////












    //////Adding [BANNER/PROFILE PICTURE] to Firebase Database and Displaying it On the Page/////////////////////////////
    @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(imageUri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);


        }

        // when pressing the crop button//
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {


                Uri resultUri = result.getUri();


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


                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {

                            Toast.makeText(Personal_Wall_Edit.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
                            Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();

                            result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    final String downloadUrl = uri.toString();


                                    UsersReference.child("banner_images").setValue(downloadUrl)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {


                                                        Toast.makeText(Personal_Wall_Edit.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        String message = task.getException().getMessage();
                                                        Toast.makeText(Personal_Wall_Edit.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                    }

                                                }


                                            });
                                }

                            });
                        }
                    }
                });

            } else {
                Toast.makeText(Personal_Wall_Edit.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();

            }


        }






        //////////////////////////PROFILE_PICTURE_SECTION////////////////////////////////////////////
        else if (requestCode == Gallery_Pick2 && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();


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


        }



        // when pressing the crop button//
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);


            if (resultCode == RESULT_OK) {


                Uri resultUri = result.getUri();


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

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {

                            Toast.makeText(Personal_Wall_Edit.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
                            Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();

                            result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    final String downloadUrl = uri.toString();


                                    UsersReference.child("profileimage").setValue(downloadUrl)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {

                                                        Toast.makeText(Personal_Wall_Edit.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        String message = task.getException().getMessage();
                                                        Toast.makeText(Personal_Wall_Edit.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                    }

                                                }


                                            });
                                }
                            });
                        }
                    }
                });
            } else {
                Toast.makeText(Personal_Wall_Edit.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
            }
        }


    }
}

    //////Adding [BANNER/PROFILE_PICTURE] to Firebase Database and Displaying it On the Page/////////////////////////////

【问题讨论】:

    标签: android firebase picasso


    【解决方案1】:

    您的代码不完整,但您似乎将 两个 ValueEventListener 附加到 UsersReference。因此,每次您上传任何图像时,都会调用ValueEventListener。尝试在单个 ValueEventListener 中创建一些检查条件来更新您的每个 ImageView

    【讨论】:

    • 谢谢鲁本。我编辑了上面的代码,现在查看 ValueEventListener。
    • 嗨鲁本,我实际上无法弄清楚要向 ValueEventListener 添加什么。你有什么建议或教程可以指出吗?我尝试在网上查找,但在找到解决方案时遇到了困难。谢谢。
    • 你已经添加了两次UsersReference.addValueEventListener(new ValueEventListener() {...},应该是一次
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多