当我尝试遍历用于循环的自定义listview的arraylist时,我的应用突然崩溃,当我尝试查看logcat时,没有出现错误。我尝试了一个发现问题的方法,然后发现问题是我尝试获得项目价值的部分。能帮我指出问题吗?
这是我的代码中迭代/获取arraylist值的一部分
for(int i=0;i<=myAdapter.myItem.size();i++){
String name=tabl.getText().toString();
//this is the part that causes the crash
String answer=myAdapter.myItem.get(i).toString();
//mHelper.insertData(name,answer);
//temporary disable sql
}
这是我的自定义列表视图的子类
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItem = new ArrayList();
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i < x+1; i++) {
ListItem listItem = new ListItem();
listItem.caption = "hahaha";
myItem.add(i+".");
}
notifyDataSetChanged();
}
public int getCount() {
return myItem.size(); }
public Object getItem(int position) {
return position; }
public long getItemId(int position) {
return position; }
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.items, null);
holder.caption = (EditText) convertView
.findViewById(R.id.ItemCaption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.caption.setText(myItem.get(position).toString());
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
myItem.set(position, Caption.getText().toString());
}
}
});
return convertView;
}
}
class ViewHolder { EditText caption;}
class ListItem { String caption;}
答案 0 :(得分:2)
更改
for(int i=0;i<=myAdapter.myItem.size();i++){
具有:
for(int i=0; i < myAdapter.myItem.size(); i++) {
使用<=
时,在上一次迭代中,您指向空值。条件应仅为i < myAdapter.myItem.size();