0

I'd like to save SparseBooleanArray using either SharedPreferences, or anything else, that's more preferred.

I've tried using https://stackoverflow.com/a/16711258/2530836, but everytime the activity is created, bundle is re-initialized, and bundle.getParcelable() returns null. I'm sure there is a workaround for this, but I haven't arrived at it despite a few hours of brainstorming.

Also, if there isn't, could I use something like SharedPreferences?

Here's the code:

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();
    }
}
Community
  • 1
  • 1
Slay
  • 221
  • 1
  • 5
  • 12

2 Answers2

1

You can store it in SharedPreferances The thing about sparsebooleanarrays is: it maps integers to boolean values, hence you can save it as a string, eliminate the braces,spaces and = signs, and all you have is an int value (for index value) and the corresponding boolean value, separated by a comma, now use the string accordingly. Hope it helps :)

inkedTechie
  • 684
  • 5
  • 13
0

Bundle is created by you in the class and it is not used by activity to store the value.

If You're using the bundle of application, still you can't get the instance once you killed the application.

For you're problem better go with shared preference but in shared preference you can't store objects.

If you want to use shared preference then there are 2 solutions.

  • Convert object to string and store in shared preference and retrieve back and reform the Object from String. (use Gson or Jackson or you're preferred way )
  • Use Complex Preferences third party one, Where you can store objects and retrieve directly.

If you're more interested using bundle only then Check this discussion on stackoverflow.

save-bundle-to-sharedpreferences

how-to-serialize-a-bundle

Hope this will help you.

Community
  • 1
  • 1
Harsha Vardhan
  • 3,324
  • 2
  • 17
  • 22
  • Can I store a bundle in ComplexPreference? The library seems to be only for GSon objects. I could be wrong. – Slay Oct 18 '14 at 14:09
  • I think it won't store. The above answer tells go with the Object than bundle and the two implementation do the same, One is manually done by you. So you have more control and Other is giving action to third party library to do. – Harsha Vardhan Oct 18 '14 at 14:17