如何初始化 Map 类型变量以解决空指针异常错误?

huangapple go评论77阅读模式
英文:

How to initialize the Map type variable to solve NullPointerException error?

问题

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

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: 尝试在空对象引用上调用接口方法'java.util.Set java.util.Map.entrySet()'
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)


<details>
<summary>英文:</summary>

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&lt;String, GistFile&gt; files;
}

static class GistFile {
    String content;
}

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

for (Map.Entry&lt;String, GistFile&gt; 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)


</details>


# 答案1
**得分**: 0

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

<details>
<summary>英文:</summary>

`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.

</details>



huangapple
  • 本文由 发表于 2020年10月10日 14:28:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64290661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定