i am downloading data from website using asynctask and
my code for async task is below
public class getSyncTaskInBackground extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
getSynchronizeTask();
return null;
}
#Override
protected void onPostExecute(Void result) {
if(progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
displaySynchronizetask();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(synchronize.this, "Tasks are synchroning...", "Please wait...");
super.onPreExecute();
}
#Override
protected void onCancelled() {
super.onCancelled();
if(progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
this thread takes more time to complete task
so if i want to cancel this thread in between of process then i had write this code of back button pressed
or if progressbar is already dismiss then i want to close activity by calling finish();
my code for back button is as below
#Override
public void onBackPressed() {
syncThread.cancel(true); //syncThread is the object of getSyncTaskInBackground
if(progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
} else {
finish();
}
}
Now when i pressed back button then the progressdialog is not dismiss
is any mistake in mycode ? is any way to complete my need ?
please help me
Hi
You might want to call
setCancelable with true on your progressDialog instance :
http://developer.android.com/reference/android/app/Dialog.html#setCancelable(boolean)
If you want an event on the cancelation of your progressDialog
you can set an onCancelListener
http://developer.android.com/reference/android/app/Dialog.html#setOnCancelListener(android.content.DialogInterface.OnCancelListener)
hope this helps
Related
I have a ListFragment which has an AsyncTask in it to write data to a remote store. I need to have a ProgressDialog show status while the data is being sent since this may take a considerable time depending on the number of files being stored remotely. I have done this successfully from an Activity, but I am having issues showing progress within the ListFragments AsyncTask.
This is complicated by the fact that I need to show updates within the doInBackground method of the task, since that is where the major of the work is being done. That said, the ProgressDialog is not showing up at all even in the non-UI bound onPreExecute() method. Looking at other posts for ProgressDialogs I am using passing getActivity() to the ProgressDialog. Also this mechanism is working with several other Activity classes I am using else where, just not here. I am probably just missing something obvious so any help is appreciated.
Here is a code example - forgive me if it does not compile or has a mistake - I had to remove boatloads of code to boil it down to the problem at hand:
public class MyFragment extends ListFragment {
private ProgressDialog mProgress;
private void hideProgress() {
if (mProgress != null) {
mProgress.dismiss();
mProgress = null;
}
}
private void showProgress(String message) {
if (mProgress != null) {
mProgress.dismiss();
mProgress = null;
}
mProgress = ProgressDialog.show(getActivity(), null, message, true, false);
}
protected void updateProgressMessage(String message) {
if (mProgress != null && mProgress.isShowing()) {
mProgress.setMessage(message);
}
}
public syncForms() {
new syncPendingFormsResultTask().execute();
}
private class syncTask extends AsyncTask<Object, String, Boolean> {
#Override
protected void onCancelled() {
hideProgress();
}
#Override
protected void onPreExecute() {
showProgress("Submitting Form...");
}
#Override
protected Boolean doInBackground(Object... params) {
onProgressUpdate("Uploading Form");
}
#Override
protected void onProgressUpdate(String... values) {
String message = values[0];
updateProgressMessage(message);
}
#Override
protected void onPostExecute(Boolean result) {
showProgress("Upload Complete...");
hideProgress();
}
}
}
}
The syncForms() is the method called to initiate the task.
I defined an AsyncTask in a button's onclicklistener, and once user clicks the button, ideally progress dialog shows while asynctask downloading.
However, progress dialog just flashes in and disappears before the results returned, and the button gets focused while the asynctask works in the background.
Can someone help me figure out what I did wrong here? Code snippet:
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
((Button)findViewById(R.id.buttonLoginActivity)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> downloadTask= new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
String data = Service.getSomeData();
context.getContentResolver.notifyChange("content://some_url");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(progressDialog== null) return;
if(progressDialog!=null) {
progressDialog.dismiss();
progressDialog = null;
}
}
};
progressDialog.show();
downloadTask.execute();
try{
downloadTask.get();
}catch(Exception e){
e.printStackTrace();
return;
}
}
});
Don't use get()
downloadTask.get();
this is a blocking call. From the Docs
Waits if necessary for the computation to complete, and then retrieves its result.
Just use execute() as you are then do what you need with the results in onPostExecute()
show the progressDialog on the onPreExecute which need to be writen, and it will run on the UI thread, not in background ( android 4 )
also I would call the async task on a new Handler().post(myAsynctaskcaller)
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
I am new to android.I need to show an activity indicator while synchronizing.On clicking a button,i am redirecting to a new activity.In this new activity i am synchronizing.I need to show an activity indicator on button click till it is synchronized.
Synchronizing is effectively a network task And you have to do this on Background ( Async Task) So you can call an AsyncTask in your new Activity
private class SyncOperation extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
// Synchronize code here
return null;
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
protected void onPreExecute() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Synchronizing, please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
}
}
}
Now in OnCreate() of new Activity
SyncOperation syncTask=new SyncOperation();
syncTask.execute();
It will show a loader like
I have problem in my app with progress dialog in AsyncTask:
my AsyncTask is doing some geting data from internet in doInBackGround(), I am starting progress dialog in onPreExecute(), finish dialog in onPostExecute().
I execute this asyncTask when click on Button. 1st time When I click this button (long operation takes place) progress dialog is not shown. But next times Progress dialog is shown normaly.
What can be the problem that 1st time of running AsyncTask, progress dialog isnt shown ?
this is onClick method:
public void onClickFind(View view){
new Task_Search().execute();
}
This is task Task_Search:
private class Task_Search extends AsyncTask<Void, Void, Void> {
#SuppressWarnings("deprecation")
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
protected Void doInBackground(Void... unused) {
//some geting of web content here
}
#SuppressWarnings("deprecation")
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_TASKING);
}
}
progress dialog defined in MainActivity:
#SuppressWarnings("deprecation")
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TASKING:
mSearchDialog = new ProgressDialog(this);
mSearchDialog.setMessage("Searching for field number..");
mSearchDialog.setCancelable(true);
return mSearchDialog;
}
return super.onCreateDialog(id);
}
Before of using AsyncTask I used separate Thread for downloading data instead: in onClick, I started first progressDialog then Thread, when Thread finished also progressDialog was stoped,
Behaviour was same:
1st time of click on Button dialog wasnt shown, next times its shown.
Anybody who can help ?
I cant see you calling show() on the dialog.
Replace
#SuppressWarnings("deprecation")
protected void onPreExecute() {
showDialog(DIALOG_TASKING);
}
with
#SuppressWarnings("deprecation")
protected void onPreExecute() {
showDialog(DIALOG_TASKING).show();
}
Do not call showDialog insode onPreExecute().
AsyncTask provides publishProgress() method which can be invoked from doInBackground() to publish updates on the UI thread.
Okay,
I created in MainActivity my own methods:
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Searching for field number..");
mProgressDialog.show();
return;
}else{
mProgressDialog.setMessage("Searching for field number..");
mProgressDialog.show();
return;
}
}
also:
public void closeProgressDialog() {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
return;
}
I changed AsyncTask following:
private class Task_Search extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
// showDialog(DIALOG_TASKING);
showProgressDialog();
}
protected Void doInBackground(Void... unused) {
//Some long duration stuff here
}
protected void onPostExecute(Void unused) {
//dismissDialog(DIALOG_TASKING);
closeProgressDialog();
}
}
mProgressDialog is a private member of MainActivity
private ProgressDialog mProgressDialog;
Situation is same: wheck onClick on button: 1st time ProgressDialog stuck, next times it works perfect
In my code I load a spinner adapter by using Async Task
In My case The ProgressDialog is Not dismissing
This is My code.
I want to show the item after adapter load and the progressDialog is to dismiss
Please Help me, Thanks
private class LoadMoreVehicals extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
progressBar = ProgressDialog.show(RegistrationScreen.this, "",
"Loading...");
progressBar.setIndeterminate(true);
progressBar.setIndeterminateDrawable(getResources().getDrawable(
R.anim.progressbar_handler));
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
String countryUrl = ConstantURL.COUNTRY_URL;
getCounty(countryUrl);
countrySpinner
.setAdapter(new MyCustomSpinnerAdapter(
RegistrationScreen.this,
R.layout.spinner_dropdown,
countyList));
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.getProgress();
}
#Override
protected void onPostExecute(Object result) {
progressBar.dismiss();
Log.e("Im in onPostExecute", "");
super.onPostExecute(result);
}
}
While programming in Android you should remember one thing that any task which draws something on the screen should be executed on the main thread. When you set the adapter then android calls the getView() method of the adapter and draws views on the screen. So you should set the adapter in the postExecute() method instead in doInBackground() method.
Here is a small sample to clear my point:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute ( )
{
//starting the progress dialogue
pd.show();
}
#Override
protected Void doInBackground (Void... params)
{
//fetch data here
...
...
return null;
}
#Override
protected void onPostExecute (Void result)
{
//set adapter here
...
...
//dismissing the progress dialogue
pd.dismiss();
}
}
In my experience i have so many problems with async runs and UI so now always separate the stuff trying to place the "responsibilities" in each place. So i do something like this:
Create my Async class with the process i want to do and nothing that transform the UI in it
Create a function in UI thread that modify the UI when async task finish, something like OnAsyncTaskComplete(Object response)
Keep communicated the threads
public class MyActivity extends Activity {
private static MyAsyncClass backgroundTask;
private static ProgressDialog pleaseWaitDialog;
//......activity stuff.......
#Override
public void onPause()
{
super.onPause();
//Get rid of progress dialog in the event of a screen rotation or other state change. Prevents a crash.
if (pleaseWaitDialog != null)
pleaseWaitDialog.dismiss();
}
//Function to avoid lose the async thread if the app interrupts (phone rotation, incoming call, etc) RECOMENDED TO HANDLE THIS!!
//Sets the current state after app resume
#Override
public void onResume()
{
super.onResume();
//If there is a background task set it to the new activity
if ((backgroundTask != null) && (backgroundTask.getStatus() == Status.RUNNING))
{
if (pleaseWaitDialog != null)
pleaseWaitDialog.show();
backgroundTask.setActivity(this);
}
}
}
//Logic business after the web service complete here
//Do the thing that modify the UI in a function like this
private void onTaskCompleted(Object _response)
{
//For example _response can be a new adapter
MyList.setAdapter((BaseAdapter)_response);
//or can be a list to create the new adapter
MyList.setAdapter(new MyAdapter(this, (ArrayList<String>)_response));
//or can be anything you want, just try to make here the things that you need to change the UI
}
/**
* Class that handle the async task
*/
public class MyAsyncClass extends AsyncTask<Void, Void, Object>
{
//Maintain attached activity for states change propose
private MyActivity activity;
//Keep the response of the async task
private Object _response;
//Flag that keep async task completed status
private boolean completed;
//Constructor
private MyAsyncClass(MyActivity activity) {
this.activity = activity;
}
//Pre execution actions
#Override
protected void onPreExecute() {
//Start the splash screen dialog
if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(activity.this,
"PLEASE WAIT",
"Getting results...",
false);
}
//Execution of the async task
protected Object doInBackground(Object...params)
{
//return the thing you want or do want you want
return new ArrayList();
}
//Post execution actions
#Override
protected void onPostExecute(Object response)
{
//Set task completed and notify the activity
completed = true;
_response = response;
notifyActivityTaskCompleted();
//Close the splash screen
if (pleaseWaitDialog != null)
{
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
}
//Notify activity of async task completion
private void notifyActivityTaskCompleted()
{
if ( null != activity ) {
activity.onTaskCompleted(_response);
}
}
//for maintain attached the async task to the activity in phone states changes
//Sets the current activity to the async task
public void setActivity(MyActivity activity)
{
this.activity = activity;
if ( completed ) {
notifyActivityTaskCompleted();
}
}
}
}
Hope its help you
First of all you cannot set the adapter in the doInBackground
follow this design:
private class LoadMoreVehicals extends AsyncTask<Object, Integer, Object>
{
private ArrayList<Country> countries;
#Override
protected void onPreExecute() {
progressBar = ProgressDialog.show(RegistrationScreen.this, "","Loading...");
progressBar.setIndeterminate(true);
progressBar.setIndeterminateDrawable(getResources().getDrawable(R.anim.progressbar_handler));
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
String countryUrl = ConstantURL.COUNTRY_URL;
countries = getCounty(countryUrl);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.getProgress();
}
#Override
protected void onPostExecute(Object result) {
countrySpinner.setAdapter(new MyCustomSpinnerAdapter(RegistrationScreen.this,R.layout.spinner_dropdown,countries));
progressBar.dismiss();
Log.e("Im in onPostExecute", "");
super.onPostExecute(result);
}
}