Black Kinght Black Kinght - 1 month ago 13
Android Question

Save the response from OkHttp -- Android --

I wanna to save the result from OnResponse method to use it for updating the UI
i tried to save the result into String var then call it into main thread but it doesn't work .

here's my code with some comments ,
any help ?

package com.example.blacknight.testokhttp;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.R.string.ok;
public class MainActivity extends AppCompatActivity {

public final String URL_MOVIE = "http://api.themoviedb.org/3/movie/popular?api_key=" + API_KEY;
String res_120 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL_MOVIE)
.build();

client.newCall(request).enqueue(new Callback() {

@Override
public void onFailure(Call call, IOException e) {

}

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

Log.v("BK-201 URL: " , response.body().string());

// wanna save the result to update UI
res_120 = response.body().string();

}

});


// just for test : if the result has been saved or not
Log.i("BK-111 : " , res_120);


}


}

Answer

Let's say you want to update a TextView element in you UI with the response in a String format. You could do something like this. I keeped your test log to help you follow the code, just in case.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL_MOVIE)
            .build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {

        }

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

            Log.v("BK-201 URL: " , response.body().string());

            // wanna save the result to update UI
            res_120 = response.body().string();
            updateUI(response.body().string());
        }
    });    
}

void updateUI(String string) {
   textView.setText(string);
   Log.i("BK-111 : " , res_120);
}
Comments