Android setText on TextView when Callback is finished

Viewed 214

Hello I have such a code: pointsToAssignTv.setText(String.valueOf(restData.getPointsUnass(login))); where restData.getPointsUnass(login) is such a Retrofit code:

    public int getPointsUnass(String name) {
    Call<String> result = Api.getClient().getPointsUnass(name);
    result.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            pointsUnass = Integer.parseInt(response.body());
        }
        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.e("tag",t.toString());
        }
    });
    return pointsUnass;
}

I want to assign this value to this TextView but it returns null, I guess it is all about time it needs to process through the internet and then return. What piece of code would you recommend to write instead?

2 Answers

You need to move the setText() statement to onResponse() callback method. Just add this statement - pointsToAssignTv.setText(String.valueOf(pointUnass)); to onResponse() method.

After get response from API, in the onResponse should add someText.setText(yourResponse) Notice: be care about threading, in android you just allow change UI element in the main thread, if you want to change the text in response you must use handler

new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
    Log.d("UI thread", "I am the UI thread");
}
});
Related