简体   繁体   English

每次单击按钮时,都会在Firebase中创建节点

[英]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. 我正在创建一个运行良好的Android应用。 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. 当用户打开广告时,会收到两个呼叫或消息选项,其中,如果用户单击消息按钮,则将其发送到聊天屏幕,在按下按钮时,信息将存储在Firebase数据库中,但是我希望信息仅是第一次存储,如果用户下次单击该按钮,则应将其带到预先生成的节点上,而不是新的节点上。

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 . 使用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() . 这可能是由于addValueEventListener()

You can try using addListenerForSingleValueEvent() which does this only one time i suppose. 您可以尝试使用addListenerForSingleValueEvent() ,我猜这只能执行一次。

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. 您每次单击按钮都会生成一个新的随机ID。 This is what push() method does. 这就是push()方法的作用。 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. 如果要第二次单击按钮以访问相同的引用,则应将该ID存储在变量中,然后再次使用相同的变量, 而不要生成另一个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次按下按钮都会创建一个新的计时器实例 - A new instance of timer created everytime I press a button 每次单击按钮将视图添加到Fragment的LinearLayout中 - Add Views to LinearLayout of Fragment everytime I click button Android Studio SQLite 每次单击查看按钮时表都会重复 - Android Studio SQLite table duplicates everytime I click view button 为什么每次单击另一个片段时从Firebase检索的数据都会增加? - Why the data retrieve from firebase increase everytime I click on another fragment? 我有一幅我希望每次单击按钮都可以增长的图像 - I have an image which i would like to have grow everytime i click a button 当用户单击加号按钮时,我如何每次加+30? - How do i add +30 everytime when user click on plus button? 每次点击注册时,我的应用程序都会崩溃 - My app are crashing everytime i click on register 单击注册按钮时应用程序崩溃(使用 firebase ) - App crashes when I click signup button (using firebase ) 下面的代码是每次我单击按钮时都会显示随机颜色。 但是,尽管已完全编译,但它无法正常工作。 谢谢 - The Code Below is to display random color everytime i click the button. But its not working despite being fully compiled. Thanks 每次单击按钮时,Firebase 都会创建一个新对象 - Firebase create a new object every time I click a button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM