Home » Android » How to add +1 in firebase when img is click android

How to add +1 in firebase when img is click android

Posted by: admin November 1, 2017 Leave a comment

Questions:

This is my code. I have two android phones and two accounts, but when I click the image1, which is pres1 and click on the other phone, it doesn’t stack. It remains 1 in the firebase.

Could anyone show me how to do it properly?

Thank you

private ImageView pres1, pres2;

long count;

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference("VoteResults");
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vote_now);

    pres1 = (ImageView) findViewById(R.id.vote_president1);
    pres2 = (ImageView) findViewById(R.id.vote_president2);

    pres2.setOnClickListener(this);
    pres1.setOnClickListener(this);
}

@Override
public void onClick(View view) {

    if(view.getId() == R.id.vote_president1){

        final DatabaseReference mCounterRef = mRootRef.child("VotePresident");
        mCounterRef.setValue(++count);
        startActivity(new Intent(VoteNow.this,VicePresInternal.class));
        finish();
    }else if(view.getId() == R.id.vote_president2) {
        final DatabaseReference mCounterRef = mRootRef.child("VotePresident2");
        mCounterRef.setValue(++count);
        startActivity(new Intent(VoteNow.this, VicePresInternal.class));
        finish();
    }
}
Answers:

Then you are working with firebase, the best way is to working with POJO models – Plain Old Java Object.

So, you have to create POJO class

@IgnoreExtraProperties
    public class President {

        public String uuid = "XXXX-XXXX-XXXX-XXXX";
        public int voteCount = 0;

        public Post() {
            // Default constructor required for calls to 
            DataSnapshot.getValue(Post.class)
        }

        public President(String uuid) {
            this.uuid = uuid;
        }
    }

And then you can work with DataSnapshot class, of course if added addValueEventListener() to you database reference

ValueEventListener voteListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Get Post object and use the values to update the UI
        President president = dataSnapshot.getValue(President.class);
        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
mRootRef.addValueEventListener(postListener);