添加新商品时的RecyclerView滞后

时间:2018-12-19 10:51:24

标签: java android firebase-realtime-database android-recyclerview

我有一个群聊应用程序。发送新消息时,应用程序输入延迟。当某人发送邮件时,对方无法同时应答。我怎么解决这个问题?我正在使用Firebase实时数据库。我不知道问题出在哪里。问题可能是由适配器引起的吗?还是与火力基地有关?

public class FragmentHaykirma extends Fragment {

    private EditText editText;
    private Button buttonSend;
    private RecyclerView recyclerView;
    private DatabaseReference myRef;
    private FirebaseDatabase database;
    private FirebaseAuth mAuth;
    private FirebaseUser mUser;
    private List<Message> messageslist = new ArrayList<>();
    private AdapterMessage adapterMessage;
    private EngelDatabase engelDatabase;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_haykirma, container, false);

        define(view);
        getMessageData();
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUser != null) {
                    final String messageText = editText.getText().toString().trim();
                    if (messageText.matches("")) {
                        Toast.makeText(getContext(), "Boş Mesaj Atmasanda Olur :) ", Toast.LENGTH_LONG).show();
                    } else {
                        final DatabaseReference myRefUserData = FirebaseDatabase.getInstance().getReference("Users");
                        final User user = new User();
                        final UUID uuidS = UUID.randomUUID();
                        final String uuid = uuidS.toString();
                        myRefUserData.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                user.setUserName(dataSnapshot.getValue(User.class).getUserName());
                                user.setUserId(dataSnapshot.getValue(User.class).getUserId());
                                user.setUserEmail(dataSnapshot.getValue(User.class).getUserEmail());
                                user.setUserImage(dataSnapshot.getValue(User.class).getUserImage());
                                user.setUserCity(dataSnapshot.getValue(User.class).getUserCity());
                                user.setUserRelationship(dataSnapshot.getValue(User.class).getUserRelationship());

                                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
                                Date currentData = cal.getTime();
                                String sonuc = DateFormat.format("dd-MM-yyyy HH:mm", currentData).toString();
                                Log.e("SONUC", sonuc);
                                Message message = new Message();
                                message.setMessageBody(messageText);
                                message.setMessageId(uuid);
                                message.setMessageSenderImage(user.getUserImage());
                                message.setMessageTime(sonuc);
                                message.setMessageSenderName(user.getUserName());
                                message.setMessageSenderCity(user.getUserCity());
                                message.setUserId(user.getUserId());
                                myRef.child(uuid).setValue(message);
                                myRef.child(uuid).child("timestamp").setValue(ServerValue.TIMESTAMP);
                                getMessageData();

                            }

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

                            }
                        });

                        editText.setText("");

                    }
                } else {
                    Snackbar snackbar = Snackbar.make(view, "Mesaj Atabilmek İçin Üye Olmanız Lazım Üye Olmak İçin Tıklayın", Snackbar.LENGTH_LONG).setAction("Üyelik Oluştur", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            getActivity().finish();
                        }
                    });
                    snackbar.show();
                }

            }
        });

        return view;
    }

    public void getMessageData() {
        final ArrayList<Engellenenler> engellenenlerArrayList = new EngelDao().getirEngellenenler(engelDatabase);
        Query query = myRef.orderByChild("timestamp");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                messageslist.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Message message = new Message();
                    message.setMessageTime(ds.getValue(Message.class).getMessageTime());
                    message.setMessageSenderImage(ds.getValue(Message.class).getMessageSenderImage());
                    message.setMessageSenderName(ds.getValue(Message.class).getMessageSenderName());
                    message.setMessageBody(ds.getValue(Message.class).getMessageBody());
                    message.setMessageSenderCity(ds.getValue(Message.class).getMessageSenderCity());
                    message.setUserId(ds.getValue(Message.class).getUserId());
                    message.setMessageId(ds.getValue(Message.class).getMessageId());

                    if (engellenenlerArrayList.size() > 0) {

                        for (Engellenenler k : engellenenlerArrayList) {

                            if (k.getEngellenen_name().contains(message.getUserId())) {
                                Log.e("SİZE", k.getEngellenen_name());
                            } else {
                                messageslist.add(message);
                                updateBoundedView();
                                recyclerView.scrollToPosition(messageslist.size() - 1);

                            }
                        }
                    } else {
                        messageslist.add(message);
                        updateBoundedView();
                        recyclerView.scrollToPosition(messageslist.size() - 1);
                    }


                    if (messageslist.size() >= 20) {
                        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Messages");
                        Query sizesRef = databaseReference.orderByChild("timestamp").limitToFirst(5);
                        sizesRef.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                    ds.getRef().removeValue();
                                    //adapterMessage.notifyDataSetChanged();
                                }
                            }

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

                            }
                        });
                    }

                }
            }

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

            }
        });


        adapterMessage = new AdapterMessage(getContext(), messageslist);
        recyclerView.setAdapter(adapterMessage);
        updateBoundedView();
        recyclerView.scrollToPosition(messageslist.size() - 1);
    }

    public void updateBoundedView() {
        if(recyclerView!=null) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    if (adapterMessage != null) {
                        adapterMessage.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    public void define(View view) {
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("Messages");
        mAuth = FirebaseAuth.getInstance();
        mUser = mAuth.getCurrentUser();

        editText = view.findViewById(R.id.editTextMessage);
        buttonSend = view.findViewById(R.id.buttonSendeMessage);
        recyclerView = view.findViewById(R.id.recycler_haykirma);
        recyclerView.setHasFixedSize(true);
        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
//        linearLayoutManager.setReverseLayout(true);
//        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(gridLayoutManager);
        engelDatabase = new EngelDatabase(getContext());

    }

我的适配器

public class AdapterMessage extends RecyclerView.Adapter<AdapterMessage.ViewHolderMessage> {

    private Context context;
    private List<Message> messageList;
    private DatabaseReference myRef;
    private FirebaseDatabase database;
    private FirebaseAuth mAuth;
    private FirebaseUser mUser;
    private EngelDatabase ed;

    public AdapterMessage(Context context, List<Message> messageList) {
        this.context = context;
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public ViewHolderMessage onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(context).inflate(R.layout.recycler_message_rowa,viewGroup,false);

        ed = new EngelDatabase(context);
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("Messages");
        mAuth = FirebaseAuth.getInstance();
        mUser = mAuth.getCurrentUser();


        return new ViewHolderMessage(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolderMessage viewHolderMessage, final int i) {
        final Message message = messageList.get(i);
        viewHolderMessage.textViewName.setText(message.getMessageSenderName());
        //viewHolderMessage.textViewDate.setText(message.getMessageTime());
        viewHolderMessage.textViewCity.setText(message.getMessageSenderCity());
        if (message.getMessageBody().startsWith("@")){
            String arr[] = message.getMessageBody().split(" ", 2);

            if (arr.length > 1){
                String first = arr[0];
                String contu = arr[1];
                Spannable spannable = new SpannableString(first+ " " +contu);
                spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, first.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.colorWomen)), first.length(), first.length()+contu.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                viewHolderMessage.textViewMessage.setText(spannable);
            }else {
                viewHolderMessage.textViewMessage.setText(arr[0]);
            }


        }else {
            viewHolderMessage.textViewMessage.setText(message.getMessageBody());
        }

        viewHolderMessage.textViewCevapla.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUser != null){
                    Intent intent = new Intent(context,CevapVerActivity.class);
                    intent.putExtra("message",message);
                    context.startActivity(intent);
                }else {
                    Snackbar snackbar = Snackbar.make(v, "Mesaj Atabilmek İçin Üye Olmanız Lazım Üye Olmak İçin Tıklayın", Snackbar.LENGTH_LONG).setAction("Üyelik Oluştur", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            context.startActivity(new Intent(context, LoginActivity.class));
                        }
                    });
                    snackbar.show();
                }
            }
        });

        Picasso.get().load(message.getMessageSenderImage()).fit().into(viewHolderMessage.imageView);
        viewHolderMessage.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUser != null){
                    PopupMenu menu = new PopupMenu(context,viewHolderMessage.button);
                    menu.getMenuInflater().inflate(R.menu.popup_menu,menu.getMenu());
                    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            if (item.getItemId() == R.id.popupReport){
                                Intent intent = new Intent(Intent.ACTION_SEND);
                                intent.setData(Uri.parse("mailto"));
                                String[] to = {"gkhn.btby1@gmail.com"};
                                intent.putExtra(Intent.EXTRA_EMAIL,to);
                                intent.putExtra(Intent.EXTRA_SUBJECT,"Mesaj Id: " + message.getMessageId() + " " + "Mesaj Atan Id: " + message.getUserId());
                                intent.setType("message/rfc822");
                                intent = Intent.createChooser(intent,"Mail Gönder");
                                context.startActivity(intent);
                            }else if (item.getItemId() == R.id.popupEngelle){
                                new EngelDao().engelEkle(ed,""+message.getUserId());
                            }
                            return false;
                        }
                    });
                    menu.show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if (messageList == null){
            return 0;
        }else {
            return messageList.size();
        }
    }


    public class ViewHolderMessage extends RecyclerView.ViewHolder{

        private ImageView imageView;
        private TextView textViewName,textViewMessage,textViewCity,textViewCevapla;
        private Button button;

        public ViewHolderMessage(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.mainMessageRowImage);
            textViewCevapla = itemView.findViewById(R.id.cevaplaButtonText);
            textViewName = itemView.findViewById(R.id.mainMessageRowNameText);
            textViewMessage = itemView.findViewById(R.id.mainMessageRowMessageText);
            textViewCity = itemView.findViewById(R.id.mainmessageRowCityText);
            button = itemView.findViewById(R.id.mainMessageRowPopupBtn);
        }
    }
}

0 个答案:

没有答案