Anurupa_Dey
Anurupa_Dey

Reputation: 113

Passing String to AsyncTask

So I have a string (that is an link to a page) and I need to pass it to a AsyncTask. Here's my code:

url = "http://www.railpnrapi.com/";
url = url.concat(numPNR);
new MyTask().execute(url);

and here's my AsyncTask:

class MyTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
String page = new Communicator().executeHttpGet(url);    
return page;
}

I know my implementation is wrong ! How do I correct it to get a valid output as a string?

Upvotes: 1

Views: 8446

Answers (5)

Stack Overflow User
Stack Overflow User

Reputation: 4082

you need get string via index on async task like below code:

class MyTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... params) {
String page = new Communicator().executeHttpGet(params[0]);    
return page;
}

you can get the return string from asynctask like below code:

String page = new MyTask().execute(url).get();

Upvotes: 2

Mehmet Emre Portakal
Mehmet Emre Portakal

Reputation: 1774

Modify your class like this.

class MyTask extends AsyncTask<String, Void, String>{

String url;

MyTask(String paramUrl)
{
this.url = paramUrl;
}

@Override
protected String doInBackground(String... params) {
String page = new Communicator().executeHttpGet(url);    
return page;
}

And use it like below;

new MyTask(url).execute();

Upvotes: 1

Shani Goriwal
Shani Goriwal

Reputation: 2104

You should change your code like this:

 class MyTask extends AsyncTask<String, Void, String>{

 @Override
 protected String doInBackground(String... params) {
 String page = new Communicator().executeHttpGet(params[0]);    
 return page;
 }

Upvotes: 1

No_Rulz
No_Rulz

Reputation: 2719

Try this

String page = new Communicator().executeHttpGet(params[0]); 

Upvotes: 1

Raghav Sood
Raghav Sood

Reputation: 82553

Change:

String page = new Communicator().executeHttpGet(url);    

to

String page = new Communicator().executeHttpGet(params[0]);    

You could also take the String in in the constructor for your AsyncTask and store it in the instance.

The ... after a parameter mean that it is a vararg, which means it take multiple parameters of that type and puts them into an array for you. You need to treat it like an array within your method.

Upvotes: 1

Related Questions