0

I am not sure which variable is null when the for loop is executed. Is it the entry that is uninitialized?

MainActivity.java

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }

    Gist gist = gistJsonAdapter.fromJson(responseBody.source());

    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
              System.out.println(entry.getKey());
              System.out.println(entry.getValue().content);
    }

Error Message

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set java.util.Map.entrySet()' on a null object reference
        at com.example.soccerapi.MainActivity$1.onResponse(MainActivity.java:76)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
oc2020
  • 31
  • 1
  • 3
  • NullPointerException cause by reference to a field or call a method from a null object, so just find out which is null should solve your problem. An easy way to find which is null, you may print variable from top to bottom, in your case, print `gistJsonAdapter` checkout if it was null, then print `responseBody `, then `responseBody.source()` and `gist ` and so on – Wangbo Oct 10 '20 at 06:39
  • Could you also show a `JSON` payload you want to deserialise? It must contain `JSON Object` with key `files`. If it does not, `NPE` is thrown later when you want to access it. – Michał Ziober Oct 10 '20 at 09:56

1 Answers1

0

gist.files is null. Since it comes from the responseBody either make sure that it is set in the response or check if it is null before using it.

Henry
  • 42,982
  • 7
  • 68
  • 84