简体   繁体   中英

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.

This is the screenshot of my issue.

在此处输入图片说明

When i click on Send it duplicates the message.

Here is my 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.

Can anybody help me with it?

You're calling bringMessageFromCloud twice. Once in your onCreate and the other in 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.

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