【发布时间】:2014-01-13 19:26:05
【问题描述】:
我已经按照这个解决方案Removing muliple items from listview using Check box in Android 实现了一个从列表视图中删除多个项目的简单方法,然后对其进行了一些修改以允许两个按钮单击事件add 和delete 的 switch 语句。但问题是当我单击删除按钮时,应用程序崩溃给我这些错误:http://pastebin.com/2NmCQk2B
我不确定为什么会出现空指针异常,因为我相信我已经正确分配了所有内容。
谁能更好地解释为什么我会收到这个错误?或者也许是从列表视图中删除选定行项目的更好方法?
完整的课程贴在下面以便更好地理解:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd,mDel;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
SparseBooleanArray mCheckStates ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mDel = (Button)rootView.findViewById(R.id.delBtn);
mAdd.setOnClickListener(this);
mDel.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
public void onClick(View v)
{
switch(v.getId()){
case R.id.newList:
//DO something
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
break;
case R.id.delBtn:
//DO something
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
list.remove(i);
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
}
}
【问题讨论】:
-
this` if (checked.get(i)==true)`
-
如何填充列表。我猜它是空的
-
我通过在edittext中输入项目并单击添加按钮来填充列表
-
首先要看到的是您的“已检查”变量为空。弄清楚为什么它是空的,然后你就会有事情发生。如果您无法弄清楚为什么“getCheckItemPositions”返回 null,请在此处阅读 stackoverflow.com/questions/7402150/…,另外,请绝对确保在 ListView 中没有选择模式设置为 CHOICE_MODE_NONE。
-
@BrianJ 是的。这应该工作
标签: android listview android-listview null nullpointerexception