英文:
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<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)
</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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论