我使用 Firebase 存储来存储图像文件,当我尝试将其发送到实时数据库时,数据重写了整个数据,因此我现有的数据消失了,仅替换为图像 URL 数据。如何在不删除现有数据的情况下发送?
这是我的代码:
public class Utama extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
private Button uploadBTN;
private ImageView imageView;
private ProgressBar progressBar;
private TextView namapengguna, emailpengguna;
private View headerView;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private Uri imageUri;
private String userID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_utama);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
uploadBTN = findViewById(R.id.upload_btn);
progressBar = findViewById(R.id.progressBar);
imageView = findViewById(R.id.imageview);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
progressBar.setVisibility(View.INVISIBLE);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 2);
}
});
uploadBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (imageUri != null) {
uploadToFirebase(imageUri);
} else {
Toast.makeText(Utama.this, "Please Select Image", Toast.LENGTH_SHORT).show();
}
}
});
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference("Users");
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
final TextView fullNameTextView = (TextView) findViewById(R.id.fullName);
final TextView emailTextView = (TextView) findViewById(R.id.emailaddress);
root.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
fullNameTextView.setText(fullName);
namapengguna.setText(fullName);
emailTextView.setText(email);
emailpengguna.setText(email);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(Utama.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
private void uploadToFirebase(Uri uri) {
StorageReference fileRef = reference.child(System.currentTimeMillis() + "." + getFileExtension(uri));
fileRef.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
final Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()){
HashMap<String,Object> result = new HashMap<>();
result.put(userID,downloadUri.toString());
root.child(userID).updateChildren(result).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
progressBar.setVisibility((View.INVISIBLE));
Toast.makeText(Utama.this, "Your Profile succesfully changed", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.ic_add_photo);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(Utama.this, "", Toast.LENGTH_SHORT).show();
}
});
}
// fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
// @Override
// public void onSuccess(Uri uri) {
// Model model = new Model(uri.toString());
// String modelId = root.push().getKey();
//// root.child(userID).child(modelId).setValue(model);
// root.child(userID).child(modelId).setValue(model);
// progressBar.setVisibility(View.INVISIBLE);
// Toast.makeText(Utama.this, "Upload Succesfully", Toast.LENGTH_SHORT).show();
// imageView.setImageResource(R.drawable.ic_add_photo);
// }
// });
}
})
// .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
// @Override
// public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
// progressBar.setVisibility(View.VISIBLE);
// }
// })
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(Utama.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private String getFileExtension(Uri mUri) {
ContentResolver cr = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cr.getType(mUri));
}
public void ClickMenu(View view) {
Dashboard.openDrawer(drawerLayout);
}
public void ClickLogo(View view) {
Dashboard.closeDrawer(drawerLayout);
}
public void ClickHome(View view) {
Dashboard.redirectActivity(this, Dashboard.class);
}
public void ClickUtama(View view) {
recreate();
}
public void ClickAboutUs(View view) {
Dashboard.redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout (this);
}
private void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void onPause() {
super.onPause();
Dashboard.closeDrawer(drawerLayout);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
return false;
}
}
这是给Model
:
public class Model {
private String imageUrl;
public String fullname, email;
public Model (){
}
public Model(String imageUrl){
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
答案 0 :(得分:0)
您必须使用 setValue 将值设置为您的实时数据库。 您当前使用的方法替换 userId 下已完成的数据,但如果您希望更新特定字段,则应该
root.child("users").child(userId).setValue(user)
使用类似的东西。
答案 1 :(得分:0)
这里是我如何重命名图像的问题
无需重命名图像。您甚至可以从一开始就正确更新它。当您向 Firebase 添加数据时,您的结构如下所示:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- email: "test@gmail.com"
|
--- fullname: "Test"
现在,要在 UID 的节点中添加一个名为“imageUrl”的新属性,该属性可以保存照片的实际 URL,请更改以下代码行:
result.put(userID,downloadUri.toString());
致:
result.put("imageUrl",downloadUri.toString());
这样,您的第一个孩子将不会被添加为:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- Pp3Cc... smV2: "https://" //Incorrect
|
--- email: "test@gmail.com"
|
--- fullname: "Test"
但是作为:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- imageUrl: "https://" //Correct
|
--- email: "test@gmail.com"
|
--- fullname: "Test"