向 Firebase 添加新项目后 ListView 重复 [重复]

Posted

技术标签:

【中文标题】向 Firebase 添加新项目后 ListView 重复 [重复]【英文标题】:ListView duplicating after adding new items to Firebase [duplicate] 【发布时间】:2021-06-21 14:09:19 【问题描述】:

我正在尝试将教师添加到 firebase 实时数据库并在 listView 中检索教师,如下图所示:

但是当添加一个新项目时,我会检索两次现有数据和一次新数据,如下图所示:

After Adding - Leading the Duplication of the ListView

''' //value variables
ArrayList<teachersHelper> teachersFromdatabase = new ArrayList<>();
teacher_adapter teacher_adapter; 

此方法在 ADDTEACHERS 的 ONCLICK 上调用

private void addingteacher() 
    progressBar.setVisibility(View.VISIBLE);

    // opening the Custom dialog to get the information of the new Teachers
    Dialog mydialog = new Dialog(teacher_admin.this);
    mydialog.setContentView(R.layout.addteachers);
    mydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    progressBar.setVisibility(View.GONE);
    mydialog.show();
    mydialog.setOnDismissListener(dialog -> progressBar.setVisibility(View.GONE));


    // hooking all the views of the dialog

    EditText teache5rName = mydialog.findViewById(R.id.teacherssname_dialogbox);
    EditText registrationNumber = mydialog.findViewById(R.id.teachersReg_dialogbox);
    EditText passwordteacher = mydialog.findViewById(R.id.teacherspassword_dialogbox);
    EditText department = mydialog.findViewById(R.id.teachersDepartment_dialogbox);
    EditText mobilenumber = mydialog.findViewById(R.id.teacherMobilenumber_dialogbox);

    NeumorphButton addteachersButton = mydialog.findViewById(R.id.add_teachersDialog);


    // when the add button on the dialog is pressed
    addteachersButton.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 

            // dilog and progress bar
            progressBar.setVisibility(View.VISIBLE);

            //converting the edittext the String Literals
            String tnamez = teache5rName.getEditableText().toString().trim();
            String tregNu = registrationNumber.getEditableText().toString().trim();
            String tpassw = passwordteacher.getEditableText().toString().trim();
            String tdepartment = department.getEditableText().toString().trim();
            String tmobileNum = "+91" + mobilenumber.getEditableText().toString().trim();

          // validating the fields wheather they are empty or not
            if (!validateFields(tnamez, tregNu, tpassw, tdepartment, tmobileNum)) 

                // if empty then show a error custom dialog
                donedialogboxMeathod(false);
                progressBar.setVisibility(View.GONE);
                return;
            

            donedialogboxMeathod(true);

            // where the teachers are under so the adding teacher fuction is in admin so
           // adminhelper is created and called the function
            AdminHelper adminHelper = new AdminHelper();

            // adding the teacher
            adminHelper.addTEachers(tnamez, tregNu, tpassw, "No", tdepartment,
                    "No", tmobileNum, "No");

            // notifyin the adpater that we added new ber
            teacher_adapter.notifyDataSetChanged();

         // dissmissing the progressbar and Custom dialog
            progressBar.setVisibility(View.GONE);
            mydialog.dismiss();


        
    );

ADMINHELPER TO ADDTEACHERS 中的此方法

public teachersHelper addteacher(String tName, String tregNumber, String tPassword,String 
                                 imageId, String tDepartment,String tEmail, String 
                                    tphoneNumber, String tadress) 

    // creating the teachers Helper Class
    teachersHelper teachersHelpers = new teachersHelper(tName, tregNumber, tPassword, imageId, tDepartment,
            tEmail, tphoneNumber, tadress);
    
    // database stuff
    DatabaseReference teacherreferenc = FirebaseDatabase.getInstance().
            getReference("Admin").child(mAuth.getUid()).child("INSTITUTE");
    
    //adding value
    teacherreferenc.child("TEACHERS").child(tregNumber).setValue(teachersHelpers);

    return teachersHelpers;


检索教师并将他们添加到列表视图(我认为问题就在这里)

public void settingViews()

  // Firebase variables to retreive the data of the teacher
                FirebaseAuth mAuth = FirebaseAuth.getInstance();

                DatabaseReference databasereference = FirebaseDatabase.getInstance()
                        .getReference("Admin").child(mAuth.getUid()).child("INSTITUTE")
                        .child("TEACHERS");


                //the teachers are stored with the node of registrationNumber so i created a arraylist
                ArrayList<String> registrattionNumber = new ArrayList<>();


                // valueevent to retreving the data
                databasereference.addValueEventListener(new ValueEventListener() 
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) 

                        // cheching if the snapshot exists
                        if (snapshot.exists()) 

                            // getting all the registration Number
                            for (DataSnapshot regis : snapshot.getChildren()) 

                                // adding the registrationNumbers to the arraylist
                                registrattionNumber.add(regis.getKey());

                            

                            // based on the arraylist of the registrationNUmber we will be retriving
                            // the data of teachers of particular registrartion Number

                            for (int i = 0; i < registrattionNumber.size(); i++) 

                                //firebase stuff
                                Query teacherssdata = FirebaseDatabase.getInstance()
                                        .getReference("Admin").child(mAuth.getUid()).child("INSTITUTE")
                                        .child("TEACHERS").child(registrattionNumber.get(i));


                                // value evnet listener
                                teacherssdata.addValueEventListener(new ValueEventListener() 
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot snapshot) 

                                        if (snapshot.exists()) 

                                          // retreiving all the teachers data from the snapshot
                                            String _name = snapshot.child("tName").getValue().toString();
                                            String _regno = snapshot.child("tregNumber").getValue().toString();
                                            String _pass = snapshot.child("tPassword").getValue().toString();
                                            String _img = snapshot.child("image").getValue().toString();
                                            String _depart = snapshot.child("tDepartment").getValue().toString();
                                            String _phonenumber = snapshot.child("tphoneNumber").getValue().toString();
                                            String _adress = snapshot.child("tadress").getValue().toString();
                                            String _emai = snapshot.child("tEmail").getValue().toString();

                                           // creating the teacherclass and adding all the info from the firebase
                                            teachersHelper teachersHelperzzzz = new
                                                    teachersHelper(_name, _regno, _pass, _img, _depart, _emai
                                                    , _phonenumber, _adress);

                                           // adding the teacher objects to the Golbal Variable
                                            teachersFromdatabase.add(teachersHelperzzzz);

                                            // creating listview
                                            // creating the adapter
                                            teacher_adapter = new teacher_adapter(teacher_admin.this,
                                                    teachersFromdatabase);

                                          // setting the adapter to the listview
                                            listView.setAdapter(teacher_adapter);
                                            progressBar.setVisibility(View.GONE);

                                           


                                         else 
                                            progressBar.setVisibility(View.VISIBLE);
                                            StyleableToast.makeText(teacher_admin.this, "Deleted Sucessfully"
                                                    , R.style.exampleToast).show();

                                        


                                    

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError error) 
                                        dialogboxMeathod(teacher_admin.this, error.getMessage());
                                    
                                );

【问题讨论】:

【参考方案1】:

每次databasereference 发生更改时,您的onDataChange 都会被调用,并带有该路径上数据的完整快照。因此,即使只有一个子节点被更改/添加/删除,snapshot 也包含您已添加到 registrattionNumber 的所有其他(未修改)子节点。

最简单的解决办法是清除onDataChange顶部的registrattionNumber

databasereference.addValueEventListener(new ValueEventListener() 
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) 
        registrattionNumber.clear();
        ...

另见:

Duplicate objects from Firebase loaded into ListView Duplicate data from firebase realtime databse Item gets duplicated in adapter, when we delete or update item from Firebase Realtime Database Why do i get duplicate values when adding data to firebase realtime database using kotlin? 还有更多来自此搜索:https://***.com/search?q=%5Bfirebase-realtime-database%5D%5Bandroid%5D+duplicate

【讨论】:

如果我使用 registrattionNumber.clear();我只是从数据库中获取一位教师的对象,并在 ListView 上显示一位教师。

以上是关于向 Firebase 添加新项目后 ListView 重复 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

添加 Firebase CocoaPods 后无法构建项目

无法在 Firebase 项目设置中添加团队 ID

如何在 Firebase 中删除 tableview 项目后删除它们

将 Firebase 添加到颤振项目,破坏项目

向 Firebase 用户添加新数据

Firebase如何向所有孩子添加新数据