简体   繁体   中英

Send string variable from Activity to AsyncTask Class

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM