Android 改装响应后设置文本

Android 改装响应后设置文本,android,textview,retrofit,Android,Textview,Retrofit,我正在进行改造以获得一些统计数据。他们到达应用程序。当我尝试将一些TextView的文本设置为值时,它们会抛出NullPointerException。有什么我应该知道的吗 public void init() { getStatistics(); txtNrCompleted.setText(String.format("%s", statistics.getTask())); } private void getStatistics(){ endpoints = Retro

我正在进行改造以获得一些统计数据。他们到达应用程序。当我尝试将一些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;
}

Refugation正在调用异步获取统计信息,但您正在同步设置
TextView
中的文本。调用
getStatistics()
,它会触发调用以获取新的统计信息,但不会等待它完成。然后立即设置文本,此时
statistics
对象仍然为空。在获得成功响应后,您需要更新
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())); 
}
public void init(){
getStatistics();
}
私有void getStatistics(){
...
@凌驾
公共void onResponse(调用、响应){
if(response.issusccessful()){
设置统计(response.body());
//在这里调用代码来更新您的UI,因为我们现在已经收到了统计数据
updateUI();
}否则{
...
}
}
...
}
...
私有void updateUI(){
textNrCompleted.setText(String.format(“%s”,statistics.getTask());
}

您好,请提供代码和崩溃日志以获取有关您的问题日志和代码的更多详细信息?您确定它是一个
NullPointerException
?别忘了只在主线程上更新UI。。。
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())); 
}