Could anyone tell me what is going wrong here?
public class BackgroungTask extends AsyncTask<String, Void, Void> {
public Void doInBackground(String... params) {
//tasks
return; //error occurs here!
}
public void onPostExecute(Void result) {
//codes
}
}
The above class does not depend on return values. So onPostExceute() simply execute codes written in there.
Thanks in advance!
just return null.
public class BackgroungTask extends AsyncTask<String, Void, Void> {
public Void doInBackground(String... params) {
//tasks
return null;
}
public void onPostExecute(Void result) {
//codes
}
}
I think you have to use "return null;" instead of just "return;", as Void is a class around the usual "void" value.
In doInBackGround return null, as Void is an object (does not = void)..
public class BackgroungTask extends AsyncTask<String, Void, Void> {
public Void doInBackground(String... params) {
//tasks
return null; //error occurs here!
}
public void onPostExecute(Void result) {
//codes
}
}
AsyncTask works like this
onPreExecute -> doInBackGround -> onPostExecute
Neglecting progressUpdates etc, as soon doInBackGround is complete, control goes to onPostExecute. A simple return disrupts this flow hence causing the error. To Solve this, replace with return null Since its a void. The return statement parameters are passed to onPostExecute as parameter, where you can use it to see wheter it has been successful.
doInBackGround returns null value
public class BackgroungTask extends AsyncTask<String, Void, Void> {
....
....
}
check this Android dev doc for asynchronous task in andorid
Related
I would need some help to figure out how to return a doInBackground() value in AsyncTask which code is an interface. Here is an example
private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
public MyAsyncTask() {
super();
// do stuff
}
#Override
protected Boolean doInBackground(Void... void) {
checkIfContentAvailable(new interfaceMediaAvailableToDownload() {
#Override
public void onComplete(boolean resutl) {
return result; //This must be doInBackground return value, not onSuccess which is Void
}
#Override
public void onInternetError() {
return false; //This must be doInBackground return value, not onSuccess which is Void
}
};
}
#Override
protected void onPostExecute(Boolean result) {
if (result){
//Do stuff
}else{
//Do stuff
}
}
}
Obviously, this above code can't work because I don't know how to return onSuccess() value to doInBackground().
I hope this is clear enough....
EDIT
Okay my bad, I thought it would have been more readable to hide MyInterface usage, but I realize through your answers it is not. So I completed the code to add more details.
Any idea please?
Thank you in advance.
Create the object of the Mynterface in the place where you execute the AsyncTask.
Create a object reference of the MyInterface inside the AsyncTask ans set your interface object.
Then call the onSuccess method like below
`
private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
MyInteface myInterface;
setMyInterface(MyInterface interface){this.myInterface = interface;}
public MyAsyncTask() {
super();
// do stuff
}
#Override
protected Boolean doInBackground(Void... void) {
this.myInterface.onSuccess(); // or call on failure if failure happened
}
#Override
protected void onPostExecute(Boolean result) {
//Do stuff with result
}
}
`
Use it like ...
MyAsyncTask async = new MyAsyncTask();
async.setMyInterface(this);
async.execute();
Implement the interface in the place where your are executing.
This how you can do it.
Here is small example for to understand my question:
public class InitSettings_Task extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
request1result = request1;
if (request1result) {
result = httprequest2;
} else {
result = httprequest3;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
//do something with result
}
}
I know that Volley is a super library, but here i can't use it because my AsyncTask can ends before i will receive answer of first request.
Can somebody help me to understand what the best style for to send http request for this logic?
Before i have used Volley with Sleep() for to wait answer, but from my view it's not best sollution
Sounds like you are trying to do this -
public class InitSettings_Task1 extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
request1result = request1;
return result;
}
#Override
protected void onPostExecute(Integer result) {
//do something with result
if (request1result) {
result = new InitSettings_Task2().execute(httprequest2);
} else {
result = new InitSettings_Task2().execute(httprequest3);
}
}
}
public class InitSettings_Task2 extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
return result;
}
#Override
protected void onPostExecute(Integer result) {
//do what you want with result ?
}
}
But I would advise you against this. Its better to do this using frameworks like RxJava or even EventBus which are better suited for this scenario.
I have realized it with OkHTTP library. Thank's "Selvin" for right direction )
I have an IME service class and a long operation method in it. I want to run the LongOperation task in a asyncTask class that is in the IME Service class.
public class Myimeservice extends InputMethodService
implements KeyboardView.OnKeyboardActionListene {
//...
//some code here....
//...
public void setDictionary(){
//....
}
private class LongOperation extends AsyncTask<String, Void, String> {
private Myimeservice parent;
public LongOperation(Myimeservice pim){
parent = pim;
}
#Override
protected String doInBackground(String... params) {
Myimeservice tmp = new Myimeservice();
tmp.setDictionary();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
//app.hideLoading();
}
#Override
protected void onPreExecute() {
//app.showLoading();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
When i run it, the application forced to close. please help me.
I think the error is somewhere in your public void setDictionary() method.
I assume that you are manipulating a variable that is bound to the UIThread/MainThread, the application will crash since doInBackground is on another Thread.
Instead make the setDictionary() method return the dictionary and return it instead of "Executed" in doInBackground().
This will call the onPostExecute(Object result) which is run on UIThread/MainThread.
Something like this:
private class LongOperation extends AsyncTask<String, Void, Dictionary> {
#Override
protected Dictionary doInBackground(String... params) {
Myimeservice tmp = new Myimeservice();
Dictionary dict = tmp.setDictionary();
return dict;
}
#Override
protected void onPostExecute(Dictionary result) {
//do what ever you meant to do with it;
}
}
If you are not expecting any result from it you can just do:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
tmp.setDictionary();
}
});
I use the Runnable instead of AsyncTask and the problem solved.
final Runnable r = new Runnable(){
public void run(){
setDictionary();
}
};
this code is in onCreate() method of service.
Tanks a lot Tristan Richard.
Android Studio is insisting that I am missing a return value in doInBackground, even though it seems to be declared as Void. Am I overlooking something?
AsyncTask<Boolean, Void, Void> initiateConnection = new AsyncTask<WebSocketClient, Void, Void>() {
#Override
protected Void doInBackground(WebSocketClient ... clients) {
clients[0].connect();
}
#Override
protected void onPostExecute(Void result) {
Log.i(st, "Socket connected.");
}
};
initiateConnection.execute();
}
Void (uppercase V) is not void (lowercase v). With void, you can just "fall off the bottom of the method". With Void, you need to explicitly return something, typically null.
You need to return null
protected Void doInBackground(WebSocketClient ... clients) {
clients[0].connect();
return null;
}
Is there anyway to use AsyncTask without passing in any parameters? I am currently passing in an empty string, but I'm not doing anything with it:
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "" });
class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(MainScreen.this);
#Override
protected void onPreExecute() {
dialog.setMessage("Gathering data for\n"+selectedSportName+".\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... urls) {
//go do something
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
startTabbedViewActivity();
}
}
private void startTabbedViewActivity(){
Intent intent = new Intent(MainScreen.this, TabbedView.class);
intent.putExtra(SPORT_NAME_EXTRA, selectedSportName);
intent.putExtra(HEADLINES_FOR_SPORT_EXTRA, existingSportHeadlines.get(selectedSportName));
intent.putExtra(SCORES_FOR_SPORT_EXTRA, existingSportScores.get(selectedSportName));
intent.putExtra(SCHEDULE_FOR_SPORT_EXTRA, existingSportSchedule.get(selectedSportName));
startActivity(intent);
}
For some reason, when I run the code as shown, with nothing happening in doInBackground(), the dialog dissapears, and the TabbedView activity starts.
But, when I use doInBackground() to run some code, the dialog dissapears, but, the TabbedView activity won't start. So I'm wondering if I could be doing anything differently?
Yes you can use AsyncTask without passing a String to the doInBackground() method.
Just change the first and third generic types from String to Void:
class DownloadWebPageTask extends AsyncTask<Void, Void, Void> {
}
From the doc:
The three types used by an asynchronous task are the following:
1)Params, the type of the parameters sent to the task upon execution.
2)Progress, the type of the progress units published during the
3) background computation. Result, the type of the result of the
background computation.
For the signature of onPostExecutetry this:
#Override
protected void onPostExecute(Void unused) {
}
EDIT:
For the parameters it's actually very simple.
Consider this:
class MyTask extends AsyncTask<Type1, Type2, Type3> {
#Override
protected void onPreExecute() {
}
#Override
protected Type3 doInBackground(Type1... param) {
}
#Override
protected void onProgressUpdate(Type2... progress) {
}
#Override
protected void onPostExecute(Type3 result) {
}
}
In order to determine what Type1, Type2 and Type3 should be, you'll have to ask yourself 3 questions:
What parameter should I pass to my task? => Type1
What is the type of the intermediate results that need to be shown during processing? =>
Type2
What is the type of the resulting operation? => Type3
In your case, I don't know whether the URL that you are downloading data from is defined in a globally or you want to pass it to the task. If it's defined globally, then you don't Type1 should be Void.
If you want to pass it to the task, then you can pass it to the doInBackground() method and Type1 would be String.
Obviously for your case you don't need to worry about Type2 since you aren't publishing any intermediate results and since you aren't doing anything with the result in onPostExecute() then Type3 is Void too.
To summarize you'll have:
class DownloadWebPageTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... urls) {
// do something with urls[0]
}
#Override
protected void onPostExecute(Void unused) {
// dismiss pd and start new intent
}
}
Or:
class DownloadWebPageTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... unused) {
}
#Override
protected void onPostExecute(Void unused) {
// dismiss pd and start new intent
}
}
Depending on your needs. Is that clear enough?
You simple specify Void for AsyncTask generics
class DownloadWebPageTask extends AsyncTask<Void, Void, Void> {
Look at the AsyncTask generics section