【问题标题】:How do I save data in Firebase without overwriting current data?如何在不覆盖当前数据的情况下在 Firebase 中保存数据?
【发布时间】:2019-08-07 13:36:26
【问题描述】:

我希望允许用户在不覆盖存储在其 UID 下的信息的情况下发布大量帖子我知道随机生成密钥的推送方法,但我宁愿不使用它。一些帮助将不胜感激。在下面的方法中,我基本上将包含用户信息的字典保存到Firebase 实时数据库中。但是由于设置值方法,信息正在被替换。

数据库:

Post
 NEbIdbCumcOnIbPdUQxpwtV7Dr63 (UID)
 desc: "Toue moe"
 id:   "NEbIdbCumcOnIbPdUQxpwtV7Dr63"
 image: "Contains some image"
 name:  "Some name"
 profileimage:  "Image"

代码:

public void saveToFirebase() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Uploading...");
    progressDialog.show();
    //final String userId = mAuth.getCurrentUser().getUid();
    final StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("images").child(userId);
    storageRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
            if (task.isSuccessful()) {
                storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        url = uri.toString();
                        postDictionary.put("desc", descriptionEditText.getText().toString());
                        postDictionary.put("image", url);
                        postDictionary.put("id", userId);
                        postDictionary.put("name",name);
                        postDictionary.put("profileimage", profileImage);
                        productsDatabaseRef.child("Post").child(userId).setValue(postDictionary);
                        progressDialog.dismiss();
                        Intent intent = new Intent(Upload_Post.this, Shop_Activity.class);
                        startActivity(intent);
                        finish();
                    }
                    //handles error
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(Upload_Post.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });

            }
        }
    });
}

【问题讨论】:

  • 嘿阿伦,您可以使用 firebase updateChildren() 方法进行数据库参考
  • 嗨,我试过这样使用,但当前信息仍在被替换 productsDatabaseRef.child("Post").child(userId).updateChildren(postDictionary);
  • 显示你的 firebase 数据库节点
  • 我编辑了我的问题,请在上面查看。这就是它的结构。我基本上是在尝试让用户发布大量帖子并将信息保存在他们的 UID 下。
  • 嗯,我看到在您的 postDictionary 地图中,您包含了数据库节点中的所有内容。这就是为什么所有人都在替换

标签: android firebase firebase-realtime-database


【解决方案1】:

如果要允许每个用户上传多张图片,调用push()为每张图片生成一个新的子节点:

productsDatabaseRef.child("Post").child(userId).push().setValue(postDictionary);

调用push() 会生成一个所谓的push ID,它保证在所有客户端中都是唯一的。要了解有关这些 ID 的更多信息,请参阅The 2^120 Ways to Ensure Unique Identifiers

【讨论】:

    【解决方案2】:

    我也遇到了同样的问题。但我通过添加时间戳/日期来解决它。 只是一个想法! 这里...

    Post
     NEbIdbCumcOnIbPdUQxpwtV7Dr63 (UID):
             (CURRENT_TIME):
                  desc: "Toue moe"
                  id:   "NEbIdbCumcOnIbPdUQxpwtV7Dr63"
                  image: "Contains some image"
                  name:  "Some name"
                  profileimage:  "Image"
    
             (CURRENT_TIME):
                  desc: "Tou"
                  id:   "NEbIdbCumcOnIbPdUQxpwtV7Dr234"
                  image: "Contains some image"
                  name:  "Some name"
                  profileimage:  "Image"
    

    我的意思是在 uid 中创建一个子项作为(更新帖子的当前时间)。 然后在 current_time 中插入新帖子。

    实现将其添加到您的 java 文件中 -

    import java.text.SimpleDateFormat;
    import java.util.Date;
    

    //定义日期和时间并将其存储在 currenttime 变量中。

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        String currenttime = sdf.format(new Date());
    

    现在在此处进行如下更改...

     final StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("images").child(userId);
                storageRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
    
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        String currenttime = sdf.format(new Date());
    
    
    storageRef.child(currenttime).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() 
    
    
    
    {
                                @Override
                                public void onSuccess(Uri uri) {
                                    url = uri.toString();
                                    postDictionary.put("desc", descriptionEditText.getText().toString());
                                    postDictionary.put("image", url);
                                    postDictionary.put("id", userId);
                                    postDictionary.put("name",name);
                                    postDictionary.put("profileimage", profileImage);
                                    productsDatabaseRef.child("Post").child(userId).setValue(postDictionary);
                                    progressDialog.dismiss();
                                    Intent intent = new Intent(Upload_Post.this, Shop_Activity.class);
                                    startActivity(intent);
                                    finish();
                                }
    

    或者不添加时间戳,您可以添加数字来定义每个帖子,方法是将其插入到 for 循环中。 希望这会有所帮助!

    从 firebase 检索数据-

    final StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("images").child(userId);
    
    storageRef.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                                    for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) {
                    String[] date=dataSnapshot.getKey().toString(); //here you will get the date/time //this is an array to store all date/time inside userid
                     //for example, 2019.08.5 at 10:05:33
    
                        for(DataSnapshot dataSnapshot2:dataSnapshot1.getChildren()) {
                            //here u will get the values inside the date/time i.e desc,id,image,name,profileimage.
                            //code to retrieve the data will come here
                            }   
                    }
    

    【讨论】:

    • 您好,我实现了时间戳,我的数据库看起来像您描述的那样,如果我想使用新添加的时间戳访问 post 节点,我该怎么做?
    • 我已经添加了上面的信息来从 firebase 检索数据!!让我知道执行后的输出。在上面的代码中,我们在 userId 中创建了一个循环。第一个循环需要第一个日期,然后进入第二个循环并检索信息..然后再次进入第一个循环,依此类推。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    相关资源
    最近更新 更多