Pass more values in doInBackground AsyncTask Android - android

How to pass more values in the doInBackground
My AsyncTask looks like this.
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
{
}
}
Is it possible somehow to pass more values on my protected String DoInBackground
for example: protected String doInBackground(String... sUrl, String... otherUrl, Context context)
And how to execute the AsyncTask after? new DownloadFile.execute("","",this) or something?

you can send multiple parameters as you can send them as varargs. But you have to use same Type of parameter. So to do what you are trying you can follow any of the followings
Option 1
you can use a setter method to set some value of the class member then use those in doInBackGround. For example
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public void setContext(Context c){
context = c;
}
#Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}
Option 2
Or you can use constructor to pass the values like
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadFile (Context c){
context = c;
}
#Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}

String... sUrl
the three consecutive dots meaning more then one String. The dots are varargs
And how to pass the Context?
you can force it adding a constructor that takes the Context as parameter:
private Context mContext;
public void setContext(Context context){
if (context == null) {
throw new IllegalArgumentException("Context can't be null");
}
mContext = context;
}

you can do something like this inside your doInBackground method:
String a = sUrl[0]
String b = sUrl[1]
execute AsyncTask in this way:
new DownloadFile().execute(string1,string2);
the first value : sUrl[0] will be the one passed from string1 and
surl[1] will be the second value passed i.e string2 !

Yes you can pass more values in constructor but not in doInBackground
Try this way
new DownloadFile(String sUrl,String other Url,Context context).execute();
Async Task
private class DownloadFile extends AsyncTask<String, Integer, String> {
public DownloadFile(String url,String url2,Context ctx)
{
}
#Override
protected String doInBackground(String... sUrl) {
{
}
}

You cannot, for the following reasons :
protected String doInBackground(String... sUrl, String... otherUrl, Context context)
is not a valid method signature. The dots notations (Varargs) can only be used as the last parameter of the method. This restriction is because otherwise it would make polymorphism much more complex. In fact, how would java know which of your Strings go to sUrl, and which goes to otherUrl?
Moreover, doInBackground overrides a method from AsyncTask. As such, you cannot change the method signature.
What you can do, however, is make those values members of your class and pass in the constructor of your DownloadFile class or add setters to set them before calling execute.

you can use constructor
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public void DownloadFile(Context c,String one, int two){
context = c;
}
#Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}

new DownloadFile().execute(Str1,str2,str3,........);
this is one way to pass more url... if you want send more values in doinbackground method..
public class DownloadFile extends AsyncTask<DataHolders, Integer, String> {
public class DataHolders {
public String url;
public String myval;
}
#Override
protected String doInBackground(DataHolders... params) {
return null;
}
}
you can call the class with
DataHolders mhold = new DataHolders();
new DownloadFile().execute(mhold,mhold2,mhold3,........);

Ypu can create constructor to pass different type parameters and also strings data using String......str
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
byte[] byteArray;
public DownloadTask (Context c,byte[] byteArray){
context = c;
byteArray=byteArray;
}
#Override
protected String doInBackground(String... str) {
{
// use context here
System.out.println(param[0]);
}
}
new DownloadTask(context,bytearray).excute("xyz");

new DownloadFile().execute("my url","other parameter or url");
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
{
try {
return downloadContent(sUrl[0], sUrl[1]); // call
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
}

Related

How to pass a value to AsyncTask?

What is the proper way in the following code (it's a bit complicated structure to me) to get url from the method gotUrl() to the doInBackground() method of AsyncTask in order to use it in onPostExecute(), after the doInBackground() method has completed its task?
public class PlayerActivity extends CustomActivity implements
ProblemListener{
public class PlayChannel extends
AsyncTask<CustomChangeChannel, String, String> {
#Override
protected String doInBackground(CustomChangeChannel... params) {
initOctoshapeSystem();
return url;
}
#Override
protected void onPostExecute(String url){
}
}
public void initOctoshapeSystem() {
os = OctoStatic.create(this, this, null);
os.setOctoshapeSystemListener(new OctoshapeSystemListener() {
#Override
public void onConnect() {
mStreamPlayer = setupStream(OCTOLINK);
mStreamPlayer.requestPlay();
}
});
}
public StreamPlayer setupStream(final String stream) {
StreamPlayer sp = os.createStreamPlayer(stream);
sp.setStatusChangedListener(new StatusChangedListener() {
#Override
public void statusChanged(byte oldStatus,
final byte newStatus) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//todo
}
});
}
});
sp.setListener(new StreamPlayerListener() {
#Override
public void gotUrl(String url) {
//String to be passed
}
});
return sp;
}
}
AsyncTask<Param1, Param2, Param3>
Param 1 is the param that you pass into your doInBackground method.
Param 2 is what you want to get while the AsyncTask working.
Param 3 is what you want to get as result.
You can declare all them as Void.
AsyncTask<Void, Void, Void>
In your case you want to pass String URL to your doInBackground, so:
AsyncTask<String, Void, Void>
Pass your URL String when you call the execute.
mAsyncTask.execute("your url");
Then get it in the doInBackground:
protected Void doInBackground(String... params) {
String yourURL = params[0];
return null;
}
change this
public class PlayChannel extends
AsyncTask<CustomChangeChannel, String, String>
to this
public class PlayChannel extends
AsyncTask<String, String, String>
and then use
PlayChannel channel = new PlayChannel(url);

how to call class AsyncTask to another class?

I tried to call the "AsyncTask" class from another class called "MainActivity" but "AsyncTask" Class is inside the class called "SiteAdapter". I tried to pass a reference but it not working. How could do that?
Main Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Call the class AsyncTask
new GetAddressTask(this).execute(); // <----ERROR - GetAddressTask cannot be resolved to a type
}
}
AsyncTask inside SitesAdapter class:
public class SitesAdapter extends ArrayAdapter<StackSite> {
...//PROCESS
public class GetAddressTask extends AsyncTask<String, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
//Pass a reference to MainActivity
private MainActivity mainActivity; // <--- WARNING - The value of the field SitesAdapter.GetAddressTask.mainActivity is not used
public GetAddressTask(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... arg0) {
...
}
#Override
protected void onPostExecute(String result) {
...
}
}
}
First of all, MainActivity is not a class that you can not define an object from. It extends Activity.
Change your AsyncTask class with it;
public static class GetAddressTask extends AsyncTask<String, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(String... values) {
// If you want to use 'values' string in here
String values = values[0];
}
#Override
protected void onPostExecute(String result) {
...
}
}
Then call this with it;
String values = ""; //You can pass any string value to GetAddressTask with that parameter
//Call the class AsyncTask
new SitesAdapter.GetAddressTask(this).execute(values);
make GetAddressTask static:
public static class GetAddressTask
Try this, this is working for me.
Just create a method in your SitesAdapter class and call it from your MainActivity like this :
new SitesAdapter().start(MainActivity.this);
now in your SitesAdapter class do this :
private Context mContext;
public void start(){
mContext = context;
new GetAddressTask().execute();
}
May this help you
You could make it static then call it with
SitesAdapter.GetAddressTask myClass = new SitesAdapter.GetAddressTask();
myClass.execute();
But, if you are going to be needing this in multiple activities, then it is probably worth it to take it out of that class and put it in its own file.
If you will need to update your UI from the task, you can see this answer on using an interface with a callback to your calling Activity.

Android AsyncTask pass variable value

How do I pass value on doInBackground so It can use it. When I type the String directly inside doInBackgroud it works. But I have three type "Professional", "General", "Special" I don't want to create 3 asyncTask. In my research i found that I need to create contructor but im don't get It.
String type = "professional";
new loadQuestioners().execute(type);
public class loadQuestioners extends AsyncTask <String, Integer, JSONArray> {
#Override
protected JSONArray doInBackground(String... arg0) {
//is the arg0 is the type i passed?
return null;
}
}
Just modify the code as follows,
public class loadQuestioners extends AsyncTask <String, Integer, JSONArray> {
#Override
protected JSONArray doInBackground(String... arg0) {
//is the arg0 is the type i passed?
String yourType=arg0[0];
return null;
}
"yourType" contains the type you passed while creating asyncTask
I can see two ways of going about this:
1st:
new loadQuestioners().execute("professional");
public class loadQuestioners extends AsyncTask <String, Integer, JSONArray>
{
#Override
protected JSONArray doInBackground(String... arg)
{
String word = arg[0];
return null;
}
}
And 2nd: create a constructor and pass the argument:
new loadQuestioners("professional").execute();
public class loadQuestioners extends AsyncTask <String, Integer, JSONArray>
{
private String word;
public loadQuestioners(String word)
{
this.word = word;
}
#Override
protected JSONArray doInBackground(String... arg0)
{
//use word
return null;
}
}
String... args means that it can take as paramrters:
a single String object OR
an array of Strings
So in your case pass an array of Strings to your async task's execute method and doInBackground will get them just fine. Inside doInBackground use the arg0 parameter as a String array and you should be good.

Use AsyncTask in other class

I wish to use asynctask in class of its on, the reason is that later on I need to export this class as external jar for that the user can add this to his project and just use it.
class DownloadFile extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < files; i++)
{
//send file to download
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
//need to send notification to main class
//pr_bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
public boolean ftpDownload(String srcFilePath, String desFilePath, final long size_server) {
//download file
publishProgress((int) prog);
}
};
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
When the user will use:
public class UserClass extends Activity {
String serialnum = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userclass);
new Download().execute();
}
How can the user in his class can get notification about the progress of asynctask?
you can pass the context of your class via the asynctask constructor. By using that context you can access the display related methods of your class
so in your separate AsyncTask class create a constructor like
Context c;
public Download(Context c){
context = c;
}
and from the main class you can call like
new Download(this).execute();
by using the context you can access the public components of your class
Just set int progress var in your class and update it when progress and make getter method in your async task class, so user can use getProgress() method to get progress from async task.
or
You can create interface inside your async task which users should implement so that they can get callback on progress of async task.

Android Asynctask passing a single string

I would like to pass a single string into an asynctask. Could anyone show me how it is done? my getEntity needs The method getEntity(Activity, String, EntityGetListener) but I keep passing this String[]
String pass= story.get(position).getEntity();
new RemoteDataTask().execute(pass);
private class RemoteDataTask extends AsyncTask<String, String, Long> {
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
EntityUtils.getEntity(activity, params, new EntityGetListener() {
#Override
public void onGet(Entity entity) {
viewcount = entity.getEntityStats().getViews();
}
#Override
public void onError(SocializeException error) {
}
});
return null;
}
}
You already have this
new RemoteDataTask().execute(pass); // assuming pass is a string
In doInbackground
#Override
protected Long doInBackground(String... params) {
String s = params[0]; // here's youre string
... //rest of the code.
}
You can find more info #
http://developer.android.com/reference/android/os/AsyncTask.html
Update
Asynctask is depecated. Should be using kotlin coroutines or rxjava or any other threading mechanism as alternatives.
You can build AsyncTask with a constructor.
public class RemoteDataTask extends AsyncTask<String, String, Long> {
private String data;
public RemoteDataTask(String passedData) {
data = passedData;
}
#Override
protected String doInBackground(Context... params) {
// you can access "data" variable here.
EntityUtils.getEntity(activity, params, new EntityGetListener() {
#Override
public void onGet(Entity entity) {
viewcount = entity.getEntityStats().getViews();
}
#Override
public void onError(SocializeException error) {
}
});
return null;
}
}
In the application (Activity, Service etc), you can use;
private RemoteDataTask mTask;
private void doStuff(){
String pass = "meow"; // story.get(position).getEntity();
mTask = new RemoteDataTask(pass);
mTask.execute();
}

Categories

Resources