如何在Android中将搜索功能添加到自定义联系人列表

时间:2018-10-04 17:24:16

标签: android listview searchbar

我想将搜索功能添加到联系人列表中,以便根据姓名或号码搜索联系人。我添加了编辑文本,并添加了onText更改侦听器,但是我感到困惑,哪些数据将被传递到,以及如何将数据传递到搜索栏。请对此进行一些澄清。这是我用于显示联系人的代码:

public class Split extends AppCompatActivity implements AdapterView.OnItemClickListener {
    public  static  String TAG = "amount";
    ListView mainListView;
    ProgressDialog pd;
    //String arr=new String[100];
    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    final static List<String> name1 = new ArrayList<>();
    List<String> phno1 = new ArrayList<>();
    List<Long> bal = new ArrayList<>();
    List<Bitmap> img = new ArrayList<>();
    //ArrayList<String> namelist= new ArrayList<>();
    MyAdapter ma;
    private SearchView mSearchView;
    Button select;
    int amount=100;
    float result;
    String ph;
    String phoneNumber;
    EditText search;
    private FirebaseAuth mAuth;
    FirebaseUser firebaseUser;
    ArrayAdapter adapter;
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    @SuppressLint("StaticFieldLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitle("Split");
        if(getSupportActionBar()!= null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.split);
        mAuth = FirebaseAuth.getInstance();
        search = findViewById(R.id.search_bar);
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        final List<String> phonenumber = new ArrayList<>();
        System.out.print(phonenumber);

        mainListView = findViewById(R.id.listview);
        showContacts();
        select = findViewById(R.id.button1);

        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text


            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts = new StringBuilder();
                ArrayList checkedcontacts1 = new ArrayList();
                ArrayList names = new ArrayList();
                System.out.println(".............." + (ma.mCheckStates.size()));
                System.out.println("name size is" + name1.size());
                int a = ma.mCheckStates.size();
                result = ((float) amount / a);
                System.out.println("final1 amount is "+result);
                long result1=(long) result;
                System.out.println("final amount is "+result1);

                for(int k =0;k<=a;k++){

                    bal.add(result1);
                }
                System.out.println("balance"+bal);
                System.out.println("selected contacts split amount"+result);

                for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount

                {
                    if (ma.mCheckStates.get(i)) {
                        checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
                        checkedcontacts1.add((phno1.get(i)));

                        names.add((name1.get(i)));
                        checkedcontacts.append("\n");
                        System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);

                    }


                }



                System.out.println("checked names"+names);
                System.out.println(
                        "checkec contcts foggfgfgfgfgf"+ checkedcontacts1
                );

                List<Object> list = new ArrayList<>();

                for(Object i : checkedcontacts1) {
                    list.add(i);
                }

                System.out.println("checked contacts size is" + checkedcontacts1.size());
                HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();

                for (int i = 0; i < checkedcontacts1.size(); i++) {
                    HashMap<String, Object> entry = new HashMap<>();
                    entry.put("PhoneNumber",list.get(i));
                    entry.put("Name",names.get(i));

                    System.out.println("entry is"+entry);
                    for (int j = i; j <= i; j++) {
                        System.out.println("phonenumber" + i + ":" + list.get(i));
                        System.out.println("amount" + j + ":" + bal.get(j));
                        //dataToSave.put("phonenumber" +i, list.get(i));
                        entry.put("Amount", bal.get(j));

                    }
                    Invites.put("Invite" + i, entry);

                }
                FirebaseFirestore db = FirebaseFirestore.getInstance();
                db.collection("deyaPayUsers").document(Objects.requireNonNull(mAuth.getUid())).collection("Split").document(mAuth.getUid()).collection("SentInvitations")
                        .add(Invites)
                        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                            @Override
                            public void onSuccess(DocumentReference documentReference) {
                                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());

                            }
                        });
                Intent intent = new Intent(Split.this, Display.class);
                intent.putExtra("selected", checkedcontacts.toString().split(","));
                startActivity(intent);

                    /*db.collection("deyaPayUsers").document(mAuth.getUid().toString()).collection("Split").document(mAuth.getUid().toString()).collection("SentInvitations").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                for (DocumentSnapshot document : task.getResult()) {
                                    Log.d(TAG, document.getId() + " => " + document.getData());
                                }
                            } else {
                                Log.d(TAG, "Error getting documents: ", task.getException());
                            }
                        }
                    });*/


            }



        });

        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected void onPreExecute()
            {
                pd = ProgressDialog.show(Split.this,
                        "Loading..", "Please Wait", true, false);
            }// End of onPreExecute method

            @Override
            protected Void doInBackground(Void... params)
            {
                getAllContacts();
                return null;
            }// End of doInBackground method

            @Override
            protected void onPostExecute(Void result)
            {
                pd.dismiss();
                MyAdapter ma = new MyAdapter(Split.this);
                // ArrayAdapter<String>   arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);

        mainListView.setAdapter(ma);
        mainListView.setItemsCanFocus(false);
        mainListView.setTextFilterEnabled(true);
        mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

            }//End of onPostExecute method
        }.execute((Void[]) null);

    }
    public void onDestroy(){
        super.onDestroy();
        if ( pd!=null && pd.isShowing() ){
            pd.cancel();
        }
    }

    private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
    {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
    }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
                                           @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
                showContacts();
            } else {
                Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void getAllContacts() {
        // it displays the contact phonenumber and name rom the phone book. and add to the list.
        ContentResolver cr = getContentResolver();
        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);


        assert phones != null;
        while (phones.moveToNext()) {
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phoneNumberWithOutCountryCode();
            String contactId = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//
            Bitmap bitmap = loadContactPhoto(
                    getContentResolver(), Long.valueOf(contactId));

            name1.add(name);

            img.add(bitmap);


        }


        phones.close();
        System.out.println("count is" + img.size());
    }

    public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
        Uri uri = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, id);
        InputStream input = ContactsContract.Contacts
                .openContactPhotoInputStream(cr, uri);
        if (input == null) {
            return null;
        }
        return BitmapFactory.decodeStream(input);
    }


    private void phoneNumberWithOutCountryCode() {
        try {
            // phone must begin with '+'
            if(phoneNumber.startsWith("+")) {
                System.out.println("hello yam");
                PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
                Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "");
                int countryCode = numberProto.getCountryCode();
                long nationalNumber = numberProto.getNationalNumber();
                Log.i("code", "code " + countryCode);
                Log.i("code", "national number " + nationalNumber);
                ph = String.valueOf(nationalNumber);
                phno1.add(ph);
                // selectedphonenumber.setText(ph);
            }
            else{
                String nospacenum = phoneNumber.replaceAll("[\\s\\-()]", "");
                System.out.print("hii"+nospacenum);
                phno1.add(nospacenum);
                // selectedphonenumber.setText(nospacenum);
            }
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }

    }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        ma.toggle(arg2);

    }

    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener{// this class is for to check the contacts for spliting the amount.
        public SparseBooleanArray mCheckStates;
        LayoutInflater mInflater;

        private Context mContext;


       // List list;

        MyAdapter(Context context) {
            mCheckStates = new SparseBooleanArray(name1.size());
            mContext = context;
            // System.out.println(mCheckStates);
            //System.out.println(name1.size());
            //System.out.println(name1);
            // inflate custom listview
            mInflater = (LayoutInflater) Split.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

//        public MyAdapter(Context context)
//        {
//            mContext = context;
//        }//End of CustomAdapter constructor

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub

            return position;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) { // this method set the phone number and name rom the list to the textviews.
            // TODO Auto-generated method stub
            ViewHolder holder;
            final int pos = position;
            View vi = convertView;
            if (convertView== null) {

                holder = new ViewHolder();
                vi = mInflater.inflate(R.layout.row, null);//false rasa..

                holder.tv = vi.findViewById(R.id.name);
                holder.tv1 = vi.findViewById(R.id.mobile);
                holder.checkbox = vi.findViewById(R.id.check);

                holder.image = vi.findViewById(R.id.image);
                convertView.setTag(holder);

            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }//End of else
            holder.checkbox.setId(position);
            holder.tv.setId(position);
            holder.tv1.setId(position);
            holder.tv.setText( name1.get(position));
            holder.tv1.setText( phno1.get(position));

//            if(img.get(position)!= null) {
//                image.setImageBitmap(img.get(position));
//            }
//            else
//            {
//                image = vi.findViewById(R.id.image);
//            }


            holder.checkbox.setTag(position);
            holder.checkbox.setChecked(mCheckStates.get(position, false));
            holder.checkbox.setOnCheckedChangeListener(this);


            return vi;
        }

        boolean isChecked(int position) {// it returns the checked contacts
            return mCheckStates.get(position, false);
        }

        void setChecked(int position, boolean isChecked) { //set checkbox postions if it sis checked
            mCheckStates.put(position, isChecked);
            System.out.println("hello...........");
            notifyDataSetChanged();
        }

        void toggle(int position) {
            setChecked(position, !isChecked(position));
        }


        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

            if(isChecked){
                mCheckStates.put((Integer)compoundButton.getTag(), true);
            }
            else {
                mCheckStates.delete((Integer)compoundButton.getTag());
            }

        }

    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            startActivity(new Intent(this,deyaPay.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
    public void onBackPressed(){
        Intent i = new Intent(Split.this,deyaPay.class);
        startActivity(i);
finish();


    }
    static class ViewHolder {
        TextView tv;
        TextView tv1;
        CheckBox checkbox;
        ImageView image;
        int id;
    }
}

0 个答案:

没有答案