简体   繁体   中英

ListView Value duplicating the value when the firebase database is updated in Android

I have Listview in a Fragment in which i am setting data using ArrayAdapter , when i am deleting the data with Dialog box the Value is duplicating in the listview . i don't know what to do i was thinkint to refresh my fragment when the delete button is clicked in dialog box but i don't how to do that.I am new to Android please let me know what can i do to solve this.Here is my Code.

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;
    }
}

This is my Dialog Box Code,I am calling this Dialog box with . setOnItemLongClickListener from my ListofFaculty fragment .

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();
    }
}

You have to clear old data when have new value

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) {

            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM