0

I need to send a string variable from my main activity class to the AsyncTask Class and use that string as part of the url to make the api call.

I tried using Intent and share preferences but neither can seem to be accessed in the AsyncTask Class. Can I use Singleton pattern, and if yes, how would I go about it?

yellowmonkey
  • 197
  • 3
  • 11
  • 1
    Post the code you have tried but all you need to do is pass it either in the constructor or in `execute()` if you just need to send it to `doInBackground()` – codeMagic Sep 03 '14 at 23:22
  • would you be able to post an example or post a link to an example of what you suggested? – yellowmonkey Sep 04 '14 at 00:08
  • I'm not sure what you need an example of but you should find different variations here http://stackoverflow.com/search?q=pass+params+to+AsyncTask+user%3A1380752 – codeMagic Sep 04 '14 at 00:21
  • anything with singleton that does that shows the task I need to do – yellowmonkey Sep 04 '14 at 00:38
  • 1
    I just gave you a list of posts. You don't need a singleton class for this. Just pass the value to a constructor or to `doInBackground()` through the `execute()` method.. See here http://stackoverflow.com/questions/18898039/using-asynctask/18898105#18898105 – codeMagic Sep 04 '14 at 00:39

1 Answers1

0

If you declare a global variable:

public class MainActivity extends Activity {

    private String url = "http://url.com";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new DownloadFilesTask().execute();
    }

    private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {

     protected Long doInBackground(Void... params) {

        // You can use your 'url' variable here
        return null;
     }

     protected void onProgressUpdate(Void... result) {
        return null; 
     }

     protected void onPostExecute(Void result) {

     }
   }
}

if you work in seperate classes:

new MyAsyncTask("Your_String").execute();

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

    public MyAsyncTask(String url) {
        super();
        // do stuff
    }

    // doInBackground()
}
letsjak
  • 359
  • 3
  • 14
  • No need to make it "global" if it's only being used in the inner-class. Plus, I got the feeling that it's a separate class. – codeMagic Sep 03 '14 at 23:42