我正在与改造工作以获取一些统计信息。他们到达应用程序。当我尝试将某些TextView的文本设置为值时,它们会抛出NullPointerException。有什么我应该知道的吗?
public void init() {
getStatistics();
txtNrCompleted.setText(String.format("%s", statistics.getTask()));
}
private void getStatistics(){
endpoints = RetrofitJsonCaller.call(APIEndpoints.class);
callStatistics = endpoints.getStatistics(URLEndpoints.getStatistics());
callStatistics.enqueue(new Callback<STATISTIC>() {
@Override
public void onResponse(Call<STATISTIC> call, Response<STATISTIC> response) {
if(response.isSuccessful()) {
setStatistics(response.body());
}else{
Log.d("STATISTICS", "Error: " + response.code());
}
}
@Override
public void onFailure(Call<STATISTIC> call, Throwable t) {
Timber.d(t.getMessage());
}
});
}
public void setStatistics(STATISTIC statistics){
this.statistics = statistics;
}
日志:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer com.example.taskmanagement.model.STATISTIC.getTaskComplet()' on a null object reference
at com.example.taskmanagement.MainActivity.onCreate(MainActivity.java:111)
at android.app.Activity.performCreate(Activity.java:6948)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
答案 0 :(得分:1)
Retrofit正在发出异步获取统计信息的调用,但是您正在同步设置TextView
中的文本。您调用getStatistics()
会触发调用以获取新的统计信息,但不等待其完成。然后,您立即设置文本,此时statistics
对象仍为null。得到成功的响应后,您需要更新TextView
。例如:
public void init() {
getStatistics();
}
private void getStatistics() {
...
@Override
public void onResponse(Call<STATISTIC> call, Response<STATISTIC> response) {
if (response.isSuccessful()) {
setStatistics(response.body());
// Call the code to update your UI here, as we have now received the stats
updateUI();
} else {
...
}
}
...
}
...
private void updateUI() {
textNrCompleted.setText(String.format("%s", statistics.getTask()));
}