Java 如何使用SharedReferences保存SparseBooleanArray?或者其他选择?

Java 如何使用SharedReferences保存SparseBooleanArray?或者其他选择?,java,android,sharedpreferences,Java,Android,Sharedpreferences,我想使用SharedReferences或其他更可取的方法保存SparseBooleanArray 我尝试使用,但每次创建活动时,bundle都会重新初始化,bundle.getParcelable返回null。我肯定有一个解决办法,但我还没有达到这一点,尽管几个小时的头脑风暴 另外,如果没有,我可以使用类似SharedReferences的东西吗 代码如下: public class ContactActivity extends Activity implements AdapterView

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

我尝试使用,但每次创建活动时,bundle都会重新初始化,bundle.getParcelable返回null。我肯定有一个解决办法,但我还没有达到这一点,尽管几个小时的头脑风暴

另外,如果没有,我可以使用类似SharedReferences的东西吗

代码如下:

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

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

如果您使用的是应用程序包,那么在终止应用程序后仍然无法获取实例

对于您的问题,最好使用共享首选项,但在共享首选项中不能存储对象

如果您想使用共享首选项,那么有两种解决方案

将对象转换为字符串并存储在共享首选项中,然后从字符串检索并重新构造对象。使用Gson或Jackson,或者您喜欢的方式 使用第三方one,您可以在其中存储对象并直接检索。 如果您对仅使用bundle更感兴趣,请查看有关stackoverflow的讨论


希望这对您有所帮助。

您可以将其存储在SharedReferences中
SparSeBooleanArray的特点是:它将整数映射为布尔值,因此您可以将其另存为字符串,消除大括号、空格和=符号,并且您所拥有的只是索引值的int值和相应的布尔值(由逗号分隔),现在相应地使用字符串。希望有帮助:

您是否使用onSaveInstanceState?你能把代码贴出来供参考吗。我希望即使退出后应用程序重新启动,数据也能恢复。当然,我会发布代码。我可以在ComplexPreference中存储一个包吗?该库似乎仅适用于GSon对象。我可能错了。我想它不会储存。上面的答案告诉我们,使用对象比bundle更方便,这两个实现做的是相同的,一个是由您手动完成的。所以你们有更多的控制权,而另一个则是让第三方库去做。