如何初始化Map类型变量以解决NullPointerException错误?

时间:2020-10-10 06:28:56

标签: java android json mochi

我不确定执行for循环时哪个变量为null。是未初始化的条目吗?

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);
    }

错误消息

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)

1 个答案:

答案 0 :(得分:0)

gist.files为空。由于它来自responseBody,因此请确保在响应中设置了它,或者在使用它之前检查它是否为空。

相关问题