简体   繁体   English

当我带来Firebase数据库时,它们正在复制数据。 当我发送消息时,它发送两个

[英]Firebase Database is duplicating the data when i bring them. When i send a message it sends two

I've been having this issue for a while. 我已经有一段时间了。 I've built a Chat application however I When i try sending a message it duplicates the message on the screen. 我已经建立了一个聊天应用程序,但是当我尝试发送消息时,它会在屏幕上复制消息。

I'm using Firebase database to bring data from the cloud, however, its duplicating only in the screen, when i look at the messages on the database they are normal. 我正在使用Firebase数据库从云中获取数据,但是,当我查看数据库中的消息时,它们仅在屏幕中复制,这是正常的。

This is the screenshot of my issue. 这是我的问题的屏幕截图。

在此处输入图片说明

When i click on Send it duplicates the message. 当我单击“发送”时,消息重复。

Here is my Chat.class 这是我的Chat.class

package br.sosqueen.com.sosqueen;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by calvin.
 */

public class Chat extends AppCompatActivity {

    private LinearLayout layout;
    private EditText messageArea;
    private ScrollView scrollView;

    DatabaseReference reference1 = FirebaseDatabase.getInstance()
            .getReferenceFromUrl("https://sosqueen-6b80b.firebaseio.com/" + UserDetails.username + "_" + UserDetails.chatWith);
    DatabaseReference reference2 = FirebaseDatabase.getInstance()
            .getReferenceFromUrl("https://sosqueen-6b80b.firebaseio.com/" + UserDetails.chatWith + "_" + UserDetails.username);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_chat);

        layout = (LinearLayout) findViewById(R.id.layout1);
        messageArea = (EditText) findViewById(R.id.messageArea);
        scrollView = (ScrollView) findViewById(R.id.scrollView);

        getSupportActionBar().setTitle(UserDetails.chatWith);

        bringMessageFromCloud();
    }

    public void sendMessage(View view) {
        String messageText = messageArea.getText().toString();

        if(! messageText.equals("")){
            Map<String, String> map = new HashMap<String, String>();
            map.put("message", messageText);
            map.put("user", UserDetails.username);
            reference1.push().setValue(map);
            reference2.push().setValue(map);
        }

        bringMessageFromCloud();

        messageArea.setText("");
    }

    public void bringMessageFromCloud() {
        reference1.addChildEventListener(new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
                Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator );
                String message = map.get("message").toString();
                String userName = map.get("user").toString();

                if(userName.equals(UserDetails.username)){
                    addMessageBox(message, 1);
                }
                else{
                    addMessageBox(message, 2);
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });
    }

    public void addMessageBox(String message, int type) {
        TextView textView = new TextView(Chat.this);
        textView.setText(message);
        LinearLayout.LayoutParams linearP = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearP.setMargins(10, 0, 0, 10);
        textView.setLayoutParams(linearP);
        textView.setTypeface(Typeface.create("sans-serif-thin", Typeface.NORMAL));
        textView.setTextSize(20);

        if(type == 1) {
            linearP.gravity = Gravity.END;
            textView.setTextColor(Color.WHITE);
            textView.setBackgroundResource(R.drawable.rounded_corner1);
            textView.setPadding(20,20,20,20);
            scrollView.post(new Runnable()
            {
                public void run()
                {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });

        } else {
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.rounded_corner2);
            textView.setPadding(20,20,20,20);
            scrollView.post(new Runnable()
            {
                public void run()
                {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }

        layout.addView(textView);
    }
}

Method sendMessage is a OnClickListener for the send message icon. sendMessage方法是用于发送消息图标的OnClickListener。

Can anybody help me with it? 有人可以帮我吗?

You're calling bringMessageFromCloud twice. 您要两次调用BringMessageFromCloud。 Once in your onCreate and the other in sendMessage. 一次在onCreate中,另一个在sendMessage中。 Every time you send a message, a new event listener is registered. 每次发送消息时,都会注册一个新的事件侦听器。 Remove the one from sendMessage and your code should work as expected. 从sendMessage中删除一个,您的代码应该可以正常工作。

暂无
暂无

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

相关问题 JButton仅在我将鼠标悬停在它们上方时才会显示。 当我调整窗口大小时也消失 - JButtons only show up when I hover over them. Also disappear when I resize window 如何从Firebase数据库中仅获取一个数据? - How can i bring just one data from firebase database? 虽然我发送了Acknowledge,但Firebase Cloud Messaging会多次发送上游消息 - Firebase Cloud Messaging sends upstream message multiple times, although I send Acknowledge 当我发送消息时,我可以在 firebase 中看到它,但我无法在模拟器或手机上阅读它,它什么也没有显示 - When I send a message I can see it in firebase but i cannot read it on emulator or my phone it show nothing 如何将“ListView”值发送到“RecycleView”并保存它们。 我正在使用使用 JAVA 的 Android Studio? - How to send a "ListView" value to a "RecycleView" and save them. I'm using Android Studio using JAVA? 我有两个线程,这两个线程几乎是完全相同的,但是只有其中之一会出现CalledFromWrongThreadException错误。 为什么? - I have two threads that two almost identical things but get CalledFromWrongThreadException error on only one of them. why? 在 Android 中更新 Firebase 数据库时,ListView 值会复制该值 - ListView Value duplicating the value when the firebase database is updated in Android 我如何在需要时而不只是在 DataChange 时从 firebase 实时数据库中读取数据 - how can i read data from firebase realtime database when i want and not just when DataChange 尝试向Firebase服务器发送消息时发生异常 - Exception when trying to send a message to firebase server 当Java向Oracle发送消息时 - When Java sends message to Oracle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM