I realize similar questions have been asked but I am new to android and find the answers a bit confusing since they are in a slightly different context.
I have looked at CountDownLatch aswell as using Threads and am not sure which method to use. Any help would be much appreciated. I have also tried using apply() instead of commit() for SharedPreferences.
I am making 2 retrofit2 calls from LoginActivity. I need the token from the first call to use in the second call. I am saving the token to a string in sharedpreferences in the onResponse method of the first retrofit call.
In my second call the value of serverToken is coming back as the token set in previous run of the app
1st call(getToken) onResponse
call.enqueue(new retrofit2.Callback<TokenResponse>() {
@Override
public void onResponse(Call<TokenResponse> call, retrofit2.Response<TokenResponse> response) {
if (response.isSuccessful()) {
TokenResponse tokenResponse = response.body();
LoginActivity.editor.putString("serverToken", tokenResponse.getAccessToken());
LoginActivity.editor.commit();
} else {
Log.i("Server Token", "failed");
}
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
public static SharedPreferences preferences;
public static SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authenticationController = new AuthenticationController();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
}
public void onLoginClicked(View view) {
getToken(); //FIRST RETROFIT CALL
connectToPush(); //SECOND CALL WHERE I NEED TOKEN FROM FIRST CALL
}
public void getToken() {
authenticationController.login(grantType, username, password);
}
public void connectToPush() {
authenticationController.connectToPush();
}
My Second Retrofit call
public void connectToPush(){
Log.i("sharedpreferencesToken", LoginActivity.preferences.getString("serverToken", "null serverToken"));
}