ListView在刷新或按下按钮时再次添加相同的名称

时间:2018-02-05 09:34:01

标签: android listview android-fragments firebase-realtime-database pull-to-refresh

因为我是Android编程的新手。当我点击button中的AlertDialog现状,缺席或延迟时,ListView会在列表中再次将List<String>的所有相同值添加到listView并显示它。而不是这样做我想只将数据发送到Firebase并更新地图值。我尝试了所有方法来删除此错误,但我无法找到问题。我想删除这个bug。请帮助我摆脱这个问题。

以下是代码:

public class Tab1 extends android.support.v4.app.Fragment {
    Context context;
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance ();
    DatabaseReference databaseReference = firebaseDatabase.getReference ();
    private JazzyListView listView;
    int check=0, connection =0;
    Map map = new HashMap ();
    Vibrator vibrator;
    public static MyAdapter adapter;
    ProgressDialog progressDialog;
    List<String> ListString = new ArrayList<> ();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate (R.layout.fragment_tab1, container, false);
        context = getContext ();
        Log.e ("Length", String.valueOf (map.size ()));
        vibrator = (Vibrator) getActivity ().getSystemService (Context.VIBRATOR_SERVICE);
        adapter = new MyAdapter (context, ListString);
        final PullRefreshLayout pullToRefreshView=(PullRefreshLayout) view.findViewById (R.id.pull);
        final Connectivity connectivity = new Connectivity (context);
        pullToRefreshView.setRefreshStyle (PullRefreshLayout.STYLE_WATER_DROP);
        pullToRefreshView.setOnRefreshListener (new PullRefreshLayout.OnRefreshListener () {
            @Override
            public void onRefresh() {
                if(!connectivity.isConnected ()){
                    Toast.makeText (context, "Connectivity to database lost. Kindly try again later or Connect your device to Internet", Toast.LENGTH_LONG).show ();
                    ListString.clear ();
                    pullToRefreshView.setRefreshing (false);
                }else {
                    ListString.clear ();
                    progressDialog = new ProgressDialog (context);
                    progressDialog.setCancelable (false);
                    progressDialog.setIcon (R.drawable.ic_file_download_black_24dp);
                    progressDialog.setMessage ("Hold your Patience");
                    progressDialog.setTitle ("Updating");
                    progressDialog.show ();
                    databaseReference.addValueEventListener (new ValueEventListener () {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            DataSnapshot snapshot = dataSnapshot.child ("User");
                            for(DataSnapshot s: snapshot.getChildren ()) {
                                if (s.getValue ().toString ().isEmpty ())
                                    Toast.makeText (context, "Empty", Toast.LENGTH_SHORT).show ();
                                else
                                    ListString.add (s.getKey ().toString ());
                            }
                            adapter.notifyDataSetChanged ();
                            progressDialog.dismiss ();
                            pullToRefreshView.setRefreshing (false);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Toast.makeText (context, databaseError.getMessage (), Toast.LENGTH_SHORT).show ();
                        }
                    });

                }

            }
        });
        if(connectivity.isConnected () || connection==1){
            progressDialog = new ProgressDialog (context);
            progressDialog.setCancelable (false);
            progressDialog.setIcon (R.drawable.ic_file_download_black_24dp);
            progressDialog.setMessage ("Hold your Patience");
            progressDialog.setTitle ("Retrieving Data");
            progressDialog.show ();
            ListString.add ("Adding");
            databaseReference.addValueEventListener (new ValueEventListener () {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    check++;
                    if(check<=1) {
                        ListString.remove ("Adding");
                        DataSnapshot snapshot = dataSnapshot.child ("User");
                        for(DataSnapshot s: snapshot.getChildren ())
                        {
                            if(s.getValue ().toString ().isEmpty ())
                                Toast.makeText (context, "Empty", Toast.LENGTH_SHORT).show ();
                            else
                                ListString.add(s.getKey ().toString ());
                        }
                        progressDialog.dismiss ();
                        adapter.notifyDataSetChanged ();
                    }else{

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Toast.makeText (context, databaseError.getMessage (), Toast.LENGTH_SHORT).show ();
                }
            });
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder (context);
            builder.setTitle("No Network")
                    .setMessage ("No Network Available").setPositiveButton ("Try again", new DialogInterface.OnClickListener () {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    vibrator.vibrate (100);
                        if(connectivity.isConnected ())
                            connection=1;
                        else
                            Toast.makeText (context, "No Connection", Toast.LENGTH_SHORT).show ();

                }
            }).setNeutralButton ("Ok", new DialogInterface.OnClickListener () {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss ();
                    vibrator.vibrate (100);
                }
            }).setIcon (R.drawable.nowifi);
            AlertDialog alertDialog = builder.create ();
            alertDialog.show ();
        }

        listView = (JazzyListView) view.findViewById (R.id.listview);
        listView.setTransitionEffect (new FadeEffect ());
        listView.setAdapter (adapter);
        //adapter.notifyDataSetChanged ();
        listView.setOnItemClickListener (new AdapterView.OnItemClickListener () {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, final View view, final int postion, long l) {
                adapter.count = 0;
                final String itemname = adapterView.getItemAtPosition (postion).toString ();
                try{
                    AlertDialog.Builder builder = new AlertDialog.Builder (context);
                    builder.setTitle("Attendence Tick")
                            .setMessage (itemname).setPositiveButton ("Present", new DialogInterface.OnClickListener () {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            try{
                                Calendar calendar = Calendar.getInstance ();
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
                                DatabaseReference user = databaseReference.child ("Attendence");
                                DatabaseReference date = user.child (simpleDateFormat.format (calendar.getTime ()));
                                DatabaseReference name = date.child (itemname);
                                name.setValue ("Present");
                                vibrator.vibrate (100);
                                map.put (String.valueOf (postion), "1");
                                adapter.setPresent (map);
                                adapter.notifyDataSetChanged ();
                            }catch (Exception e){
                                Log.e ("Problem", e.getMessage ());
                            }
                        }
                    }).setNeutralButton ("Absent", new DialogInterface.OnClickListener () {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Calendar calendar = Calendar.getInstance ();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
                            DatabaseReference user = databaseReference.child ("Attendence");
                            DatabaseReference date = user.child (simpleDateFormat.format (calendar.getTime ()));
                            DatabaseReference name = date.child (itemname);
                            name.setValue ("Absent");
                            vibrator.vibrate (100);
                            map.put (String.valueOf (postion), "0");
                            adapter.setPresent (map);
                            adapter.notifyDataSetChanged ();
                        }
                    }).setNegativeButton ("Late", new DialogInterface.OnClickListener () {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Calendar calendar = Calendar.getInstance ();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("dd MMM yyyy");
                            DatabaseReference user = databaseReference.child ("Attendence");
                            DatabaseReference date = user.child (simpleDateFormat.format (calendar.getTime ()));
                            DatabaseReference name = date.child (itemname);
                            name.setValue ("Late");
                            vibrator.vibrate (100);
                            map.put (String.valueOf (postion), "2");
                            adapter.setPresent (map);
                            adapter.notifyDataSetChanged ();
                        }
                    }).setIcon (R.drawable.ic_done_all_white_24dp);
                    AlertDialog alertDialog = builder.create ();
                    alertDialog.show ();
                }catch (Exception e){
                    Toast.makeText (context, e.getMessage (), Toast.LENGTH_SHORT).show ();
                }
            }
        });
        return view;
    }
}

1 个答案:

答案 0 :(得分:0)

**Place this when you add item to arraylist, to avoid duplication**

if(ListString.size>0){
  if(!ListString.contians(s.getKey ().toString ()){
       ListString.add(s.getKey ().toString ());
  }
}else{
       ListString.add(s.getKey ().toString ());
}