首页 > 解决方案 > 如何从 LongSparseArray 中获取值?

问题描述

我用复选框实现了显示联系人。当我选择多个联系人并单击按钮时,它会显示此错误“

尝试在空对象引用上调用虚拟方法 'boolean java.lang.Boolean.booleanValue()'

. 在 mCustomAdapter.mCheckedStates.get(i)。所以我在适配器类中这样写的是“

mCheckedStates = new LongSparseArray<>(ContactList.size())

并且在分配一些值后再次显示相同的错误。当我打印 mCustomAdapter.mCheckedStates.size 的大小时,它会显示我选择的联系人数量的正确值,但是在获取该值时会显示错误。如何解决?

这是我的适配器类:

 public class Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener

    {
//        public SparseBooleanArray mCheckStates;
       LongSparseArray<Boolean> mCheckedStates = new LongSparseArray<>();
        private ArrayList<COntactsModel> ContactList;
        private Context mContext;
        private LayoutInflater inflater;
        private ValueFilter valueFilter;
        ArrayList<COntactsModel> ContactListCopy ;

        public Splitadapter(Context context, ArrayList<COntactsModel> ContactList) {
            super();
            mContext = context;
            this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.ContactList = ContactList;
            this.ContactListCopy = this.ContactList;
            mCheckedStates = new LongSparseArray<>(ContactList.size());
            System.out.println("asdfghjk" + mCheckedStates);
            getFilter();

        }//End of CustomAdapter constructor


        @Override
        public int getCount() {
            return ContactListCopy.size();
        }

        @Override
        public Object getItem(int position) {
            return ContactListCopy.get(position).getName();
        }

        @Override
        public long getItemId(int position) {
            return ContactListCopy.get(position).getId();
        }




        public class ViewHolder {
            TextView textviewName;
            TextView textviewNumber;
            CheckBox checkbox;

            Button b;
            int id;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            final int pos = position;
            //
            if (convertView == null) {
                holder = new ViewHolder();

                convertView = LayoutInflater.from(mContext).inflate(R.layout.list, null);
                holder.textviewName = (TextView) convertView.findViewById(R.id.name);
                holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
                holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
                holder.b = convertView.findViewById(R.id.round_icon);
                convertView.setTag(holder);
            }//End of if condition
            else {
                holder = (ViewHolder) convertView.getTag();
            }//End of else
            COntactsModel c = ContactListCopy.get(position);
            holder.textviewName.setText(c.getName());
            holder.textviewNumber.setText(c.getPhonenum());
            holder.checkbox.setTag(c.getId());
            holder.checkbox.setChecked(mCheckedStates.get(c.getId(), false));
            holder.checkbox.setOnCheckedChangeListener(this);
            holder.b.setText(c.getName().substring(0,1));



            //holder.id = position;

            return convertView;
//        }//End of getView method

        }

        boolean isChecked(long id) {// it returns the checked contacts
            return mCheckedStates.get(id, false);
        }

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

        void toggle(long id) {
            setChecked(id, !isChecked(id));
        }


        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                mCheckedStates.put((Long) buttonView.getTag(), true);
            } else {
                mCheckedStates.delete((Long) buttonView.getTag());
            }

        }

        @Override
        public Filter getFilter() {
            if (valueFilter == null) {

                valueFilter = new ValueFilter();

            }

            return valueFilter;
        }

        private class ValueFilter extends Filter {

            //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<COntactsModel> filterList = new ArrayList<COntactsModel>();
                    for (int i = 0; i < ContactList.size(); i++) {
                        COntactsModel ca = ContactList.get(i);
                        if ((ca.getName().toUpperCase())
                                .contains(constraint.toString().toUpperCase())) {

                            //COntactsModel contacts = new COntactsModel();
                            filterList.add(ca);
                        }
                    }
                    results.count = filterList.size();
                    results.values = filterList;
                } else {
                    results.count = ContactList.size();
                    results.values = ContactList;
                }
                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) {
                ContactListCopy = (ArrayList<COntactsModel>) results.values;
                notifyDataSetChanged();
            }
        }
        }

这是我的主要活动:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    public  static  String TAG = "amount";
    ListView mainListView;
    ProgressDialog pd;
    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<>();
    private Splitadapter mCustomAdapter;
    private ArrayList<COntactsModel> _Contacts = new ArrayList<COntactsModel>();
    HashSet<String> names = new HashSet<>();
    Set<String>phonenumbers = new HashSet<>();

    Button select;
    int amount=100;
    float result;
    String ph;
    String phoneNumber;
    EditText search;
    String contactID;
    String name;
//    private FirebaseAuth mAuth;
//    FirebaseUser firebaseUser;
//
//    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.activity_main);

        search = findViewById(R.id.search_bar);

        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 chan ged the Text


                mCustomAdapter.getFilter().filter(cs.toString());


//

            }

            @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


                //ma.filter(text);
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts = new StringBuilder();
                ArrayList checkedcontacts1 = new ArrayList();
                ArrayList names = new ArrayList();
                System.out.println(".............." + (mCustomAdapter.mCheckedStates.size()));
                System.out.println("name size is" + name1.size());
                int a = mCustomAdapter.mCheckedStates.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);
                System.out.println("names" + name1.size());
//                int  as = name1.size();
//                mCustomAdapter.mCheckedStates = new LongSparseArray<>(as);
                System.out.println("cjgygytygh" + mCustomAdapter.mCheckedStates);

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

                {
                    System.out.println("checked contcts" + mCustomAdapter.mCheckedStates.get(i));

                    if (mCustomAdapter.mCheckedStates.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);

                }

                Intent intent = new Intent(MainActivity.this, Display.class);
                intent.putExtra("selected", checkedcontacts1.toString().split(","));
                startActivity(intent);




            }


        });

    }

    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);
    }
    else {

        mCustomAdapter   = new Splitadapter(MainActivity.this,_Contacts);
        //ArrayAdapter<String>   arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
        mainListView.setAdapter(mCustomAdapter);
        mainListView.setOnItemClickListener(this);
        mainListView.setItemsCanFocus(false);
        mainListView.setTextFilterEnabled(true);
        getAllContacts();

    }

    }
    @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();
        String[] PROJECTION = new String[] {
                ContactsContract.RawContacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
                ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String filter = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
        String order = ContactsContract.Contacts.DISPLAY_NAME + " ASC";

        Cursor phones = cr.query(uri, PROJECTION, filter, null, order);
        while (phones.moveToNext()) {
            long id = phones.getLong(phones.getColumnIndex(ContactsContract.Data._ID));
            name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            _Contacts.add(new COntactsModel(id,name,phoneNumber));
            name1.add(name);
            phno1.add(phoneNumber);




        }




        phones.close();



    }


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



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

    }

这是我的模型类:

public class COntactsModel
{
    String phonenum;
     long id;
    String cname;
    boolean selected = false;

    public COntactsModel(long id, String name,String phonenumber) {
        this.id = id;
        this.cname = name;
        this.phonenum = phonenumber;
    }
    public long getId() {
        return this.id;
    }
    public String getName() {
        return this.cname;
    }
    public String getPhonenum() {
        return this.phonenum;
    }
}

如何解决该错误?

标签: javaandroid

解决方案


推荐阅读