9

Okay, that's what I've got:

        String[] data = null;
    String[] data2 = null;
    String[] datas = res.split("(s1)");
    int i1 = 0;
    int i2 = 0;
    for(String datasx : datas)
    {
        i1++;
        String[] datas2 = datasx.split("(s2)");

        for(String datas2x : datas2)
        {
            String[] odcinek = datas2x.split("(s3)");
            data[i2] = odcinek[1] + "////" + odcinek[2] + "////" + odcinek[6];
            i2++;
        }
    }

And it's not working. Application crashes on this line:

data[i2] = odcinek[1] + "////" + odcinek[2] + "////" + odcinek[6];

Actually, Eclipse gives me the following warning on it:

Null pointer access: The variable data can only be null at this location

but I have no idea what's wrong. Can anybody help? Thanks.

Maciej Wilczyński
  • 379
  • 1
  • 5
  • 13
  • the `data` array gets initialized to `null` and it is never assigned another value. The array itself is null, so you can't assign a value to a member in that array like: `data[i2] = ...` – Ahmad Y. Saleh Apr 22 '12 at 13:51
  • The issue here is not the NPE itself, but that you need to learn to check all variables on the line that causes the NPE whenever you get one by backtracking through your code and seeing where each variable has been initialized. Do this as a reflex and next time, the answer should be obvious to you. I've deleted my answer below to help reduce "answer clutter". – Hovercraft Full Of Eels Apr 22 '12 at 13:59
  • same topic: http://stackoverflow.com/questions/4909903/ and http://stackoverflow.com/questions/20035122/ – Yousha Aleayoub Sep 11 '16 at 14:09

3 Answers3

7

Seem like you required dynamic list, so what you need is replace String[] data = null; to use List

List data = new ArrayList<String>();
String[] data2 = null;
String[] datas = res.split("(s1)");
         
int i1 = 0;
int i2 = 0;
     
for (String datasx : datas) {
    i1++;
    String[] datas2 = datasx.split("(s2)");

    for (String datas2x : datas2) {
        String[] odcinek = datas2x.split("(s3)");
        data.add(odcinek[1] + "////" + odcinek[2] + "////" + odcinek[6]);
        i2++;
    }
}
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Pau Kiat Wee
  • 9,485
  • 42
  • 40
5

You are initializing the array data to be null, when you try to access it it gives you null pointer access error.

You must initialize it to the appropriate type before you try to acces it i.e. initialize it to String[] instead of null.

Sahil Sachdeva
  • 442
  • 3
  • 5
  • 12
3

You need to initialize the 'data' variable. It's null at this point.

Please try the following

String[] datas2 = datasx.split("(s2)");
data = new String[datas2.length];
Chetter Hummin
  • 6,687
  • 8
  • 32
  • 44