我想为每个发帖的用户设置counter的值,并将其保存到数据库中。
因此在回收者视图中,我可以PostRef.orderByChild("counter");
用户1发布,然后设置计数器0的值开始,然后其他用户或同一用户发布
计数器的值应为1,然后为2、3、4、5等(应使用getChildrenCount();
进行计数但它不起作用,为什么?它显示数字9
我也将StoringPostToFirebaseStorage();
放在countPosts = dataSnapshot.getChildrenCount();
行下,它的作用是计数1、2、3,但是它还将旧帖子更新为与刚发布的新帖子相同的编号。 / p>
我编码错了吗?
PostsRef:
PostsRef = FirebaseDatabase.getInstance().getReference().child("posts");
柜台:
private void CounterPosts() {
PostsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
countPosts = dataSnapshot.getChildrenCount();
} else {
countPosts = 0;
}
StoringPostToFirebaseStorage();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
StoringPostToFirebaseStorage();
private void StoringPostToFirebaseStorage() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitudesave = location.getLongitude();
latitudesave = location.getLatitude();
//edit test 1 HashMap<String, Object> postsMap = new HashMap<>();
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("posttext", PostIntiText);
postsMap.put("date", saveCurrentDateForUser);
postsMap.put("time", saveCurrentTimeForUser);
postsMap.put("postimage", downloadImageUrl);
postsMap.put("longitude", longitudesave);
postsMap.put("latitude", latitudesave);
postsMap.put("district", district);
postsMap.put("city", city);
postsMap.put("counter", countPosts);
PostsRef.child(current_user_id + postRandomKey).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener < Void > () {
@Override
public void onComplete(@NonNull Task < Void > task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(PostActivity.this, "Posted successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String errormessage = task.getException().toString();
Toast.makeText(PostActivity.this, "Error:" + errormessage, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
数据库映像