android - App crashes while trying to iterate through the ArrayList
问题描述
When i was trying to iterate through the arraylist of custom listview used for loop, my app suddenly crashed and when i tried to look at the logcat no error appeared. I've tried one by one finding the problem then i found out the problem is the part where i try to get the item value. can help me point out the problem?
This is part of my code in iterating/getting the arraylist value
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
}
This is my subclass for the custom listview
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;}
解决方案
change
for(int i=0;i<=myAdapter.myItem.size();i++){
with:
for(int i=0; i < myAdapter.myItem.size(); i++) {
When you're using <=
, at the last iteration you're pointing to null. The condition should be just i < myAdapter.myItem.size();
推荐阅读
- python - rst2pdf AttributeError:“PDFWriter”对象没有属性“custom_cover”
- android - 组件中存在具有匹配键的绑定:dagger 2.12
- numpy - 在 cython 中为 numpy 定义自定义 dtype
- node.js - NodeJs 项目 SyntaxError:不能在模块外使用 import 语句
- entity-framework - 如何使用 Entity Framework fluent API 设置外键
- c - 为什么我的 GTK CSS 按钮颜色仅在未选择我的应用程序时才有效?
- flutter - 文本对齐底部将文本保持在屏幕顶部
- reactjs - FOUC如何去除
- python - 有谁知道如何在 Windows 上安装 Python P5 包?
- c++ - 使用没有结构的链表打印堆栈