This is my MainActivity.java where I instanciate static SharedPreferences and it's editor:
public static SharedPreferences settings;
public static SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
editor = settings.edit();
Then I make an AsyncTask call to another java class where I try to store a token in onPostExecute method to this SharedPreferences.
@Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
}
This Log.d() method outprints the token value in the console, which is "OK". But then I start an acitivity Next.java where I try to get this token on a screen using this:
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String auth_token_string = MainActivity.settings.getString("auth_token", "Nothing");
text = (TextView) findViewById(R.id.logintxt);
text.setText(auth_token_string);
And the result on the screen is the default String "Nothing".
What am I doing wrong here? ...and is this the right way to use SharedPreferences? I got this idea here in this topic.
EDIT:
Code from AuthorizeActivity.java where I call the asyncTask:
public void getToken(String code){
AsyncTask<String, Void, String> tsk = new Api().execute(code);
Intent i = new Intent(this.getBaseContext(), Next.class);
dialog.dismiss();
startActivity(i);
}