0

What is a NullPointerException, and how do I fix it? I'm asking this question after referring many answers regarding null pointer exception in Stack Overflow. I tried many methods and failed.

So the issue is I'm getting null pointer exception in Async task. I'm gonna leave the piece of codes that is responsible for this error.

Below is the class where I'm getting an error.

GetArrayAsyncTask :

@TargetApi(19)
public Map doInBackground(String... strArr) {
    StringBuffer stringBuffer = new StringBuffer();
    String str = null;
    try {
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(strArr[0]).openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();
        InputStream inputStream = httpURLConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        while (true) {
            String readLine = bufferedReader.readLine();
            if (readLine == null) {
                break;
            }
            stringBuffer.append(readLine);
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        httpURLConnection.disconnect();
        String stringBuffer2 = stringBuffer.toString();
        if (!stringBuffer2.contains("host") && !stringBuffer2.contains("version")) {
            boolean contains = stringBuffer2.contains("http");
        }
        List list = JsonHelper.toList(new JSONArray(stringBuffer2));
        HashMap hashMap = new HashMap();
        hashMap.put("data", list);
        return hashMap;
    } catch (MalformedURLException unused) {
    } catch (ProtocolException unused2) {
    } catch (IOException unused3) {
    } catch (JSONException unused) {
        return (Map) JsonUtils.stringObject(str, Map.class); //Error is here.
    }
    return null;
}

public void onPostExecute(Map map) {
    if (map == null || map.size() <= 0) {
        Toast.makeText(this.context, "Data format error!", Toast.LENGTH_LONG).show();
        this.listener.onGetArrayResultsData(map, this.request_code);
        return;
    }
    this.listener.onGetArrayResultsData(map, this.request_code);
}

The exception occurs at return (Map) JsonUtils.stringObject(str, Map.class);

JsonUtils :

public class JsonUtils {
public static String jsonString(Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (JsonProcessingException unused) {
        return null;
    }
}

public static <T> T stringObject(String str, Class<T> cls) {
    try {
        return new ObjectMapper().readValue(str, cls); //Error line.
    } catch (JsonParseException unused) {
        return null;
    } catch (JsonMappingException unused2) {
        return null;
    } catch (IOException unused3) {
        return null;
    }
}
}

LogCat :

java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:318)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:760)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
    at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:889)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at converter.JsonUtils.stringObject(JsonUtils.java:20)
    at com.kds.gold.pi.asyncs.GetArrayAsyncTask.doInBackground(GetArrayAsyncTask.java:111)
    at com.kds.gold.pi.asyncs.GetArrayAsyncTask.doInBackground(GetArrayAsyncTask.java:24)

This project is using the Jackson faster XML library.

Edit: After some modifications, I ran into one weird issue that after initializing str with " " instead of null (this actually solved null pointer exception but led to functional issue). When I add a breakpoint to that line(return (Map) JsonUtils.stringObject(str, Map.class); //Error is here) and debug, the app works fine. Whereas when I run it through normal mode it gives Data format error! Toast as defined in onPost execute method.

Nithis Kumar
  • 278
  • 2
  • 5
  • 21

1 Answers1

1
return (Map) JsonUtils.stringObject(str, Map.class); //Error is here.

str is null. You never seem to assign a value to it. And, since this line of code is in a catch block, it is possible that the exception will occur before you assign a value to str anyway.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for your help mate. I ran into one weird issue that after initializing str with `" "` instead of `null`. When I add a breakpoint to that line and debug app works fine. Whereas when I run it through normal mode it gives `Data format error!` Toast as defined in onPost execute method. What could be the reason? – Nithis Kumar Apr 15 '19 at 14:46
  • @NithisKumar: Um, well, " " is not a JSON representation of a `Map`. – CommonsWare Apr 15 '19 at 21:27