2014-10-18 48 views
0

我想使用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(); 
    } 
} 
+0

你使用onSaveInstanceState或不?你可以張貼代碼以供參考 – 2014-10-18 13:02:41

+0

不,我不是。即使應用在退出後重新啓動,我也希望數據得到恢復。當然,我會發布代碼。 – Slay 2014-10-18 13:05:52

回答

0

摞由您在類中創建並且不使用活動來存儲值。

如果您正在使用該應用程序包,則在您終止該應用程序後仍然無法獲取該實例。

因爲你是問題更好去與共享偏好,但在共享偏好,你不能存儲對象。

如果您想使用共享首選項,那麼有2個解決方案。

  • 對象轉換爲字符串並將其存儲在共享的偏好和檢索回來,從字符串改革對象。 (使用Gson或Jackson或您首選的方式)
  • 使用Complex Preferences第三方一,您可以在其中存儲對象並直接檢索。

如果你對使用bundle更感興趣,那麼請檢查stackoverflow上的這個討論。

save-bundle-to-sharedpreferences

how-to-serialize-a-bundle

希望這會幫助你。

+0

我可以在ComplexPreference中存儲一個包嗎?該庫似乎只適用於GSon對象。我可能是錯的。 – Slay 2014-10-18 14:09:29

+0

我認爲它不會存儲。上面的答案告訴我們使用Object而不是bundle,兩個實現都是一樣的,一個是由你手工完成的。所以你有更多的控制權,其他人正在給第三方圖書館採取行動。 – 2014-10-18 14:17:10

1

您可以將其存儲在SharedPreferances 約sparsebooleanarrays的事情是:它映射整數布爾值,因此可以將其保存爲一個字符串,消除括號,空格和=跡象,你已經是一個int值(用於索引值)和相應的布爾值(用逗號分隔)現在相應地使用該字符串。希望它有助於:)

相關問題