刷新后在Recycler View上复制第一条消息密钥

时间:2019-04-23 10:07:03

标签: java android android-recyclerview recycler-adapter recyclerview-layout

当我使用swipeRefreshLayout从数据库加载所有消息时,发生探测。当我刷新回收站视图时,它将刷新我的第一个密钥,次数与刷新的次数相同。数据仅在回收者视图中以不同的方式查看,不会影响数据库。

如何阻止它在“回收者”视图中多次显示第一个键?任何帮助都将是巨大的,我不知道应该使用什么条件来解决此问题。

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;


public class MessageActivity extends AppCompatActivity {

// Initialise
private String userID;
private DatabaseReference databaseReference;
private TextView messageTitle;
private TextView lastActive;
private CircleImageView profileImg;
private Toolbar messageToolbar;
private FirebaseAuth firebaseAuth;
private String currentUser;
private EditText messageText;
private ImageButton sendMessage;

// Initialise Array list
private final List<Messages> messages_list = new ArrayList<>();

private LinearLayoutManager linearLayoutManager;

// Messages to load to and current page
private MessageAdapter messageAdapter;
private int current_page = 1;
private static final int messages_to_load = 10;

// Messages RecylerView
private RecyclerView messageView;
private SwipeRefreshLayout swipeRefreshLayout;

private int position = 0;
private String last_message ="";
private String first_message = "";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_message);


    // Setup Toolbar
    messageToolbar = findViewById(R.id.message_bar);
    setSupportActionBar(messageToolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);

    // Get Database Reference
    databaseReference = FirebaseDatabase.getInstance().getReference();
    firebaseAuth = FirebaseAuth.getInstance();
    currentUser = firebaseAuth.getCurrentUser().getUid();

    // Get user ID from Intent
    userID = getIntent().getStringExtra("user_ID");
    String UserName = getIntent().getStringExtra("user_Name");
   // getSupportActionBar().setTitle(UserName);

    // Inflater Service
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View message_actionbar_view =    inflater.inflate(R.layout.message_custom_imagebar,null);
    actionBar.setCustomView(message_actionbar_view);

    // Action bar
    messageTitle = findViewById(R.id.message_bar_title);
    lastActive = findViewById(R.id.message_bar_lastseen);
    profileImg = findViewById(R.id.message_image);


    messageText = findViewById(R.id.send_message_text);
    sendMessage = findViewById(R.id.message_send_btn);
    messageAdapter = new MessageAdapter(messages_list);

    messageView = findViewById(R.id.Messages_recycler);

    // set swipe layout
    swipeRefreshLayout = findViewById(R.id.swipe_layout_message);
    linearLayoutManager = new LinearLayoutManager(this);

    messageView.setHasFixedSize(true);
    messageView.setLayoutManager(linearLayoutManager);
    messageView.setAdapter(messageAdapter);

    // Call get messages method
    getMessages();


    // Set values
    messageTitle.setText(UserName);

    databaseReference.child("Users").child(userID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String onlineUser = dataSnapshot.child("online").getValue().toString();
            String userImg = dataSnapshot.child("image").toString();

            Timestamp timestamp = new Timestamp();
            long lastSeen = Long.parseLong(onlineUser);
            String lastActives = timestamp.getTimeAgo(lastSeen, getApplicationContext());

           // lastActive.setText(lastActives);

        }

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

        }
    });


    // click event on image button
    sendMessage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendMessageText();
        }
    });

    // What happens when you swipe to refresh
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            current_page++;
            position = 0;
           getAllMessages();

        }
    });

}
// Load a number of messages
private void getAllMessages() {
    DatabaseReference message_reference = databaseReference.child("Messages").child(currentUser).child(userID);

    Query message_Query = message_reference.orderByKey().endAt(last_message).limitToLast(10);
    message_Query.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            Messages message = dataSnapshot.getValue(Messages.class);
            String last_message_key = dataSnapshot.getKey();
            messages_list.add(position++, message);



            // Checks if position  is 1
            if(position == 1){

                last_message = last_message_key;

            }



            messageAdapter.notifyDataSetChanged();

            swipeRefreshLayout.setRefreshing(false);
            linearLayoutManager.scrollToPositionWithOffset(10,0);


        }

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

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

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

        }

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

        }
    });
}

private void getMessages() {
    DatabaseReference message_reference = databaseReference.child("Messages").child(currentUser).child(userID);

    Query message_Query = message_reference.limitToLast(current_page * messages_to_load);
    message_Query.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            Messages messages = dataSnapshot.getValue(Messages.class);

            position++;

            if(position == 1){
                String last_message_key = dataSnapshot.getKey();
                last_message = last_message_key;
                first_message = last_message_key;
            }
            messages_list.add(messages);

            messageAdapter.notifyDataSetChanged();

            messageView.scrollToPosition(messages_list.size() - 1);
             swipeRefreshLayout.setRefreshing(false);


        }

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

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

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

        }

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

        }
    });

}

private void sendMessageText() {
    String message = messageText.getText().toString();
    if(!TextUtils.isEmpty(message)){

        String current_User = "Messages/" + currentUser + "/" + userID;
        String chat_User = "Messages/" + userID + "/" + currentUser;
        DatabaseReference message_push = databaseReference.child("Messages").child(currentUser).child(userID).push();
        String pushID = message_push.getKey();
        Map sendMessageMap = new HashMap();
        sendMessageMap.put("message", message);
        sendMessageMap.put("seen", false);
        sendMessageMap.put("type", "text");
        sendMessageMap.put("time", ServerValue.TIMESTAMP);
        sendMessageMap.put("from", currentUser);

        Map sendUserMap = new HashMap();
        sendUserMap.put(current_User + "/" + pushID, sendMessageMap);
        sendUserMap.put(chat_User + "/" + pushID, sendMessageMap);
        messageText.setText("");

        databaseReference.updateChildren(sendUserMap, new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
                if(databaseError != null){
                    Log.d("CHAT_LOG", databaseError.getMessage());
                }
            }
        });

    }
}

}

它应该只打印一次以供回收者查看,而不是2或3次。

0 个答案:

没有答案