Why value is assigned after usage in method?

Viewed 36

So, I was bothering with this issue. I have in my code value named public String currentSong = "artist- title"; and I use it in code like this

private MetadataOutput getSongTime() {

    return new MetadataOutput() {
        @Override
        public void onMetadata(Metadata metadata) {
            final int length = metadata.length();
            if (length > 0) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(existingURL.split("play")[0] + "currentsong").build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        currentSong = response.body().toString();
                    }
                });
                Toast.makeText(RadioService.this, currentSong, Toast.LENGTH_SHORT).show();
            }

        }
    };
}

But value in Toast is always behind the change (on second run it have value I expected on first run) Is there any way to make it work correctly?

1 Answers

currentSong get the value on the onResponse, and its asynchronous

You must wait the response to show the Toast Message

 @Override
public void onResponse(Call call, Response response) throws  IOException {
    currentSong = response.body().toString();
    // you new a new Thread to show info in the screen beacausre the methos is asynchronous
    Activity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // show toast here
        }
    }
}
Related