I want to set value of counter to every post user made and it saved to database.
so in recycler view i can PostRef.orderByChild("counter");
User 1 post then set value start of counter 0 then other user or the same user posted
The value of the counter should be 1 then 2, 3, 4, 5 etc (it should count with getChildrenCount();
but it doesn't work, why? it shows number 9
I also put StoringPostToFirebaseStorage();
under the countPosts = dataSnapshot.getChildrenCount();
line at it works for counting 1, 2, 3 but it also updates the old post to the same number as the new one that was just posted.
Am I coding it wrong?
PostsRef:
PostsRef = FirebaseDatabase.getInstance().getReference().child("posts");
the counter:
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) {
}
});
}
the 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();
}
}
});
}
The Database Image