如何初始化Map类型变量解决NullPointerException错误?
How to initialize the Map type variable to solve NullPointerException error?
我不确定执行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.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)
gist.files
为空。由于它来自 responseBody
,请确保它已在响应中设置或在使用前检查它是否为空。
我不确定执行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.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)
gist.files
为空。由于它来自 responseBody
,请确保它已在响应中设置或在使用前检查它是否为空。