您好我试图将数据从我的数据库存储为数组,然后我将使用它为myadapter创建一个自定义的列表视图,但是我的索引超出此范围。
这是我的代码,用于从我的数据库中检索数据以将其存储为数组(主要活动)
int[] avatarImage = {R.mipmap.blademaster,R.mipmap.gunslinger,R.mipmap.pyro};
//i didnt store my image to my database because i dont know how to store and retrieve it so i use manual array
List<Avatar>values = db.getAllAvatars();
int countOfValues = values.size();
String[] titles = new String[countOfValues];
for (int i=0; i<=countOfValues; i++) {
titles[i] = (String)values.get(i).getName();
}
listView = (ListView) findViewById(R.id.avatarlv);
MyAdapter myAdapter = new MyAdapter(MainActivity.this,titles,avatarImage);
listView.setAdapter(myAdapter);
我的适配器java
public class MyAdapter extends ArrayAdapter<String> {
String [] names;
int [] avatarImage;
Context mContext;
public MyAdapter(Context context,String[] nama,int[] aImage) {
super(context, R.layout.adapter_main);
this.names = nama;
this.avatarImage = aImage;
this.mContext = context;
}
@Override
public int getCount()
{
return names.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = new ViewHolder();
if(convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.adapter_main, parent, false);
mViewHolder.mAvatar = (ImageView) convertView.findViewById(R.id.imageView);
mViewHolder.mName = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(mViewHolder);
}
else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mAvatar.setImageResource(avatarImage[position]);
mViewHolder.mName.setText(names[position]);
return convertView;
}
static class ViewHolder{
ImageView mAvatar;
TextView mName;
}
}
但是当我运行它时“java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.gorila.sqlite_grid_view / com.example.gorila.AvatarShop.MainActivity}:java.lang.IndexOutOfBoundsException:索引4无效,大小是4“
请帮助,谢谢。
答案 0 :(得分:1)
在你的this.avatarImage中,你只有3个元素,但是在getView中,如果位置为4则尝试得到这个mViewHolder.mAvatar.setImageResource(avatarImage[position]);
,它将给出IndexOutOfBoundsException。
为了测试只是评论该行并运行,它将正常工作。
或者你可以这样做,
mViewHolder.mAvatar.setImageResource(avatarImage [(position%avatarImage.length)]);
答案 1 :(得分:0)
你有一个&lt; = in for for循环
for (int i=0; i<=countOfValues; i++)
它应该是
for (int i=0; i<countOfValues; i++)