我正在使用Firebase设置个人资料活动,用户可以在其中拍摄图像并将其设置为他们的个人资料图片。当用户选择图片时,它会上传到Firebase,但是,当我尝试使用Picasso检索图片并将其放入ImageView时,则不会显示。我已经仔细检查过我在调用正确的UI元素。我相信问题可能出在onDataChanged方法中。这是代码:
public class EditBio extends AppCompatActivity {
ImageView editPic;
EditText editUsername;
EditText editAge;
EditText editBio;
Button save;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
private ProgressDialog loadingBar;
private StorageReference UserProfileImageRef;
String currentUserId;
final static int galleryPic = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_bio);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Images");
editPic = findViewById(R.id.add_profile_pic);
editUsername = findViewById(R.id.edit_username);
editAge = findViewById(R.id.edit_age);
editBio = findViewById(R.id.edit_bio);
save = findViewById(R.id.save_profile);
loadingBar = new ProgressDialog(this);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveAccountInformation();
Intent intent = new Intent(EditBio.this, Profile.class);
startActivity(intent);
}
});
editPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//send user to phone gallery
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, galleryPic);
}
});
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String image = dataSnapshot.child("profileImage").getValue().toString();
//use Picasso to insert image
Picasso.get()
.load(image)
.placeholder(R.drawable.icon1)
.into(editPic);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
//Function to select and crop an image from gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == galleryPic && 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){
//store image in firebase storage
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait while we update 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 Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(EditBio.this, "Profile image saved successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
usersRef.child("profileImage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
//Intent intent = new Intent(EditBio.this, Profile.class);
//startActivity(intent);
Toast.makeText(EditBio.this, "Profile image stored to firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(EditBio.this, "Error occured when saving profile: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else {
Toast.makeText(this, "Error occured: Image cant be cropped. Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
//store account information in firebase
private void saveAccountInformation(){
String username = editUsername.getText().toString();
String age = editAge.getText().toString();
String bio = editBio.getText().toString();
if (TextUtils.isEmpty(username)){
Toast.makeText(this, "Please enter a user name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(age)){
Toast.makeText(this, "Please enter an age", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(bio)){
Toast.makeText(this, "Please enter a bio", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Saving Information");
loadingBar.setMessage("Please wait while we update your account information");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("age", age);
userMap.put("bio", bio);
usersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
SendUserToProfileActivity();
Toast.makeText(EditBio.this, "Your account information has been saved", Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
else{
String message = task.getException().getMessage();
Toast.makeText(EditBio.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
//send user to profile activity
private void SendUserToProfileActivity(){
Intent profileIntent = new Intent(this, Profile.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(profileIntent);
finish();
}
}
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditBio"
android:background="@drawable/gradient">
<ImageView
android:id="@+id/add_profile_pic"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:layout_marginTop="15dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_username"
android:layout_below="@+id/add_profile_pic"
android:layout_marginTop="80dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Username: "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_age"
android:layout_below="@+id/edit_username"
android:layout_marginTop="30dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Age: "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_bio"
android:layout_below="@+id/edit_age"
android:layout_marginTop="30dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Bio: "/>
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="@+id/save_profile"
android:layout_below="@+id/edit_bio"
android:background="@drawable/circle"
android:layout_marginTop="99dp"
android:text="Save"
android:textColor="@color/colorPrimary"
android:layout_centerInParent="true"/>
</RelativeLayout>
编辑 我尝试使用Glide而不是Picasso,但是仍然存在相同的问题。这是我写的代码
Glide.with(EditBio.this)
.load(image)
.apply(new RequestOptions()
.placeholder(R.drawable.icon1))
.into(editPic);
答案 0 :(得分:2)
而不是使用此行将上传的图像存储到Firebase数据库中,
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
使用此
final String downloadUrl = task.getDownloadUrl().toString();
如果问题仍然存在,那么我需要知道您在下面的行中获得了什么 image 值。
String image = dataSnapshot.child("profileImage").getValue().toString();
答案 1 :(得分:1)