Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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 34 mins ago

1 Answer 1

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()
}
share|improve this answer
    
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 14 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.