Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 496
Maciej Wilczyński Avatar asked Apr 22 '12 13:04

Maciej Wilczyński


People also ask

WHAT IS NULL pointer access?

In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object.

WHAT IS NULL pointer access in Java?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

How to handle Null Pointer Exception in Java?

To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

What is null in Java?

In Java, null is a literal, a special constant you can point to whenever you wish to point to the absence of a value. It is neither an object nor a type, which is a common misconception newcomers to the Java language have to grapple with.


2 Answers

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++;
    }
}
like image 169
Pau Kiat Wee Avatar answered Sep 22 '22 16:09

Pau Kiat Wee


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.

like image 26
Sahil Sachdeva Avatar answered Sep 19 '22 16:09

Sahil Sachdeva