我有多个字符串,如st1,st2,st3,st4,st5,st6,st7。现在我想通过for循环使用其计数器(在我的情况下为int i)动态获取字符串。像“st”+ i,但是android不接受它,所以我应该怎么做才能动态地获取字符串。有关更多信息,请参阅代码块
String image1 = cData.getString(cData.getColumnIndex("fld_image_url1"));
String image2 = cData.getString(cData.getColumnIndex("fld_image_url2"));
String image3 = cData.getString(cData.getColumnIndex("fld_image_url3"));
String image4 = cData.getString(cData.getColumnIndex("fld_image_url4"));
ArrayList<String> imagesArray = new ArrayList<String>();
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
if("image"+i!=null){
imagesArray.add(String.valueOf("image"+ i));
}
}
答案 0 :(得分:3)
如下:
List<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
答案 1 :(得分:1)
如果要动态获取游标值,请将代码更改为:
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
int count = cData.getColumnIndex("fld_image_url"+i));
if(count != -1)
imagesArray.add(cData.getString(count));
}