java - 如何使用 SharedPreferences 保存 SparseBooleanArray?或者还有其他选择吗?

标签 java android sharedpreferences

我想使用 SharedPreferences 或其他更推荐的方式保存 SparseBooleanArray。

我尝试过使用https://stackoverflow.com/a/16711258/2530836 ,但每次创建 Activity 时,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();
    }
}

最佳答案

您可以将其存储在 SharedPreferances 中 稀疏 boolean 数组的特点是:它将整数映射到 boolean 值,因此您可以将其保存为字符串,消除大括号、空格和=符号,您拥有的只是一个 int 值(用于索引值)和相应的 boolean 值,用逗号分隔,现在相应地使用该字符串。希望它有帮助:)

关于java - 如何使用 SharedPreferences 保存 SparseBooleanArray?或者还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26439951/

相关文章:

android - Samsung Galaxy S2 OpenGl ES 2.0 问题

android - 在 android-sdk 目录中找不到示例

android - 如何在 SharedPreferences RecyclerView 中保存特定的复选框项目并检索它们

android - 我忘记了 SharedPreferences 文件的名称。

java - 将空值设置为整数

Java list 文件

java - 为什么列表大小返回0?

java - 正则表达式需要太多步骤

java - 在扩展 CrudRepository 的接口(interface)中缓存 Pageable 对象(结果)

android - 共享首选项未保存