user3056928 user3056928 - 3 months ago 29
Android Question

How to save the value of a variable inside a Retrofit call?

I am trying to retrieve the value of a certain field from the header using a Retrofit call to be used to be sent back to server. I am successful in getting the value inside the try block and send it back immediately in the try block too. But when I try the same outside the call instance, the value of abc (which is where I assigned the value of the response header) is lost. I have already declared the String abc as a global variable. How do I save the value of the string?

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivityClass";
String abc;

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

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

Call<List<TrendingModel>> call = apiService.getAllTodos();
call.enqueue(new Callback<List<TrendingModel>>() {
@Override
public void onResponse(Call<List<TrendingModel>> call, Response<List<TrendingModel>> response) {
try {

List<TrendingModel> todoModels = response.body(); // WHERE WE GET THE RESPONSE BODY
abc = response.headers().get("Tanand"); // WHERE WE GET THE RESPONSE HEADER AND ASSIGN IT TO abc, WHICH WE DECLARED GLOBALLY

ApiClient.getClient(abc).create(ApiInterface.class); // PASSING THE abc VARIABLE TO THE GETCLIENT(TOKEN) METHOD WITHIN
// THE SAME TRY BLOCK WHICH WORKDS

} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}

@Override
public void onFailure(Call<List<TrendingModel>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});

ApiClient.getClient(abc).create(ApiInterface.class); // VALUE OF abc IS NOT PERSISTED HERE (abc IS NULL) ALTHOUGH WE DECLARED IT GLOBALLY
}
}

Answer

Try to call method inside OnResponse method .

because onRespnse() method run on background till process done and then data come.

If you want to access response data then call your method inside it .

And outside all statements are called before the response data finished that why it not give you actual data . For Good Practice use below method it look readable .

Just create a method and inside the class and call your all statements inside.

And call your method inside onResponse method .

enjoy coding .