反压时自动重置过滤器

时间:2018-07-23 13:53:42

标签: android android-recyclerview android-filter

我在android过滤器中遇到一个问题。

首先,我搜索一些文本,并根据结果值做一个事件,然后返回活动。到那时,我的列表视图将刷新所有项目,而不是过滤后的项目。

例如: 我正在从通讯录中搜索一个联系人,它将返回一些结果。根据该结果,我将执行一些功能,然后返回到联系人列表屏幕,此时我的联系人列表会自动重置。

下面是过滤器的代码

public class ValueFilter extends Filter {

        ContactsAdapter adapter;
        private ArrayList<HashMap<String, Object>> mfilterList;

        public ValueFilter(ArrayList<HashMap<String, Object>> filterList, ContactsAdapter adapter) {
            this.adapter = adapter;
            this.mfilterList = filterList;
        }

        //Invoked in a worker thread to filter the data according to the constraint.
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {

                ArrayList<HashMap<String, Object>> filterListbk = new ArrayList<HashMap<String, Object>>();

                for (int i = 0; i < mfilterList.size(); i++) {
                    String contactName = (String) mfilterList.get(i).get(Contacts.CONTACTKEY);
                    String contactNo = (String) mfilterList.get(i).get(Contacts.DURATION);
                    contactName = contactName.toLowerCase();
                    constraint = (CharSequence) constraint.toString().toLowerCase();
                    if (contactName.contains(constraint)) {
                        filterListbk.add(mfilterList.get(i));
                    }
                    if (contactNo.contains(constraint)) {
                        filterListbk.add(mfilterList.get(i));
                    }

                    results.count = filterListbk.size();

                    results.values = filterListbk;
                }

            } else {
                results.count = mfilterList.size();

                results.values = mfilterList;

            }

            return results;


        }


        //Invoked in the UI thread to publish the filtering results in the user interface.
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            //  adapter.players= (ArrayList<Player>) results.values;
            adapter.Books = (ArrayList<HashMap<String, Object>>) results.values;

            String new_result = results.values.toString();

            if(!new_result.equals(null)){
                adapter.Books = (ArrayList<HashMap<String, Object>>) results.values;
                adapter.notifyDataSetChanged();
                Intent intent = new Intent();
                intent.setAction(SipManager.ACTION_NO_RECORD_FOUND);
                Bundle args = new Bundle();
                args.putSerializable("result",(Serializable)adapter.Books);
                args.putSerializable("flag","0");
                intent.putExtra("BUNDLE",args);
                /*intent.putExtra("flag","0");
                intent.putExtra("result",adapter.Books);*/
                // add data
                ctx.sendBroadcast(intent);
            }

            if(new_result.equals("[]")){
                Intent intent = new Intent();
                intent.setAction(SipManager.ACTION_NO_RECORD_FOUND);
                //intent.putExtra("flag","1");
                Bundle args = new Bundle();
                args.putSerializable("result",(Serializable)adapter.Books);
                args.putSerializable("flag","1");
                intent.putExtra("BUNDLE",args);

                ctx.sendBroadcast(intent);
            }
            //adapter.Books.clear();
            notifyDataSetChanged();

        }


    }

下面是我的代码片段

public class Contacts extends Fragment implements OnBackPressListener {
    IndexFastScrollRecyclerView mRecyclerView;
    private List<String> mDataArray;
    public static boolean isVisible = false;
    ContactsAdapter adapter;
    DatabaseHelper dbHelp;
    public static final String CONTACTID = "contactid";
    public static final String CONTACTKEY = "contactname";
    public static final String CONTACTFAV = "contactfav";
    public static final String CONTACTNUM = "contactno";
    public static final String DURATION = "duration";
    public static final String SIP = "sip";
    public static final String SIP_USER = "sip_user";


    public String sip_label = "";//"Aniphones";
    public String not_sip_label = "";
    public int flag = 0;
    public Cursor cursor;
    public ArrayList<HashMap<String, Object>> myBooks;
    public ArrayList<HashMap<String, Object>> myBooks1;
    public ArrayList<String> ContactSimpleList;
    public HashMap<String, Object> hm;
    public Long id;
    public String getname = "";
    public DatabaseHelper dbhelp;
    public SharedPreferences.Editor edit;
    public TextView no_contacts;
    public String contact = "";
    public Phonenumber.PhoneNumber number = null;
    public PhoneNumberUtil phoneUtil;
    public String dynamic_table = "";
    FloatingActionButton fab;
    String test = "", sip_user_pref = "";
    Context ctx;

    String service_start;
    private TextWatcher mSearchTw;
    private EditText etAllContSearch;
    View rootView;
    public String name = "", balance = "";
    public static final int PREMISSION_CONTACT_REQUEST_CODE = 1;
    private Background_allcontacts mBackground_allcontacts = null;
    AlertDialog spotDialog = null;
    private List<AlphabetItem> mAlphabetItems;
    PrefManager pref;
    HashMap<String, String> credential;
    GlobalClass gc;
    ViewPager viewPager;
    boolean isCallPlaced = true;
    Object selectedItem;
    boolean is_called_from_filter = false;
    public ArrayList<HashMap<String, Object>> filterBook;


    private BroadcastReceiver mNoRecordFound = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Extract data included in the Intent
            if (intent.getAction().equals(SipManager.ACTION_NO_RECORD_FOUND)) {
                Bundle args = intent.getBundleExtra("BUNDLE");
                String flag = args.getString("flag");
                //String flag = intent.getExtras().getString("flag");
                if(flag.equals("1")){
                    no_contacts.setVisibility(View.VISIBLE);

                }
                else {
                    is_called_from_filter = true;
                    ArrayList<HashMap<String, Object>> object = (ArrayList<HashMap<String, Object>>) args.getSerializable("result");
                    filterBook = object;

                    no_contacts.setVisibility(View.INVISIBLE);
                }
            }

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        setHasOptionsMenu(true);
        Fabric.with(getActivity(), new Crashlytics());
        getActivity().invalidateOptionsMenu();
        rootView = inflater.inflate(R.layout.contact_tab, container,
                false);
        ctx = getContext();
        pref = new PrefManager(getActivity());


        mRecyclerView = (IndexFastScrollRecyclerView) rootView.findViewById(R.id.fast_scroller_recycler);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager = new MyCustomLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.smoothScrollToPosition(0);

        gc = GlobalClass.getInstance();

        no_contacts = (TextView) rootView.findViewById(R.id.no_contacts);
        spotDialog = new SpotsDialog(ctx, R.style.CustomSpotDialog);



        ctx = getContext();
        dbhelp = new DatabaseHelper(ctx);
        initialiseData();
        initialiseUI();
        etAllContSearch = (EditText) rootView.findViewById(R.id.etAllContSearch);
        etAllContSearch.requestFocus();

        etAllContSearch.setOnTouchListener(Contacts.this);
        etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(R.drawable.search_icon, 0, 0, 0);

        mSearchTw = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {




                if (etAllContSearch.getText().toString().trim().length() > 0) {
                    etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.closesicon, 0);

                    mRecyclerView.setIndexBarVisibility(true);
                } else {
                    etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(R.drawable.search_icon, 0, 0, 0);

                    mRecyclerView.setIndexBarVisibility(false);
                }
                if (adapter != null) {
                    //if (!adapter.isEmpty()) {
                    System.out.println("Test: Result do in search " + s);
                    adapter.getFilter().filter(s);
                    mRecyclerView.setIndexBarVisibility(true);

                    //}
                }


            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (etAllContSearch.getText().toString().length() == 0 || etAllContSearch.getText().toString() == "") {

                    mRecyclerView.setIndexBarVisibility(true);

                } else {
                    mRecyclerView.setIndexBarVisibility(false);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAllContSearch.getText().toString().length() == 0 || etAllContSearch.getText().toString() == "") {

                    mRecyclerView.setIndexBarVisibility(true);

                } else {
                    mRecyclerView.setIndexBarVisibility(false);

                }
            }

        };



        myBooks = new ArrayList<HashMap<String, Object>>();
        myBooks1 = new ArrayList<HashMap<String, Object>>();
        ContactSimpleList = new ArrayList<String>();

        service_start = PreferenceManager.getDefaultSharedPreferences(ctx).getString(Settings.PREF_SERVICE_START + "", Settings.DEFAULT_SERVICE_START);
        Log.d(TAG, "contact_sync service flag" + service_start);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkPermission()) {
                Log.d(TAG, "inside check permission" + service_start);
                if (service_start.equals("0")) {
                    no_contacts.setVisibility(View.VISIBLE);
                    no_contacts.setText(getResources().getString(R.string.synchronize_contacts));
                } else {
                    //  hideDialog();
                    no_contacts.setVisibility(View.GONE);
                    System.out.println("Test: Result oncreate ");
                    if (mBackground_allcontacts == null) {
                        mBackground_allcontacts = new Background_allcontacts();
                        mBackground_allcontacts.execute();
                    }

                }
            } else {
                requestPermission();
            }
        } else {
            Log.d(TAG, "else " + service_start);
            if (service_start.equals("0")) {
                no_contacts.setVisibility(View.VISIBLE);
                no_contacts.setText(getResources().getString(R.string.synchronize_contacts));

            } else {
                // hideDialog();
                no_contacts.setVisibility(View.GONE);
                if (mBackground_allcontacts == null) {
                    mBackground_allcontacts = new Background_allcontacts();
                    mBackground_allcontacts.execute();
                }

            }
        }

        etAllContSearch.addTextChangedListener(mSearchTw);

        IntentFilter iFilter_NorecordFound = new IntentFilter(SipManager.ACTION_NO_RECORD_FOUND);
        getActivity().registerReceiver(mNoRecordFound, iFilter_NorecordFound);

        return rootView;
    }


    protected void initialiseData() {
        //Recycler view data
        mDataArray = DataHelper.getAlphabetData();

        //Alphabet fast scroller data
        mAlphabetItems = new ArrayList<>();
        List<String> strAlphabets = new ArrayList<>();
        for (int i = 0; i < mDataArray.size(); i++) {
            String name = mDataArray.get(i);
            if (name == null || name.trim().isEmpty())
                continue;

            String word = name.substring(0, 1);
            if (!strAlphabets.contains(word)) {
                strAlphabets.add(word);
                mAlphabetItems.add(new AlphabetItem(i, word, false));
                // mAlphabetItems.add(new AlphabetItem(i, word, false));
            }
            mRecyclerView.smoothScrollToPosition(i);

        }
    }


    protected void initialiseUI() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


        mRecyclerView.setIndexTextSize(12);
        mRecyclerView.setIndexBarColor("#FFFFFF");
        mRecyclerView.setIndexBarCornerRadius(0);
        mRecyclerView.setIndexBarTransparentValue((float) 0.4);
        mRecyclerView.setIndexbarMargin(0);
        mRecyclerView.setIndexbarWidth(30);

        mRecyclerView.setPreviewPadding(0);
        mRecyclerView.setIndexBarTextColor("#2d4278");
        mRecyclerView.setIndexBarVisibility(true);
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private void requestPermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS) && ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_CONTACTS)) {

            Toast.makeText(getActivity(), "Until you grant the permission, we canot display the contacts.", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, Contacts.PREMISSION_CONTACT_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case Contacts.PREMISSION_CONTACT_REQUEST_CODE:
                if (grantResults.length > 0) {
                    // Contacts permission
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        if (service_start.equals("0")) {
                            Toast.makeText(getActivity(), getResources().getString(R.string.synchronize_contacts), Toast.LENGTH_SHORT).show();
                        } else {
                            new Background_allcontacts().execute();
                        }
                    } else {
                        Toast.makeText(getActivity(), "Until you grant the permission, we canot display the contacts.", Toast.LENGTH_LONG).show();

                    }
                }
                break;
        }
    }

    public void nodata() {
        // TODO Auto-generated method stub
        no_contacts.setText(getString(R.string.no_sip_contacts));
        no_contacts.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle outState) {
        super.onActivityCreated(outState);
        if (adapter != null) {
            adapter.saveStates(outState);
        }
    }


    @Override
    public void onViewStateRestored(@Nullable Bundle inState) {
        super.onViewStateRestored(inState);
        if (adapter != null) {
            adapter.restoreStates(inState);
        }
    }



    @Override
    public void onResume() {

        super.onResume();
        isCallPlaced = true;
        pref.set_is_ongoing_call_flag(false);
        mRecyclerView.setVisibility(View.VISIBLE);
        getActivity().invalidateOptionsMenu();
        System.out.println("Test: Result onresume ");

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        if (isVisibleToUser && this.isVisible()) {

            viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
            if (viewPager.getCurrentItem() == 1) {
                gc.hideKeypad(getActivity());
                spotDialog.hide();

                if (adapter != null) {
                    adapter.getFilter().filter(etAllContSearch.getText().toString());
                    mRecyclerView.setIndexBarVisibility(true);

                }

            }

        }
        super.setUserVisibleHint(isVisibleToUser);

    }

    @Override
    public boolean onBackPressed() {
        return new BackPressImpl(this).onBackPressed();
    }

    public void getdata() {
        if (mBackground_allcontacts == null) {
            mBackground_allcontacts = new Background_allcontacts();
            mBackground_allcontacts.execute();
        }
    }

    public void getdata(String from, String value) {

        if (mBackground_allcontacts == null) {
            mBackground_allcontacts = new Background_allcontacts(from, value);
            mBackground_allcontacts.execute();

        }
    }

    //Himadri
    //Unregister all receiver when view destroy
    @Override
    public void onDestroyView() {
        try {
            //Here is the code for stopping some service

        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroyView();
    }


    public class Background_allcontacts extends AsyncTask<Void, Integer, Void> {

        String from;
        String value;

        public Background_allcontacts() {

        }

        public Background_allcontacts(String from, String value) {
            // TODO Auto-generated constructor stub
            this.from = from;
            this.value = value;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            //  showDialog();

        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            String dynamic_table = PreferenceManager.getDefaultSharedPreferences(ctx).getString(Settings.PREF_DYNAMIC_TABLE + "", Settings.DEFAULT_DYNAMIC_TABLE);
            if (dynamic_table != null) {
                if (!dynamic_table.equals(Settings.DEFAULT_DYNAMIC_TABLE)) {
                    cursor = dbhelp.fetchcalllog("select contact_id,contact_name,contact_num, fav,contactImage from '" + dynamic_table + "' order by UPPER(contact_name)");
                }
            }

            return null;
        }

        // @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            try {
                ContactSimpleList = new ArrayList<String>();
                if (cursor != null) {

                    if (cursor.getCount() == 0) {
                        nodata();

                    } else if (cursor.getCount() > 0) {
                        no_contacts.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                        etAllContSearch.setVisibility(View.VISIBLE);
                        test = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(Settings.PREF_SIPARRAY + "", Settings.DEFAULT_SIPARRAY);

                        sip_user_pref = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(Settings.PREF_SIPUSERARRAY + "", Settings.DEFAULT_SIPARRAY);
                        String[] separated = null, sipUser = null;

                        if (test != null && test.length() != 0) {
                            if (test.charAt(test.length() - 1) == ',') {
                                test = test.substring(0, test.length() - 1);
                            } else if (sip_user_pref.charAt(sip_user_pref.length() - 1) == ',') {
                                sip_user_pref = sip_user_pref.substring(0, sip_user_pref.length() - 1);
                            }

                            // Log.v("sip contacts",test);
                            if (test.contains(",")) {
                                separated = test.split(",");
                                sipUser = sip_user_pref.split(",");
                            }
                        }
                        myBooks.clear();
                        // cursor.moveToFirst();
                        while (cursor.moveToNext()) {

                            String id = "", name = "", phoneNumber = "", phoneFav = "", contactImg = "";
                            try {
                                id = cursor.getString(0);
                                name = cursor.getString(1);
                                phoneNumber = cursor.getString(2);
                                phoneFav = cursor.getString(3);
                                contactImg = cursor.getString(4);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            phoneNumber = phoneNumber.replaceAll("\\D", "");


                            if (test.contains(",")) {
                                for (int j = 0; j < separated.length; j++) {
                                    if (Arrays.asList(separated).contains(phoneNumber)) {
                                        if (separated[j].equals(phoneNumber)) {
                                            hm = new HashMap<String, Object>();
                                            hm.put(CONTACTID, id);
                                            hm.put(CONTACTKEY, name);
                                            hm.put(DURATION, phoneNumber);
                                            hm.put(CONTACTFAV, phoneFav);
                                            hm.put("contactImage", contactImg);
                                            hm.put(SIP, sip_label);
                                            hm.put(SIP_USER, sipUser[j]);
                                            myBooks.add(hm);
                                            myBooks1.add(hm);
                                            ContactSimpleList.add(phoneNumber);
                                        }
                                    } else {
                                        hm = new HashMap<String, Object>();
                                        hm.put(CONTACTID, id);
                                        hm.put(CONTACTKEY, name);
                                        hm.put(DURATION, phoneNumber);
                                        hm.put(CONTACTFAV, phoneFav);
                                        hm.put("contactImage", contactImg);
                                        hm.put(SIP, not_sip_label);
                                        hm.put(SIP_USER, "");
                                        myBooks.add(hm);
                                        myBooks1.add(hm);
                                        ContactSimpleList.add(phoneNumber);

                                    }


                                }
                            } else {
                                if (Arrays.asList(test).contains(phoneNumber)) {
                                    hm = new HashMap<String, Object>();
                                    hm.put(CONTACTID, id);
                                    hm.put(CONTACTKEY, name);
                                    hm.put(DURATION, phoneNumber);
                                    hm.put(CONTACTFAV, phoneFav);
                                    hm.put("contactImage", contactImg);
                                    hm.put(SIP, sip_label);
                                    hm.put(SIP_USER, sip_user_pref);
                                    myBooks.add(hm);
                                    myBooks1.add(hm);
                                    ContactSimpleList.add(phoneNumber);

                                } else {
                                    hm = new HashMap<String, Object>();
                                    hm.put(CONTACTID, id);
                                    hm.put(CONTACTKEY, name);
                                    hm.put(DURATION, phoneNumber);
                                    hm.put(CONTACTFAV, phoneFav);
                                    hm.put("contactImage", contactImg);
                                    hm.put(SIP, not_sip_label);
                                    hm.put(SIP_USER, "");
                                    myBooks.add(hm);
                                    myBooks1.add(hm);
                                    ContactSimpleList.add(phoneNumber);

                                }

                            }
                        }
                    }
                    Set<HashMap<String, Object>> unique = new LinkedHashSet<HashMap<String, Object>>(myBooks);
                    myBooks = new ArrayList<HashMap<String, Object>>(unique);

                    Set<String> unique1 = new LinkedHashSet<String>(ContactSimpleList);
                    ContactSimpleList = new ArrayList<String>(unique1);


                    gc.setContactsList(ctx, myBooks);
                    gc.setContactListSimpleNum(ctx, ContactSimpleList);

                    adapter = new ContactsAdapter(myBooks, getActivity(), "ALL_CONTACT", mDataArray, false);
                    mRecyclerView.setAdapter(adapter);

                }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mBackground_allcontacts = null;
                }

                super.onPostExecute(result);
            }

        }

    }

0 个答案:

没有答案