在Android中更新firebase数据库时ListView值重复值

Posted

技术标签:

【中文标题】在Android中更新firebase数据库时ListView值重复值【英文标题】:ListView Value duplicating the value when the firebase database is updated in Android 【发布时间】:2020-12-27 14:09:35 【问题描述】:

我在Fragment 中有Listview,我在其中使用ArrayAdapter 设置数据,当我使用对话框删除数据时,值在listview 中重复。我不知道该怎么做我想在对话框中单击删除按钮时刷新我的fragment,但我不知道该怎么做。我是 android 新手,请让我知道我能做些什么解决这个问题。这是我的代码。

ListOfFaculty

public class ListOfFaculty extends Fragment 

    DatabaseReference ref;
    ListView listview;
    List<String> store;
    List<String> UserID;
    String[] faculty_list;
    String a;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        ref = FirebaseDatabase.getInstance().getReference("Faculty");
    

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

        listview = root.findViewById(R.id.lv);
        store =new ArrayList<>();
        UserID =new ArrayList<>();

        ref.addValueEventListener(new ValueEventListener() 

            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
                for(DataSnapshot postsap : dataSnapshot.getChildren() ) 

                    DataSnapshot data = postsap.child("name");
                    if(data.exists())
                         a =  data.getValue().toString();
                    
                    store.add(a);
                    String Id = postsap.getKey();
                    UserID.add(Id);
                

                faculty_list = new String[store.size()];

                for(int i=0;i<faculty_list.length;i++)
                    faculty_list[i] =store.get(i);
                
                if (getActivity() != null) 
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, faculty_list);
                    listview.setAdapter(adapter);
                
            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 

            
        );

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 

                Intent i = new Intent(getContext(),Faculty.class);
                i.putExtra("User_Id",UserID.get(position));
                startActivity(i);
            
        );

        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) 

                String name = faculty_list[position];
                Toast.makeText(getContext(), ""+UserID.get(position), Toast.LENGTH_SHORT).show();

                DialogFragment dialogFragment =new MyDailogFragment();
                Bundle bundle =new Bundle();
                bundle.putString("Name",name);
              
                bundle.putString("Id",UserID.get(position));
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getChildFragmentManager(),"missiles");

                return true;
            
        );

        return root;
    

这是我的对话框代码,我在 ListofFaculty fragment 中使用 .setOnItemLongClickListener 调用此 Dialog 框。

MyDailogFragment

public class MyDailogFragment extends DialogFragment 

    DatabaseReference dailog;
    String Id;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) 

        Bundle bundle = getArguments();
        final String name=  bundle.getString("Name","");
        Id = bundle.getString("Id","");

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setMessage("Delete "+name+ " ?")
                .setPositiveButton("Delete", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                        Toast.makeText(getActivity(), ""+Id, Toast.LENGTH_SHORT).show();
                        dailog = FirebaseDatabase.getInstance().getReference("Faculty").child(Id);
                        dailog.addListenerForSingleValueEvent(new ValueEventListener() 
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
                                dataSnapshot.getRef().removeValue();
                                Toast.makeText(getActivity(), name+" Deleted Successfully ", Toast.LENGTH_SHORT).show();
                            

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) 

                            
                        );
                    
                )
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                        Toast.makeText(getActivity(), "Nothing", Toast.LENGTH_SHORT).show();
                    
                );

        return alertDialog.create();
    

【问题讨论】:

【参考方案1】:

有新值时必须清除旧数据

ref.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
                store.clear();
                for(DataSnapshot postsap : dataSnapshot.getChildren() )

                    DataSnapshot data = postsap.child("name");
                    if(data.exists())
                        a =  data.getValue().toString();
                    

                    store.add(a);
                    String Id = postsap.getKey();
                    UserID.add(Id);
                

                faculty_list = new String[store.size()];

                for(int i=0;i<faculty_list.length;i++)
                    faculty_list[i] =store.get(i);
                
                if (getActivity() != null) 
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, faculty_list);
                    listview.setAdapter(adapter);
                


            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 

            
        );

【讨论】:

以上是关于在Android中更新firebase数据库时ListView值重复值的主要内容,如果未能解决你的问题,请参考以下文章

Android - 应用更新时的 Firebase 远程配置缓存

将子值从 firebase 获取到 android 应用程序

当我在 Android 中将文件上传到 Firebase 存储时,进度条没有更新

在android studio中将firebase添加到flutter时出错:插件项目:firebase_core_web未找到。请更新 settings.gradle [重复]

Android Firebase FireStore实时更新分页

关闭 Firebase 上的实时更改 (Android)