John
John

Reputation: 281

Nullpointer Acess message in Java

I have created a method to parse a JSON object and to return an array of string.

private String[] getAttributesfromJson(JSONObject attacheddataattributejson) {
    String returnjsonArray[] = null;
    JSONArray subcatarray = attacheddataattributejson.optJSONArray("subcatAttributes");
    if(subcatarray!=null){
        for(int i=0;i<subcatarray.length();i++)
        {
            returnjsonArray[i]=subcatarray.getJSONObject(i).optString("name");
        }   
    }
    return returnjsonArray;
}

But my eclipse is showing an warning on returnjsonArray[i] that this can only be null at this pos. But I have a null check for subcatarray also. Please help.

Upvotes: 0

Views: 67

Answers (3)

Shivakumar ss
Shivakumar ss

Reputation: 663

you can use the following code.


private String[] getAttributesfromJson(JSONObject attacheddataattributejson) throws JSONException {
        List<String> returnjsonArray = new ArrayList<String>();
        JSONArray subcatarray = attacheddataattributejson.optJSONArray("subcatAttributes");
        if (subcatarray != null) {
            for (int i = 0; i < subcatarray.length(); i++) {
                returnjsonArray.add(subcatarray.getJSONObject(i).optString("name"));
            }
        }
    return (String[]) returnjsonArray.toArray();
}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122006

See this line

String returnjsonArray[] = null;

You forgot to initialize it.

You won't get anything from a basket when you did'nt fill it before.

Upvotes: 1

fge
fge

Reputation: 121820

You initialize your returnjsonArray[] to null and try to access it without having ever initialized it.

Java does no magic with null references; what is more, arrays are not dynamically allocated in Java. If you want that, use a List (which you should initialize as well), and return this list's .toArray().

Upvotes: 1

Related Questions