如何在不覆盖当前数据的情况下将数据保存在Firebase中?

时间:2019-08-01 01:42:41

标签: android firebase firebase-realtime-database

我希望允许用户发表大量帖子而不覆盖其UID下存储的信息,我知道随机生成密钥的push方法,但我宁愿不使用它。一些帮助将不胜感激。在下面的方法中,我基本上将包含用户信息的字典保存到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();

                    }
                });

            }
        }
    });
}

2 个答案:

答案 0 :(得分:0)

我也有同样的问题。但我通过添加时间戳/日期解决了。 只是一个主意! 在这里...

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
                        }   
                }

答案 1 :(得分:0)

如果要允许每个用户上传多个图像,请调用x为每个图像生成一个新的子节点:

push()

呼叫productsDatabaseRef.child("Post").child(userId).push().setValue(postDictionary); 会产生一个所谓的push(),这可以保证在所有客户端上都是唯一的。要了解有关这些ID的更多信息,请参见The 2^120 Ways to Ensure Unique Identifiers

相关问题