Recycler View не обновляется из-за того, что ValueEventListeners запускает метод onDataChange одновременно - PullRequest
0 голосов
/ 25 апреля 2020

Итак, моя проблема в том, что valueeventlistener userRef и groupRef ставки срабатывает одновременно, если я создаю новую группу, что делается нажатием кнопки с плавающим действием, введя имя в поле всплывающее окно и нажав кнопку создания. Из-за этого groupKeys Array List пуст, когда программа пытается проверить, содержит ли groupsKeys один из ключей, хранящихся в узле users. Из-за этого ни один элемент не добавляется в список массивов mGroups.

Как вы могли заметить, я не лучший в объяснении, но я надеюсь, что вы поняли, что я имею в виду.

Вот мой класс группы


/**
 * A simple {@link Fragment} subclass.
 */
public class GroupsFragment extends Fragment
{

    private FloatingActionButton createGroupButton;
    private RecyclerView groupRecyclerView;
    private FirebaseAuth mAuth;
    private StorageReference storageReference;
    private DatabaseReference groupRef;
    private DatabaseReference userRef;
    private List<String> groupKeys;
    private List<Group> mGroups;
    private GroupAdapter groupAdapter;

    public GroupsFragment()
    {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_groups, container, false);

        createGroupButton = view.findViewById(R.id.groups_create_group_btn);
        groupRecyclerView = view.findViewById(R.id.groups_recycler_view);
        groupRecyclerView.setHasFixedSize(true);
        groupRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mGroups = new ArrayList<Group>();
        mAuth = FirebaseAuth.getInstance();
        storageReference = FirebaseStorage.getInstance().getReference();
        groupRef = FirebaseDatabase.getInstance().getReference().child("Groups");
        userRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
        groupKeys = new ArrayList<String>();

        userRef.child("Groups").child("ids").addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                if(dataSnapshot.exists())
                {
                    groupKeys.clear();
                    for (DataSnapshot groupId : dataSnapshot.getChildren())
                    {
                        groupKeys.add(groupId.getKey());
                    }
                }
            }

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

            }
        });

        groupRef.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                if(dataSnapshot.exists())
                {
                    mGroups.clear();
                    for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
                    {
                        if(groupKeys.contains(dataSnapshot1.getKey()))
                        {
                            Group group = dataSnapshot1.getValue(Group.class);
                            mGroups.add(group);
                        }
                    }
                    groupAdapter = new GroupAdapter(getContext(), mGroups);
                    groupRecyclerView.setAdapter(groupAdapter);
                }

            }

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

            }
        });

        createGroupButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                GroupDialog groupDialog = new GroupDialog();
                groupDialog.show(getFragmentManager(), "create_group_dialog");
            }
        });


        return view;
    }
}

Я не знаю, если это необходимо, но вот класс группового диалога и класс GroupAdapter

GroupDialog:


public class GroupDialog extends AppCompatDialogFragment
{
    private EditText groupNameEditText;
    private CircleImageView groupIcon;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.create_group_pop_up, null);

        groupNameEditText = view.findViewById(R.id.pop_up_group_name);
        groupIcon = view.findViewById(R.id.pop_up_group_image);

        builder.setView(view)
        .setTitle("Create Group")
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        })
        .setPositiveButton("Create", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                createNewGroup(dialog);
            }
        });

        return builder.create();
    }

    private void createNewGroup(final DialogInterface dialog)
    {
        final DatabaseReference groupRef = FirebaseDatabase.getInstance().getReference().child("Groups");
        final DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("Users");
        final FirebaseAuth mAuth = FirebaseAuth.getInstance();
        final String uid = mAuth.getCurrentUser().getUid();
        final String randomId = groupRef.push().getKey();
        final String groupName = groupNameEditText.getText().toString();
        //später
        final String imageUrl = "https://firebasestorage.googleapis.com/v0/b/debtapp-c3b21.appspot.com/o/appImages%2Fic_launcher_round.png?alt=media&token=5976f603-0e03-4c4c-bc10-7a15958eb5b0";

        if(!groupName.isEmpty())
        {
            final ProgressDialog progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("Creating Group");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
            HashMap<String, Object> memberMap = new HashMap<>();
            memberMap.put("id", uid);
            final HashMap<String, Object> attributesMap = new HashMap<>();
            attributesMap.put("name", groupName);
            attributesMap.put("adminid", uid);
            attributesMap.put("image", imageUrl);
            final HashMap<String, Object> userMap = new HashMap<>();
            userMap.put(randomId, randomId);
            groupRef.child(randomId).child("Members").updateChildren(memberMap).addOnCompleteListener(new OnCompleteListener<Void>()
            {
                @Override
                public void onComplete(@NonNull Task<Void> task)
                {
                    if (task.isSuccessful())
                    {
                        groupRef.child(randomId).updateChildren(attributesMap).addOnCompleteListener(new OnCompleteListener<Void>()
                        {
                            @Override
                            public void onComplete(@NonNull Task<Void> task)
                            {
                                if(task.isSuccessful())
                                {
                                    userRef.child(uid).child("Groups").child("ids").updateChildren(userMap).addOnCompleteListener(new OnCompleteListener<Void>()
                                    {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task)
                                        {
                                            if (task.isSuccessful())
                                            {
                                                dialog.dismiss();
                                                progressDialog.dismiss();
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        else
        {
            Toast.makeText(getContext(), "Name cannot be empty...", Toast.LENGTH_SHORT).show();
        }
    }
}

GroupAdapter:


public class GroupDialog extends AppCompatDialogFragment
{
    private EditText groupNameEditText;
    private CircleImageView groupIcon;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.create_group_pop_up, null);

        groupNameEditText = view.findViewById(R.id.pop_up_group_name);
        groupIcon = view.findViewById(R.id.pop_up_group_image);

        builder.setView(view)
        .setTitle("Create Group")
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        })
        .setPositiveButton("Create", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                createNewGroup(dialog);
            }
        });

        return builder.create();
    }

    private void createNewGroup(final DialogInterface dialog)
    {
        final DatabaseReference groupRef = FirebaseDatabase.getInstance().getReference().child("Groups");
        final DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("Users");
        final FirebaseAuth mAuth = FirebaseAuth.getInstance();
        final String uid = mAuth.getCurrentUser().getUid();
        final String randomId = groupRef.push().getKey();
        final String groupName = groupNameEditText.getText().toString();
        //später
        final String imageUrl = "https://firebasestorage.googleapis.com/v0/b/debtapp-c3b21.appspot.com/o/appImages%2Fic_launcher_round.png?alt=media&token=5976f603-0e03-4c4c-bc10-7a15958eb5b0";

        if(!groupName.isEmpty())
        {
            final ProgressDialog progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("Creating Group");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
            HashMap<String, Object> memberMap = new HashMap<>();
            memberMap.put("id", uid);
            final HashMap<String, Object> attributesMap = new HashMap<>();
            attributesMap.put("name", groupName);
            attributesMap.put("adminid", uid);
            attributesMap.put("image", imageUrl);
            final HashMap<String, Object> userMap = new HashMap<>();
            userMap.put(randomId, randomId);
            groupRef.child(randomId).child("Members").updateChildren(memberMap).addOnCompleteListener(new OnCompleteListener<Void>()
            {
                @Override
                public void onComplete(@NonNull Task<Void> task)
                {
                    if (task.isSuccessful())
                    {
                        groupRef.child(randomId).updateChildren(attributesMap).addOnCompleteListener(new OnCompleteListener<Void>()
                        {
                            @Override
                            public void onComplete(@NonNull Task<Void> task)
                            {
                                if(task.isSuccessful())
                                {
                                    userRef.child(uid).child("Groups").child("ids").updateChildren(userMap).addOnCompleteListener(new OnCompleteListener<Void>()
                                    {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task)
                                        {
                                            if (task.isSuccessful())
                                            {
                                                dialog.dismiss();
                                                progressDialog.dismiss();
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        else
        {
            Toast.makeText(getContext(), "Name cannot be empty...", Toast.LENGTH_SHORT).show();
        }
    }
}

...