如何使用SharedPreferences保存SparseBooleanArray?或者任何其他选择



我想使用SharedPreferences或其他更可取的方法保存SparseBooleanArray。

我试过使用https://stackoverflow.com/a/16711258/2530836,但每次创建活动时,都会重新初始化bundle,bundle.getParcelable()返回null。我确信有一个解决办法,但经过几个小时的头脑风暴,我还没有找到。

此外,如果没有,我可以使用类似SharedPreferences的东西吗?

这是代码:

public class ContactActivity extends Activity implements AdapterView.OnItemClickListener {
    List<String> name1 = new ArrayList<String>();
    List<String> phno1 = new ArrayList<String>();
    ArrayList<String> exceptions = new ArrayList<String>();
    MyAdapter adapter;
    Button select;
    Bundle bundle = new Bundle();
    Context contactActivityContext;
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts_layout);
        getAllContacts(this.getContentResolver());
        ListView list= (ListView) findViewById(R.id.lv);
        adapter = new MyAdapter();
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        list.setItemsCanFocus(false);
        list.setTextFilterEnabled(true);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        select = (Button) findViewById(R.id.button1);
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts = new StringBuilder();
                for (int i = 0; i < name1.size(); i++)
                {
                    if (adapter.isChecked(i)) {
                        checkedcontacts.append(name1.get(i).toString());
                        exceptions.add(name1.get(i).toString());
                        checkedcontacts.append(", ");
                    }
                }
                checkedcontacts.deleteCharAt(checkedcontacts.length() - 2);
                checkedcontacts.append("selected");
                editor = prefs.edit();
                editor.putInt("Status_size", exceptions.size()); /* sKey is an array */
                for(int i=0;i<exceptions.size();i++)
                {
                    editor.remove("Status_" + i);
                    editor.putString("Status_" + i, exceptions.get(i));
                }
                editor.commit();
                Toast.makeText(ContactActivity.this, checkedcontacts, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        adapter.toggle(arg2);
    }
    private void setContext(Context contactActivityContext){
        this.contactActivityContext = contactActivityContext;
    }
    protected Context getContext(){
        return contactActivityContext;
    }
    public  void getAllContacts(ContentResolver cr) {
        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC" );
        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            name1.add(name);
            phno1.add(phoneNumber);
        }
        phones.close();
    }
    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
    {   SparseBooleanArray mCheckStates;
        ContactActivity mContactActivity = new ContactActivity();
        LayoutInflater mInflater;
        TextView tv1,tv;
        CheckBox cb;
        int mPos;
        MyAdapter()
        {
            mCheckStates = new SparseBooleanArray(name1.size());
            mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
            mInflater = (LayoutInflater) ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }
        public void setPosition(int p){
            mPos = p;
        }
        public int getPosition(){
            return mPos;
        }

        @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 0;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi=convertView;
            if(convertView==null)
            vi = mInflater.inflate(R.layout.row, null);
            tv= (TextView) vi.findViewById(R.id.textView1);
            tv1= (TextView) vi.findViewById(R.id.textView2);
            cb = (CheckBox) vi.findViewById(R.id.checkBox1);
            tv.setText("Name :"+ name1.get(position));
            tv1.setText("Phone No :"+ phno1.get(position));
            cb.setTag(position);
            cb.setChecked(mCheckStates.get(position, false));
            setPosition(position);
            cb.setOnCheckedChangeListener(this);
            return vi;
        }
        public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }
        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
        }
        public void toggle(int position) {
            setChecked(position, !isChecked(position));
        }
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mCheckStates.put((Integer) buttonView.getTag(), isChecked);
        }
    }
    @Override
    public void onDestroy(){
        bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
        super.onDestroy();
    }
}

您可以将其存储在SharedPreferences中sparsebolinarrays的特点是:它将整数映射为布尔值,因此您可以将其保存为字符串,去掉大括号、空格和=符号,您只需要一个int值(表示索引值)和相应的布尔值,用逗号分隔,现在相应地使用该字符串。希望有帮助:)

Bundle由您在类中创建,活动不使用它来存储值。

如果您使用的是应用程序捆绑包,那么一旦您终止应用程序,仍然无法获得实例。

如果你有问题,最好使用共享偏好,但在共享偏好中,你不能存储对象。

如果你想使用共享偏好,那么有两种解决方案。

  • 将对象转换为字符串并存储在共享的首选项中,然后从字符串中检索并修改对象。(使用Gson或Jackson,或者您更喜欢的方式)
  • 使用复杂的首选项第三方之一,在那里您可以存储对象并直接检索

如果您只对使用bundle更感兴趣,请查看stackoverflow上的讨论。

将捆绑包保存到共享引用

如何批量化捆绑

希望这对你有帮助。

相关内容

最新更新