Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I don't want to pass any arguments to doInBackground method of the AsyncTask.
So what should be the code like?
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AsyncExample extends Activity{
private String url="http://www.google.co.in";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
}
According to AsyncTask, its
AsyncTask<Params, Progress, Result>
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the
background computation.
Result, the type of the result of the background computation.
So if you want to pass void in doInBackground just pass void in place of Params.
Example code:
class DownloadLink extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Do Your stuff here..
return null;
}
}
And call it as:
new DownloadLink().execute();
Create your AsyncTask class as if you don't want to pass any parameter to doInBackground :
public class LongOperation extends AsyncTask<Void, Void, String> {
public LongOperation(Context context) {
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
and start AsyncTask as without passing any parameter to execute :
LongOperation longOperation = new LongOperation(this);
longOperation.execute();
Why don't you want to pass any arguments to it? You should explain...
This is how it usually works (example):
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
And to execute it you call:
new DownloadFilesTask().execute(url1, url2, url3);
Source: Android docs
Related
I don't know how to tell the problem.
I have two AsyncTask methods. doAreYouStanding and StartTimeout, when I'm running both in MainActivity
if StartTimeout in if I wait 10 seconds, the other method is waiting.
Why is this startTimeout thread pausing my other method?
doAreYouStanding in doInBackground works after waiting onPreExecute for 10 seconds
new doPopup().execute((Void) null);
// new StartTimeout().execute((Void) null);
private class doAreYouStanding extends AsyncTask<Object, Object, Void> {
#Override
protected void onPreExecute() {
Log.e("YHACKUP", "onPreExecute");
super.onPreExecute();
}
#Override
protected Void doInBackground(Object... objects) {
Log.e("YHACKUP", "doInBackground");
return null;
}
}
private class StartTimeout extends AsyncTask<Object, Object, Void> {
#Override
protected void onPostExecute(Void aVoid) {
if (!(ActivitySplash.this).isFinishing()) {
layout_timeout.setVisibility(View.VISIBLE);
}
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Object... objects) {
// try {
// Thread.sleep(10000);
// } catch (Exception e) {
// }
return null;
}
}
I'm sorry if my english is bad
By default async tasks run serially. so Intil, the first asyncTask gets completed, second asyntask will not be started. In order to run paelelly, use executeOnExecutor method
new doPopup().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I don't want to pass any arguments to doInBackground method of the AsyncTask.
So what should be the code like?
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AsyncExample extends Activity{
private String url="http://www.google.co.in";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
}
According to AsyncTask, its
AsyncTask<Params, Progress, Result>
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the
background computation.
Result, the type of the result of the background computation.
So if you want to pass void in doInBackground just pass void in place of Params.
Example code:
class DownloadLink extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Do Your stuff here..
return null;
}
}
And call it as:
new DownloadLink().execute();
Create your AsyncTask class as if you don't want to pass any parameter to doInBackground :
public class LongOperation extends AsyncTask<Void, Void, String> {
public LongOperation(Context context) {
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
and start AsyncTask as without passing any parameter to execute :
LongOperation longOperation = new LongOperation(this);
longOperation.execute();
Why don't you want to pass any arguments to it? You should explain...
This is how it usually works (example):
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
And to execute it you call:
new DownloadFilesTask().execute(url1, url2, url3);
Source: Android docs
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.
I'm using AsyncTask to download some files, and want to do something after all tasks finished.
Is there any easy way to do this?
Keep track of how many async tasks you have running and do something when the total is 0.
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public int numOfTasks = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addTask(){
numOfTasks++;
}
public void removeTask(){
numOfTasks--;
}
public void allTasksComplete(){
if(numOfTasks ==0){
//do what you want to do if all tasks are finished
}
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
String responseString = "";
return responseString;
}
#Override
protected void onPreExecute()
{
addTask(); // adds one to task count.
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
removeTask(); // subtracts one from task count.
allTasksComplete(); // checks to see if all tasks are done... task count is 0
}
}
}
AsyncTask has a callback method name onPostExecute. It will be execute when the background task finish.
You can use onPostExecute() callback when Asyn task finishes background processing, In a typical scenarion you would notify the UI (list adapter or UI Activity) that download of the File is finished and UI can refresh or populate the data.
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
Please have a look at this Android Ref example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
Example2:
https://github.com/ashutoshchauhan13/TwitterFeedApp/blob/master/TwitterFeedApp/src/com/sixthsense/twitterfeed/ui/TwitterFeedActivity.java
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