简体   繁体   中英

Android: fill spinner with items in text file

I want fill spinner with items in text file on my hosting. The text file content separate with "\\n" character:

Afghanistan
Albania
Algeria
Andorra
Angola

I write this code but I've this error :

03-10 12:32:07.716: E/AndroidRuntime(7670): 
FATAL EXCEPTION: Thread-69056
03-10 12:32:07.716: 

E/AndroidRuntime(7670): 
java.lang.ArrayIndexOutOfBoundsException: 
length=91; index=91

                    bo.write(buffer);
                    String s = bo.toString();

                    final Vector<String> str = new Vector<String>();
                    String[] line = s.split("\n");
                    int index = 0;
                    while (line[index] != null) {
                        str.add(line[index]);
                        index++;
                    }

you need to change the condition.. with this:

while (line[index] != null) {
   str.add(line[index]);
   index++;
}

if say the size of line is 10, index++ will make it 11. thus line[11] will not be null but rather throw an ArrayIndexOutOfBoundsException .

change the condition to :

for(int i=0;i<line.length;i++) {
    if(line[i] != null) {
       str.add(line[index]);
    }
}

You need to be check by the length of your String array in for loop

for(int i=0;i<line.length;i++) {
if(line[i] != null) {
   str.add(line[index]);
}
}

Change code to:

bo.write(buffer);
String s = bo.toString();
final Vector<String> str = new Vector<String>();
String[] line = s.split("\n");
int index = 0;
while (index < line.length) {
str.add(line[index]);
index++;
}

You are getting java.lang.ArrayIndexOutOfBoundsException because you are not doing bound checking for line array.

It should be:

int index = 0, length = line.length;
while (index < length) {
   str.add(line[index++]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM