当前位置: 首页 > 知识库问答 >
问题:

在firebase实时数据库中按时间戳删除邮件

房星光
2023-03-14
 "Posts" : {
"-MCCtOfEcs-t8OhKAj_R" : {
  "description" : "",
  "picture" : "https://firebasestorage.googleapis.com/v0/b/instagram-c0686.appspot.com/o/blog_images%2Fimage%3A22222?alt=media&token=eb7ffc1f-f7bd-4ab7-a108-5baf92e3ef47",
  "postKey" : "-MCCtOfEcs-t8OhKAj_R",
  "timeStamp" : 1594739760019,
  "title" : "",
  "userId" : "1tXK0R5B9uOWyAbzlZMEIs6axHo1"
},
"-MCCtPZxoFEChRczT9nY" : {
  "description" : "",
  "picture" : "https://firebasestorage.googleapis.com/v0/b/instagram-c0686.appspot.com/o/blog_images%2Fimage%3A22222?alt=media&token=c92b64ff-c2f6-4076-949a-b176253f0497",
  "postKey" : "-MCCtPZxoFEChRczT9nY",
  "timeStamp" : 1594739763718,
  "title" : "",
  "userId" : "1tXK0R5B9uOWyAbzlZMEIs6axHo1"
},

我想使用equalTo时间戳变量删除一篇文章。所以我做了一个密码。

Query fquery =FirebaseDatabase.getInstance().getReference("Posts").orderByChild("timeStamp").equalTo("1615602220595");

但我不知道为什么不工作..当我这样做的时候

Query fquery =FirebaseDatabase.getInstance().getReference("Posts").orderByChild("postKey").equalTo("-MCCtOfEcs-t8OhKAj_R");

奏效了。

public class PostDetailActivity extends AppCompatActivity {

ImageView imgPost,imgUserPost,imgCurrentUser;
TextView txtPostDesc,txtPostDateName,txtPostTitle;
EditText editTextComment;
Button btnAddComment;
String PostKey;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
RecyclerView RvComment;
CommentAdapter commentAdapter;
List<Comment> listComment;
static String COMMENT_KEY = "Comment";
InputMethodManager imm;
EditText et;
Button btnDeletePost;
String myUid;
String UId;
String postImage;
private DatabaseReference mDatabase;







@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post_detail);
    imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    et = (EditText)findViewById(R.id.post_detail_comment);



    // let's set the statue bar to transparent


    // ini Views
    RvComment = findViewById(R.id.rv_comment);
    imgPost =findViewById(R.id.post_detail_img);
    imgUserPost = findViewById(R.id.post_detail_user_img);
    imgCurrentUser = findViewById(R.id.post_detail_currentuser_img);

    txtPostTitle = findViewById(R.id.post_detail_title);
    txtPostDesc = findViewById(R.id.post_detail_desc);
    txtPostDateName = findViewById(R.id.post_detail_date_name);

    editTextComment = findViewById(R.id.post_detail_comment);
    btnAddComment = findViewById(R.id.post_detail_add_comment_btn);
    btnDeletePost = findViewById(R.id.button_delete);


    firebaseAuth = FirebaseAuth.getInstance();
    firebaseUser = firebaseAuth.getCurrentUser();
    firebaseDatabase = FirebaseDatabase.getInstance();
    // add post delete button
    mDatabase= FirebaseDatabase.getInstance().getReference();

    myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();

    btnDeletePost.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //여기 수정 주의 UId.equals(myUid)
            if (true){
                Toast.makeText(PostDetailActivity.this,"삭제중...",Toast.LENGTH_SHORT).show();
                beginDelete();
                onBackPressed();
            }
            else{
                Toast.makeText(PostDetailActivity.this,"다른 사용자의 게시글입니다.",Toast.LENGTH_SHORT).show();
            }
        }
    });

    // add Comment button click listner

    btnAddComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            btnAddComment.setVisibility(View.INVISIBLE);
            DatabaseReference commentReference = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey).push();
            String comment_content = editTextComment.getText().toString();
            String uid = firebaseUser.getUid();
            String uname = firebaseUser.getDisplayName();
            if (firebaseUser.getPhotoUrl()!=null){
                String uimg = firebaseUser.getPhotoUrl().toString();
                Comment comment = new Comment(comment_content,uid,uimg,uname);
                commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        showMessage("comment added");
                        editTextComment.setText("");
                        btnAddComment.setVisibility(View.VISIBLE);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        showMessage("fail to add comment : "+e.getMessage());
                    }
                });

            }
            else{
                String usphoto =Integer.toString(R.drawable.userphoto);
                Comment comment = new Comment(comment_content,uid,usphoto,uname);
                commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        showMessage("comment added");
                        editTextComment.setText("");
                        btnAddComment.setVisibility(View.VISIBLE);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        showMessage("fail to add comment : "+e.getMessage());
                    }
                });
            }




        }
    });


    // now we need to bind all data into those views
    // firt we need to get post data
    // we need to send post detail data to this activity first ...
    // now we can get post data



    // 게시글 사진 백지 케이스
    postImage = getIntent().getExtras().getString("postImage") ;
    if(postImage!=null){
        Glide.with(this).load(postImage).into(imgPost);
    }
    else{
        Glide.with(this).load(R.drawable.whitepaper).into(imgPost);
    }


    String postTitle = getIntent().getExtras().getString("title");
    txtPostTitle.setText(postTitle);

    String userpostImage = getIntent().getExtras().getString("userPhoto");
    if (userpostImage!=null){
        Glide.with(this).load(userpostImage).into(imgUserPost);
    }
    else {
        Glide.with(this).load(R.drawable.userphoto).into(imgUserPost);
    }

    String postDescription = getIntent().getExtras().getString("description");
    txtPostDesc.setText(postDescription);

    // set comment user image
    if (firebaseUser.getPhotoUrl()!=null){
        Glide.with(this).load(firebaseUser.getPhotoUrl()).into(imgCurrentUser);
    }
    else{
        Glide.with(this).load(R.drawable.userphoto).into(imgCurrentUser);
    }
    // get post key
    PostKey = getIntent().getExtras().getString("postKey");

    String date = timestampToString(getIntent().getExtras().getLong("postDate"));
    txtPostDateName.setText(date);
    // get post uid
    UId = getIntent().getExtras().getString("userId");



    // ini Recyclerview Comment
    iniRvComment();


}

private void beginDelete() {

    StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(postImage);
    picRef.delete()
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    //image deleted, now delete database
                    Query fquery =FirebaseDatabase.getInstance().getReference("Posts").orderByChild("timeStamp").equalTo("1615602220595");
                    fquery.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            for (DataSnapshot ds:dataSnapshot.getChildren()){
                                ds.getRef().removeValue(); // remove values from firebase where postkey matches
                            }
                            //Deleted
                            Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
                        }

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

                        }
                    });

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //failed, can't go further
                    Toast.makeText(PostDetailActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });

}

public void linearOnClick(View v) {
    imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}


private void iniRvComment() {

    RvComment.setLayoutManager(new LinearLayoutManager(this));

    DatabaseReference commentRef = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey);
    commentRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            listComment = new ArrayList<>();
            for (DataSnapshot snap:dataSnapshot.getChildren()) {

                Comment comment = snap.getValue(Comment.class);
                listComment.add(comment) ;

            }

            commentAdapter = new CommentAdapter(getApplicationContext(),listComment);
            RvComment.setAdapter(commentAdapter);


        }

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

        }
    });




}

private void showMessage(String message) {

    Toast.makeText(this,message,Toast.LENGTH_LONG).show();

}


private String timestampToString(long time) {

    Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
    calendar.setTimeInMillis(time);
    String date = DateFormat.format("yyyy-MM-dd",calendar).toString();
    return date;


}

}

共有1个答案

苗烈
2023-03-14

如果要删除“posts”节点中存在的第一个节点(-mcctofecs-t8ohkaj_r),请注意不需要执行查询。由于节点的键与postkey字段的值相同,因此只需使用以下代码行:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
db.child("Posts").child("-MCCtOfEcs-t8OhKAj_R")).removeValue();

我还建议您在removeValue()操作中附加一个完整的监听器,以查看是否出错。如果您没有适当的规则,那么将引发异常。

编辑:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt("1615602220595");
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                ds.getRef().removeValue();
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});
 类似资料:
  • 我以为上面的办法行得通,但它失败了。我把它放在渲染行部分。它出现了reference.remove失败。第一个参数必须是有效的函数。就像在这些房间里,它有信息,我认为这是我出错的地方,但我不知道如何去做它。谢谢。

  • 我在我的react本地应用程序中使用Firebase实时数据库。大多数事情都是通过REST API云函数来完成的。app中很少东西直接使用实时数据库。最近,我发现我数据库中的所有数据都被莫名其妙地删除了。甚至数据库中不再使用且未在我的应用程序/云功能的源代码中引用的部分也消失了。 问题发生在两个项目及其数据库(生产/测试)中。我必须使用备份来恢复它们,但即使没有人使用应用程序(例如,在测试环境中)

  • 我如何删除记录“苹果”(在图片中标记)? 根据文档,要移除一个项,需要对引用调用removeValue()。但要获得引用,我需要子ID。因为它是一个随机生成的id(-kisnx87ayigsh3ilp0d),如何删除它?

  • 我仍在开发我的登录应用程序。此时,用户可以注册、登录和更新配置文件信息。数据存储在firebase实时数据库中,该装置也通过firebase工作。我想添加一个“删除配置文件”按钮,以便从firebase中删除用户信息。我弄清楚了如何从自动认证过程中删除用户。现在我尝试对Uid调用remove()函数,因此现在数据在实时数据库中被删除,但仍在Firebase身份验证中,如果删除userdata,应用

  • 从android工作室按特定值删除记录的适当代码是什么。 必需:如果starCount字段等于0,则删除所有记录。

  • 我在Firebase上运行一个web应用程序,从实时数据库开始,现在我正在将数据迁移到firestore。 我使用ADMINSDK迁移了除时间戳之外的所有其他数据。在我的web应用程序中,当用户上传新内容时,代码会向数据库添加时间戳,以便内容可以按时间排序。 问题在于实时数据库和firestore显然在记录时间戳时使用了不同的方法: 另一个问题是firebase.firestore.Timesta