8kk
8kk

Reputation: 140

Set Text after retrofit response

I am working with retrofit to get some statistics. They arrive at the app. When I try to set some TextView's text to the values they throw a NullPointerException. Is there something I should know?

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;
}

LOGS:

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)

Upvotes: 1

Views: 1312

Answers (1)

jguerinet
jguerinet

Reputation: 1549

Retrofit is making the call to get the statistics asynchronously, but you are setting the text in the TextView synchronously. You call getStatistics() which triggers the call to get the new statistics but doesn't wait for it to finish. You then set the text immediately after, at which point the statistics object is still null. You need to update the TextView after you get a successful response. For example:

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())); 
}

Upvotes: 1

Related Questions