I am setting a member variable in a button click listener which also starts a browser activity. My problem is that the variable is null after the browser is closed and the user returns to my application. I am also saving the variable in onSaveInstanceState and restoring it on onRestoreInstanceState, so I don't think memory management is the issue.
If I don't open the browser the variable is set. Could somebody explain to me why this is the case and the common way to fix this issue? Thanks in advance.
// member variable declaration
private String uniqueTokenRequestID;
// in onCreate()
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uniqueTokenRequestID = UUID.randomUUID().toString();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
});
Complete code:
public class LoginActivity extends AppCompatActivity {
private String uniqueTokenRequestID;
private Button loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (savedInstanceState == null) {
Network.init(this);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Login");
setSupportActionBar(toolbar);
loginButton = (Button) findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uniqueTokenRequestID = UUID.randomUUID().toString();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com"));
startActivity(browserIntent);
}
});
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
uniqueTokenRequestID = savedInstanceState.getString("uniqueTokenRequestID");
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("uniqueTokenRequestID", uniqueTokenRequestID);
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
Uri uri = intent.getData();
if (uri != null) {
Log.d("LOGIN", uri.toString());
String state = uri.getQueryParameter("state");
String code = uri.getQueryParameter("code");
String error = uri.getQueryParameter("error");
if (error != null) {
Log.e("LOGIN", error);
}
else if (state != null && code != null) {
if (state.equals(uniqueTokenRequestID)) {
Log.d("API", "Retrieving tokens");
// successfully logged in
Reddit.retrieveAccessToken(code, new Reddit.AccessTokenListener() {
@Override
public void onAccessTokenRetrieved(Account account) {
Log.d("API", account.getAccessToken() + " " + account.getRefreshToken() + " " + account.getAccessTokenExpiresIn());
}
@Override
public void onError(String error) {
Log.e("API", error);
}
});
}
}
}
}
}