Shmebulouk
Shmebulouk

Reputation: 13

variable keeps being 0

I am using firebase database and I am trying to create some sort of an index for each one of my childs - enter image description here

the index itself does update but under the posts section it keeps being 0, this is the code that is responsible for updating the index

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference indexReference =ref.child("postNum");
indexReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if(snapshot.getValue()==null){
            tempIndex = 0;
        }
        else {
            tempIndex =(Long) snapshot.getValue();
            Log.d("read", String.valueOf(tempIndex));
        }
        snapshot.getRef().setValue(tempIndex+1);
        Log.d("temp", String.valueOf(tempIndex));
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
    }
});

this is the code i use to upload new posts to firebase

Post post =new Post(etProductName.getText().toString(), date,btChooseLocation.getText().toString(),etProductPrice.getText().toString(),etProductDescription.getText().toString(),uuidImage,uid, tempIndex);
            FirebaseDatabase.getInstance().getReference("Posts").child(uuidPost).setValue(post);

Upvotes: 0

Views: 53

Answers (2)

niranj1997
niranj1997

Reputation: 872

The below solution might help you

Post post =new Post(etProductName.getText().toString(),date ,btChooseLocation.getText().toString(), etProductPrice.getText().toString(), etProductDescription.getText().toString(), uuidImage, uid, tempIndex);
    
//Before setting, check your POST object by printing it
//ref.child("Posts").child(yourPostID).setValue(post);

ref.child("Posts").child("a1d03799-6146-4776-9d69-73b8d9d7ae61").setValue(post);

Upvotes: 0

t3ddys
t3ddys

Reputation: 155

The problem is that your reference to postNum inside Posts table is wrong. You need to change it to ref.child("Posts").child(PostID).child("postNum");

Upvotes: 1

Related Questions