1

I have a problem when I want to access to my SharedPreferences inside doInBackground. How can I do this?

Really thanks!

private class postData extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {

    // I need to access here to my SharedPreferences //

  }
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Marco Antonio
  • 339
  • 2
  • 10
  • 1
    You can access SharedPreferences in background threads (the same way you do on a main thread) as they are stored persistently. – Edison Mar 08 '13 at 22:12
  • Thank you really much, it works! :D I don't know why i tought that I was unable of do that, I'll post my final code. – Marco Antonio Mar 08 '13 at 22:20

1 Answers1

2

The solution was easier than I thought.

private class postData extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext() );    
    String userName = sharedPrefs.getString("auth_username", "");
    String userPass = sharedPrefs.getString("auth_password", "");
  }
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Marco Antonio
  • 339
  • 2
  • 10
  • 4
    IDK why would this work, the getApplicationContext() is a method of the Context class and the AsyncTask does not extend it – viplezer Nov 22 '13 at 12:12
  • 6
    This answer is not correct, getApplicationContext() does not work here. – Loolooii Feb 26 '14 at 14:47
  • Check the link, This is work for me http://stackoverflow.com/questions/15855332/update-shared-preferences-from-asynctask-onpostexecute – KZoNE Jul 07 '15 at 11:19
  • The context bit is wrong, but you can pull some working bits out of this – justinraczak May 30 '16 at 00:12