这是我的baseadapter的代码,它显示了联系人'姓名,电话号码和旁边的复选框。
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
int mPos;
MyAdapter()
{
if (mCheckStates==null){
mCheckStates = new SparseBooleanArray(name1.size());
}else {
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));
//adapter is the MyAdapter object created in parent class
super.onDestroy();
}
请注意,我使用bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
和mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
来存储和检索正在销毁和重新创建的活动的SparseBooleanArray。 onDestroy()方法是父类,它是一个活动。我没有粘贴,因为我认为这是无关紧要的。请询问是否需要。
我还使用SparseBooleanArrayParcelable
类来帮助我mCheckStates
进行销毁,并在创建时进行检索。
根据日志,尝试执行bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
时,onDestroy()内发生NullPointerException
帮助将不胜感激。谢谢!
编辑:我初步化了bundle
错误。现在我没有遇到任何错误,但是没有保存复选框状态。我可以用一些帮助。谢谢!