How can i use AsyncTask Class to showing dialog when execute a task???
class TestAsynTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
ProgressDialog.show(???, null, null);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
Assuming that TestAsyncTask is an inner class to an Activity, then you can use the activity name .this to get the context. If TestAsyncTask is not an inner class, then you will want to pass an instance of your Activity into the constructor so that you can provide it as the Context to the ProgressDialog.show() method.
Here is an example of the inner class method:
class MyActivity extends Activity {
//Activity Lifecycle methods
class TestAsynTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyActivity.this, "title", "message");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//very long computation...
return null;
}
#Override
protected void onPostExecute(Void void) {
dialog.cancel();
}
}
}
You will notice that you should save off the ProgressDialog to a instance variable in the onPreExecute() method and call cancel() on it in the onPostExecute() method.
The other approach looks similar:
class MyActivity extends Activity {
//Activity Lifecycle methods
}
class TestAsynTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
MyActivity activity;
TaskAsynTask(MyActivity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(activity, "title", "message");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//very long computation...
return null;
}
#Override
protected void onPostExecute(Void void) {
dialog.cancel();
}
}
Related
I'm inserting some data in my app's local database inside AysncTask, but when executing the class the progress dialog is not showing on the screen while i can see the running log. I see many related answer but the issue is not resolved. I read the .get() method blocks the ui but I'm already not using this method. I don't why it is not showing on the screen
calling async class from main Activity
AsyncGetDataFromServer task = new AsyncGetDataFromServer(this);
task.execute();
code of AsyncTask class
public class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
Context cxt;
DatabaseHandler dbHelper;
private static ArrayList<DataModel> categoryArrayList;
public AsyncGetDataFromServer(Context context) {
// TODO Auto-generated constructor stub
cxt= context;
pd = new ProgressDialog(cxt);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
dbHelper = new DatabaseHandler(cxt);
}
#Override
protected Boolean doInBackground(Void... params)
{
try {
Log.d("do in background","true");
for (int i = 0; i < response.body().getVideoEntity().size(); i++) {
//inserting in categories
VideoEntity videoEntity;
videoEntity = response.body().getVideoEntity().get(i);
dbHelper.insertChannels(videoEntity);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("exception error", e.getMessage());
}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("on pre execute","true");
pd.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("on post execute","true");
pd.dismiss();
}
}
pass Activity instead of context to the constructor.For example-
AsyncGetDataFromServer task = new AsyncGetDataFromServer(MyActivity.this);
task.execute();
You should implement the method onProgressUpdate and use the method publishProgress :
see https://developer.android.com/reference/android/os/AsyncTask.html
Show dialog in onPreExecute() method & dismiss in onPostExecute() method:
private class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
protected void doInBackground(final Void unused) {
//don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
I have a class that takes care of performing background tasks.
public class BackgroundTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog dialog;
public BackgroundTask(AppCompatActivity activity)
{
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Doing something, please wait.");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
}
#Override
protected void onPostExecute(Void result)
{
if (dialog.isShowing())
{
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params)
{
try
{
// How can I call non-static method of MyActivity here?
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
}
In my activity MyActivity (derived from AppCompatActivity) whenever there are time consuming task, I call it like this:
BackgroundTask task = new BackgroundTask(MyActivity.this);
task.execute();
And then displays waiting animation in dialog which is perfectly fine. I like to know: How can I pass non static method (that consumes time) which belongs to MyActivity (and any other activities) to this BackgroundTask so that I can call it from `doInBackground' ?
Thanks in advance.
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private MyActivity activity;
public BackgroundTask(MyActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
...
#Override
protected Void doInBackground(Void... params) {
try {
activity.callWhatYouNeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
But take care about what you call inside doInBackground, becasue this method executes on non-main thread, so you can't do anything with Views. If you need do something with views, make call like this
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private MyActivity activity;
private Handler uiHandler;
public BackgroundTask(MyActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
uiHandler = new Handler(Looper.getMainLooper());
}
...
#Override
protected Void doInBackground(Void... params) {
try {
mHandler.post(new Runnable() {
#Override
public void run() {
activity.callWhatYouNeed();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
UPDATE: if you want use AsyncTask with other activities, you should use inheritance and create one BaseActivity with callWhatYouNeed()
public abstract class BaseActivity extends AppCompatActivity {
public abstract void callWhatYouNeed();
}
extends from BaseActivity:
public class MyActivity extends BaseActivity {
#Override
public void callWhatYouNeed() {
//Implementation
}
}
and change AsyncTask
public class BackgroundTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog dialog;
private BaseActivity activity;
public BackgroundTask(BaseActivity activity)
{
this.activity = activity;
dialog = new ProgressDialog(activity);
}
#Override
protected Void doInBackground(Void... params) {
try {
activity.callWhatYouNeed();
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
Or you can check activity with instanceof operator:
public class BackgroundTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private AppCompatActivity activity;
public BackgroundTask(AppCompatActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
...
#Override
protected Void doInBackground(Void... params){
try {
if (activity instanceof MyActivity) {
((MyActivity) activity).callWhatYouNeed();
} else if (acitivty instanceof SeocndActivity) {
((SecondActivity) activity).secondCall();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
But it is bad practice to use instanceof, so i strongly recommend use inheritance.
BackgroundTask task = new BackgroundTask(MyActivity.this);
task.execute();
When you call above code in MyActivity class at that time You have passed the instance on class in a constructer. So You can get any non-static method from MyActivity class. for example
public class BackgroundTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog dialog;
private MyActivity activity;
public BackgroundTask(MyActivity activity)
{
this.activity = activity;
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Doing something, please wait.");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
}
#Override
protected void onPostExecute(Void result)
{
if (dialog.isShowing())
{
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params)
{
try
{
activity.callyourmethod();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
}
For this code snippet( I have excluded the doInBackground(), postExecute() etc. )
How should I pass the Activity parameter while calling the Async Task from the CheckServer Activity?
public class CheckServer extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
HttpTicket ticket= new HttpTicket(); //HOW IS THIS LINE DONE? WHAT PARAM SHOULD BE PASSED?
}
#SuppressWarnings("unused")
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
}
You can sipmly do
HttpTicket mHttpTicket = new HttpTicket(this);
mHttpTicket.execute();
You could also delete the constructor, and just pass it to OnPreExecute as param. Then you give it in execute(this);
In your Activity onCreate()
HttpTicket ticket= new HttpTicket(Activity.this);
//passing context to the asynctask constructor
ticket.execute();
//call execute to laod asynctask
Define asynctask as below
private class HttpTicket extends AsyncTask<String, String, String>
{
private Activity activity;
private ProgressDialog dialog;
public HttpTicket(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
dialog.setTitle("Wait...");
}
protected void onPreExecute()
{
dialog.show();
}
protected String doInBackground(String params)
{
//background opearation
return "string";
}
protected void onPostExecute(String result)
{
dialog.dismiss();
//update ui
}
}
I want to set ProgressVisibility(true) in an AsyncTask. Is the AsyncTask in the Main, all is fine.
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This has to be called before setContentView and you must use the
//class in com.actionbarsherlock.view and NOT android.view
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_glance);
}
public class TestTask extends AsyncTask<String, String, ArrayList<String>> {
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// Load some Data...
return null;
}
protected void onPostExecute(ArrayList<String> arg) {
// Hide IndeterminateProgressBar
setProgressBarIndeterminateVisibility(false);
}
}
}
But if I want to generate an Extra File for the AsyncTask, the setProgressBarIndeterminateVisibility is undefined for GroupPageTask...
How can I use this method in an seperate AsyncTask File?
GlanceActivity.java
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This has to be called before setContentView and you must use the
//class in com.actionbarsherlock.view and NOT android.view
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_glance);
}
}
GroupPageTask.java
public class GroupPageTask extends AsyncTask<String, String, ArrayList<String>> {
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// Load some Data...
return null;
}
protected void onPostExecute(ArrayList<String> arg) {
// Hide IndeterminateProgressBar
setProgressBarIndeterminateVisibility(false);
}
}
You could hand over the context during AsyncTask construction:
public class GroupPageTask extends AsyncTask<String, String, ArrayList<String>>
{
private Context context;
public AsyncTask(Context context)
{
this.context = context;
}
protected void onPreExecute()
{
((Activity) context).setProgressBarIndeterminateVisibility(true);
}
protected void onPostExecute(ArrayList<String> arg)
{
((Activity) context).setProgressBarIndeterminateVisibility(false);
}
}
Then create your AsyncTask with the new constructor from your activity:
GroupPageTask groupPageTask = new GroupPageTask(this);
With the Answer of Matt Handys, i found the right way...
GlanceActivity.java
public class GlanceActivity extends SherlockActivity implements ActionBar.OnNavigationListener {
public static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
GroupPageTask groupPageTask = new GroupPageTask(getSherlock());
}
}
GroupPageTask.java
public class GroupPageTask extends AsyncTask<String, String, ArrayList<Mannschaft>> {
private ActionBarSherlock sherlock;
#Override
public void onPreExecute() {
// Show IndeterminateProgressBar
sherlock.setProgressBarIndeterminateVisibility(true);
}
protected void onPostExecute(ArrayList<Mannschaft> arg) {
sherlock.setProgressBarIndeterminateVisibility(false);
}
}
public class async extends AsyncTask<String, Integer, String>{
ProgressDialog prog;
#Override
protected void onPreExecute() {
super.onPreExecute();
prog=new ProgressDialog(async.this);//This is chowing error
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setMax(100);
prog.show();
}
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values) {
prog.setProgress(values[0]);
super.onProgressUpdate(values);
}
}
The above code is producing the error:
the constructor ProgressDialog(AndroidasynctaskActivity.async) is
undefined
Why is this so? Can anyone please help me troubleshoot this?
As already mentioned, the reason this is happening is because the ProgressDialog constructor you're using needs a Context object. Here's one example of how you can do this.
Modify your async class and add a single-argument constructor that accepts a Context object. Then modify the onPreExecute method to use said Context. For example:
public class async extends AsyncTask<String, Integer, String>{
private Context context;
ProgressDialog prog;
public async(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
prog=new ProgressDialog(context);
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setMax(100);
prog.show();
}
// ...
}
Then to instantiate and run this AsyncTask:
async mTask = new async(context);
mTask.execute(params);
Async tasks do not provide an application or activity context. You may have to pass the context in if this class is contained within the activity that called it.