实时数据库 orderbyByChild(timeStamp) 不工作 (android-java)
Posted
技术标签:
【中文标题】实时数据库 orderbyByChild(timeStamp) 不工作 (android-java)【英文标题】:Realtime database orderbyByChild(timeStamp) not working (android-java) 【发布时间】:2021-12-16 04:43:52 【问题描述】:这是我的数据结构
"Posts" :
"-MnL-M_t4hHrcaqWecDM" :
"description" : "",
"picture" : "",
"postKey" : "-MnL-M_t4hHrcaqWecDM",
"timeStamp" : 1635677993574,
"title" : "",
"userId" : "",
"userPhoto" : ""
,
"-MnL-xtVgZAC2TIY6Whn" :
"description" : "",
"picture" : "",
"postKey" : "",
"timeStamp" : 1635678150450,
"title" : "",
"userId" : "",
"userPhoto" : ""
,
我想删除具有旧时间戳的帖子。 我使用 equalTo 方法而不是 endAt 进行练习。 所以我使用这个代码
private void beginDelete()
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").equalTo("1635677993574");
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();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
else
Log.d("TAG",task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제안되었습니다.",Toast.LENGTH_SHORT).show();
);
所以我使用查询在帖子中指定“timeStamp”->“-MnL-M_t4hHrcaqWecDM”->“timeStamp” 像那样。但我认为“-MnL-M_t4hHrcaqWecDM”会产生问题。可以通过“-MnL-M_t4hHrcaqWecDM”子查询找到“timeStamp”吗?因为我可以使用 postKey 删除帖子.. 喜欢这里。
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("postKey").equalTo("-MDFJ23...");
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();
);
这是完整的代码。
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()
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").equalTo("1635677993574");
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();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
else
Log.d("TAG",task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제안되었습니다.",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】:您的timeStamp
属性是一个数字,不是一个字符串。
"timeStamp" : 1635677993574
所以要解决这个问题,请更改以下查询:
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").equalTo("1635677993574");
收件人:
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").equalTo(1635677993574);
实际搜索数字而不是字符串。看,没有双引号?
【讨论】:
有效!谢谢!以上是关于实时数据库 orderbyByChild(timeStamp) 不工作 (android-java)的主要内容,如果未能解决你的问题,请参考以下文章