這是我的實時資料庫資料
"Posts" : {
"-MCCtOfEcs-t8OhKAj_R" : {
"description" : "",
"picture" : "https://firebasestorage.googleapis.com/v0/b/instagram-c0686.appspot.com/o/blog_images/image:22222?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/image:22222?alt=media&token=c92b64ff-c2f6-4076-949a-b176253f0497",
"postKey" : "-MCCtPZxoFEChRczT9nY",
"timeStamp" : 1594739763718,
"title" : "",
"userId" : "1tXK0R5B9uOWyAbzlZMEIs6axHo1"
},
我想使用 equalTo timeStamp 變數洗掉帖子。所以我寫了一個代碼。
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;
}
}
uj5u.com熱心網友回復:
如果你想洗掉的第一個節點(-MCCtOfEcs-t8OhKAj_R),在“帖子”節點存在,請注意,有沒有必要進行查詢。由于節點的鍵與postKey欄位的值相同,因此您只需使用以下代碼行:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
db.child("Posts").child("-MCCtOfEcs-t8OhKAj_R")).removeValue();
我還建議您為removeValue()操作附加一個完整的偵聽器,以查看是否出現問題。如果您沒有正確的規則,則會拋出例外。
編輯:
根據你最后的評論:
我想洗掉具有舊時間戳的實體。
在這種情況下,您確實需要使用查詢。例如,如果您需要洗掉特定時間戳之前的子項,則可以使用Query#endAt()方法,該方法:
創建一個限制為僅回傳值小于或等于給定值的子節點的查詢,使用給定的 orderBy 指令或優先級作為默認值,另外只回傳鍵小于或等于給定鍵的子節點。
這是一個作業示例:
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!
}
}
});
此查詢的結果將是洗掉之前存在的所有子項1615602220595。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342784.html
標籤:爪哇 安卓 火力基地 Firebase 实时数据库 谷歌云平台
上一篇:在類建構式中使用列舉
