Access to null pointer: variable data can only be null at this point

Good thing I have:

        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 does not work. Application crash on this line:

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

Actually, Eclipse gives me the following warning:

Access to null pointer: variable data can only be null in this place

but I don’t know what happened. Can anyone help? Thank.

+3
source share
3 answers

It looks like you need a dimatic list, so you need to replace String[] data = null;with 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++;
    }
}
+6
source

You initialize the data of the array to zero, when you try to access it, it gives an error accessing the null pointer.

, , String [] null.

+4

You need to initialize the variable 'data'. At this point, this value is zero.

Try the following

String[] datas2 = datasx.split("(s2)");
data = new String[datas2.length];
+2
source

All Articles