Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

java - setValue Inside onDataChange

I try to set a new value from inside onDataChange on firebase but when i try to set a new value on a variable inside real-time database the android studio mark the setValue() method with red and says Cannot resolve method 'setValue' in 'DataSnapshot'

Here is the part of my code:

like_btn.setImageResource(R.drawable.like_emoji);
                    postRef.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            // get post id \
                            PostModel postModel = new PostModel();
                            String post_id = postModel.getId();

                            // get current likes from db \
                            String currentLikes = snapshot.child(post_id).child("likes").getValue().toString();
                            int currentLikesToInt = Integer.parseInt(currentLikes);

                            // set new current likes on db \
                            int newCurrentLikes = currentLikesToInt + 1;
                            snapshot.child(post_id).child("likes").setValue(newCurrentLikes);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                            Toast.makeText(itemView.getContext(), "Error: " + error, Toast.LENGTH_LONG).show();
                        }
                    });
question from:https://stackoverflow.com/questions/65921359/setvalue-inside-ondatachange

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot use setValue() on DataSnapshot , which is the value firebase just retrieved for you. What you need to do is use your database reference. In this case, it would be something like this:

postRef.child(post_id).child("likes").setValue(yourValue);

Hoping that postRef is a reference to a database where post_id and likes can be found. For more information on this read Firebase documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...