简体   繁体   中英

Nodes are getting created in Firebase everytime I click a button

Thanks for helping. I am creating an Android app which is working perfectly well. But I am facing a minor problem. The application contains message functionality for the posted ads. When the user opens an ad he is greeted with two options of call or message, where if the user clicks on the message button then he is sent to the chat screen, at the time of the button press the info gets stored in firebase database but I want the info to get stored only for the first time and if the users clicks the button next time then he should be taken to the pre-generated node, not on the new one.

Below is my code for adding the new nodes on the click of the button. Please lemme know if there is any way through which I can stop nodes from getting generated on every button click:

 mChat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent chatIntent = new Intent(ExpandActivity.this, ChatActivity.class);
                        chatIntent.putExtra("user_id", mId);
                        chatIntent.putExtra("user_name", mName);
                        chatIntent.putExtra("ad_id", user_id);
                        chatIntent.putExtra("cow", m);
                        startActivity(chatIntent);

                mRootRef.child("Chat").child(uid).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        DatabaseReference user_message_push = mRootRef.child("Chat").child(uid).push();

                        m = user_message_push.getKey();


                        if (!dataSnapshot.hasChild(user_id)) {
                            mRootRef.child("AdvertData").child(user_id).addValueEventListener(new 

ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                            if (dataSnapshot.exists()) {
                                                String image = dataSnapshot.child("image").getValue().toString();
                                                String title = dataSnapshot.child("title").getValue().toString();
                                                String price = dataSnapshot.child("price").getValue().toString();

                                                Map chatAddMap = new HashMap();
                                                chatAddMap.put("seen", false);
                                                chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
                                                chatAddMap.put("image", image);
                                                chatAddMap.put("title", title);
                                                chatAddMap.put("price", price);
                                                chatAddMap.put("chatUser", mName);
                                                chatAddMap.put("ads", user_id);
                                                chatAddMap.put("chatUserId", mId);


                                                 Map chatAddMap1 = new HashMap();
                                                chatAddMap1.put("seen", false);
                                                chatAddMap1.put("timestamp", ServerValue.TIMESTAMP);
                                                chatAddMap1.put("image", image);
                                                chatAddMap1.put("title", title);
                                                chatAddMap1.put("price", price);
                                                chatAddMap1.put("chatUser", name);
                                                chatAddMap1.put("ads", user_id);
                                                chatAddMap1.put("chatUserId", uid);


                                                Map chatUserMap = new HashMap();
                                                chatUserMap.put("Chats/" + uid + "/" + m, chatAddMap);
                                                chatUserMap.put("Chats/" + mId + "/" + m, chatAddMap1);


mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
                                                @Override
                                                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                                                    if (databaseError != null) {

                                                        Log.d("CHAT_LOG", databaseError.getMessage().toString());

                                                    }

                                                }
                                            });

Below is the picture of how my database looks like:

在此处输入图片说明

Here is the logic..! Use addListenerForSingleValueEvent . It is called only one time. And Get key only if snapshot doesn't exist

  DatabaseReference user_message_Ref = mRootRef.child("Chat").child(uid);
   // First check if snapshot exist()

     user_message_Ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if(dataSnapshot.exists())     
                    {
                         // GO TO THE DESIRED ACTIVITY
                       navigateToYOURActivity();

                    }else
                    {

                         // GET KEY 
                      String key = user_message_Ref.push().getKey();
                        // & UPDATE DATABASE                          
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

I want the info to get stored only for the first time and if the users clicks the button next time then he should be taken to the pre-generated node

It's probably because of addValueEventListener() .

You can try using addListenerForSingleValueEvent() which does this only one time i suppose.

When you are using the following lines of code:

DatabaseReference user_message_push = mRootRef.child("Chat").child(uid).push();
m = user_message_push.getKey();

You are generating a new random id at every button click. This is what push() method does. If you want the second time you click the button to access the same reference, you should store that id in a variable and use the same variable again, not generate another one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM