gpt4 book ai didi

java - 我如何解决 java.lang.ArrayIndexOutOfBoundsException 错误

转载 作者:行者123 更新时间:2023-12-01 04:19:21 25 4
gpt4 key购买 nike

您好,我正在开发使用自定义 ListView 的 Android 应用程序,但我不断收到 java.lang.ArrayIndexOutOfBoundsException 错误。但我在代码中找不到任何错误,我可能在哪里出错了。

public class MainActivity extends Activity {

ListView lv_event;

List<HashMap<String, String>> alist;

String[] event_name = { "The Kampala City Festival",
"The Awakening (Lantern Meet of Poets Recital)" };
int[] event_img = { R.drawable.kla_festival, R.drawable.city_rooming };
String[] event_date = { "October 6th, 2013", "October 4th, 2013" };
String[] event_venue = { "Watoto Church, Central", "National Theatre" };
String[] event_time = { "11:30 am", "07:00 pm" };
String[] event_info = { "The #KampalaCityFestival will on Sunday 6th October",
"From the creators of Broken Voices of the Revolution "
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUI();
setEventList();
}

private void setEventList() {
// TODO Auto-generated method stub
try {
alist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 3; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("event_picture", Integer.toString(event_img[i]));
hm.put("event_name", event_name[i]);
hm.put("event_date", event_date[i]);
hm.put("event_venue", event_venue[i]);
hm.put("event_time", event_time[i]);
hm.put("event_info", event_info[i]);
alist.add(hm);
}

// from
String[] from = { "event_picture", "event_name", "event_date",
"event_venue", "event_time", "event_info" };
// to
int[] to = { R.id.img_view_event, R.id.tv_event_name, R.id.tv_date,
R.id.tv_event_place, R.id.tv_time, R.id.tv_event_info };

SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
alist, R.layout.lv_custom, from, to);

lv_event.setAdapter(adapter);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}

}

private void setUI() {
// TODO Auto-generated method stub
lv_event = (ListView) findViewById(R.id.lv_event);
}

最佳答案

您正在尝试对数组进行三次迭代,期望每个数组中有三个元素。

但是这里您只定义了两个值,例如:

String[] event_name = { "The Kampala City Festival",
"The Awakening (Lantern Meet of Poets Recital)" };

这可能就是你得到 ArrayIndexOutOfBoundsException 的原因

所以尝试改变i < 3i < 2 ,如果您希望数组中只有 2 个元素,或者向只有 2 个值的数组中添加一个元素。

关于java - 我如何解决 java.lang.ArrayIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19112477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com