defiant
defiant

Reputation: 3341

Passing SharedPreferences to doInBackground()

I am trying to pass the SharedPreferences prefs, as an argument to doInBackground function in AsyncTask. I am already passing a string(url) to it, so I would need to pass the prefs also as a string. Can I simply use, prefs.toString() to convert it into string?

This is where I set the prefs:

if (prefs.getBoolean("firstrun", true)) {
            prefString = prefs.toString();
            prefs.edit().putBoolean("firstrun", false).commit();
        }

Upvotes: 0

Views: 1197

Answers (2)

Houcine
Houcine

Reputation: 24181

try this code :

  public class DownloadFiles extends AsyncTask<URL, Void, Void> {

      Context ctx;
    boolean firstLaunch;
    SharedPreferences prefs;


      DownloadFiles(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences("Prefs",Context.MODE_PRIVATE);
      }
      @Override
      public void onPreExecute() {
          firstLaunch = prefs.getBoolean("firstrun", true);
      }

      @Override
      public void doInBackground(URL... urls) {

        if(firstLaunch)
          // code for the firstLaunch
        else 
          //code if it isn't the firstLaunch 
      }

      @Override
      public void onPostExecute(Void params) {
          // update prefs after the firstLaunch
          if(firstLaunch)
              prefs.edit().putBoolean("firstrun", false).commit();
      }
    }

Upvotes: 0

Raffaele
Raffaele

Reputation: 20885

You can't and you shouldn't. You can easily read the preferences just inside doInBackground() withou passing anything to the method, simply by using the PreferenceManager:

public class DownloadFiles extends AsyncTask<URL, Void, Void> {

  Context ctx;

  DownloadFiles(Context ctx) {
    this.ctx = ctx;
  }

  @Override
  public void doInBackground(URL... urls) {
    // ...
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    // ...
  }
}

Upvotes: 4

Related Questions