Launching a long running task from an AlertDialog (Android) - android

I have an AlertDialog in and it's got a button, which, if selected, will initiate a file upload to a remote server like this:
builder.setMessage(text)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
uploadFile();
}})
This works fine, the only problem is that uploadFile() can potentially take a long time (30 seconds to 2 minutes). I would like to replace the AlertDialog with a progress dialog (even an indeterminate one), but I can't see how to launch one dialog from another?
Can anyone offer some advice for a how I could accomplish this.
Thanks,
Jarabek

You can use AsyncTask here, keep your ProgressDialog on the PreExecute() and call the method in the doingInBackground() and dismiss the ProgressDialog in the PostExecute().
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(ActivityName.this, "Loading...", "Data is Loading...");
}
#Override
protected Void doInBackground(Void... params) {
uploadFile();
return null;
}
}
Then just call the MyAsyncTask using new MyAsyncTask().execute();

The best way to do this - using AsyncTask. There you can provide progress and do your long action

Related

Progress dialog does not show exactly after show()?

Found that weird bahaviour of ProgressDialog.
I show ProgressDialog in onClickListener of list before starting new Thread and dismiss it inside that Thread but after all work is done:
GlobalProgressDialog.show(getActivity());
new Thread(new Runnable() {
#Override
public void run() {
//...all other logic
GlobalProgressDialog.dismiss();
}
}).start();
and that GlobalProgressDialog i use to simplify calls:
public class GlobalProgressDialog{
private static ProgressDialog progressDialog;
public static void show(Activity activity){
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
public static void dismiss(){
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
Dialog appears but NOT exactly after show() being called! I have debugged it and found out that there are 4 standard Android classes are being operated:
AdapterView.java
AbsListView.java
Handler.java
Looper.java
And only after Looper the ProgressDialog is being snown. Is it possible to trick this or fix? Or maybe there's some my fault in code? What could it be?
The problem is that delay between item click and show() is like 1 sec. So application freezes for 1 sec. And only then dialog appears and all work done takes 1-2 sec, sometimes even 0.5 sec. In such cases its not cool to look at frozen app and flashed for 0.5 sec progress dialog.
Thanks in advance.
You're doing too much work on the main thread. show() will show the dialog, but it will do so on the main thread. It does not block execution until it is dismissed. So something you're doing in your code after calling show() and which you are not showing us, is causing the delay in the appearance of the dialog.
Just to be clear again, this has nothing to do with the Thread you're starting and changing it to an AsyncTask won't fix it, although it might be a good idea to do that anyway if the pattern fits your use case.
You should use a AsyncTask here.
public class DialogAsync extends AsyncTask<Void, Void, Void> {
private Context context;
private ProgressDialog progressDialog;
public DialogAsync(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Perform your logic here
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
Usage:
DialogAsync globalProgessDialog = new DialogAsync(getActivity());
globalProgessDialog.execute();

Progress bar dialog while method are not finished

I need to show simple progress bar dialog while some method not finish.
I Try to call it like
ProgressDialog progressDialog = ProgressDialog.show(Activity.this, "", "Please wait");
SyncCity()
SyncStreet()
progressDialog.dismiss();
But than app is blocked while method not finish,after that i get progress dialog,and in next second dissapear, sometimes i not See it at all.
All calling is going on button click...
Where is catch?
Thank You.
That's because you're blocking the UI thread. Try using AsyncTask, like this:
ProgressDialog progressDialog;
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Activity.this, "", "Please wait");
}
#Override
protected Void doInBackground(Void... params) {
SyncCity()
SyncStreet()
return null;
}
#Override
protected void onPostExecute(Void args) {
progressDialog.dismiss();
}
}.execute();
You should use an AsyncTask to do such processes. You shouldn't do any process in the UI thread.
Here is a good example on how to use AsyncTask:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

Android Progress Bar appear and hide

I have a progress bar and I do not want to incorporate a numerical value to show the loading of some content. I just want that the ProgressBar should appear, animate and then go away.
I used:
public void buttonClick(View v){
ProgressBar mProgress=(ProgressBar)findViewById(R.id.my_progress);
mProgress.setVisibility(VISIBLE); //line 1..
//loading data from web... takes time
mProgress.setVisibility(INVISIBLE); //line 2..
}
but when I run this code, both line 1 and line 2 executes, but the UI changes afterwards, which is not desired. I want that when the button is clicked, the progress bar should appear and when the data is downloaded from the web the progress bar should disappear.
I tried setting the visibility from another thread, but it didn't work as UI changes are not allowed in other threads.
You download your data in AsyncTask right? Put this code
private class DownloadData extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// download your data here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mProgress.setVisibility(View.GONE);
}
}
The best way implement it by using an AsyncTask
MyTask.java
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
Context context;
MyTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
dialog=new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//do your task here
}
#Override
protected void onPostExecute(Void result) {
if(dialog.isShowing()){
dialog.dismiss();
}
}
}
You can start the task like this:
public void buttonClick(View v){
new MyTask(YourActivity.this).execute();
}
You can modify the AsyncTask accordingly to retrieve the result.
Hope it helps. :)

ProgressDialog show too much late with Asynch task in Android

I am new in android. I am trying to display ProgressDialog when click on button .
This is my code:
// set listener
btn_Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//progress.show();
MyAsynch asynch = new MyAsynch();
asynch.execute();
}
In this code progress dialog too much late appear when i am comment on Asynctask object then progress dialog appear normally.
I am puting my progress dialog in
AsynchTask method
onPreExecute() but same out put dialog display late .
How to solve my problem..??
I am also read stack answers following link but not solve my problem .
async task progress dialog show too late
ProgressDialog appears too late and dissapears too fast
here is my Asynctask code
private class MyAsynch extends AsyncTask<String, Void, String> {
ProgressDialog progress;
String login_stat;
String stat;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(this);
progress.setTitle(" User Login ");
progress.setMessage("Please Wait!!");
progress.setCancelable(false);
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected String doInBackground(String... urls) {
try {
login_stat = s_ApiHandling.doLogin(m_Et_Username.getText()
.toString().trim(), m_Et_Password.getText()
.toString().trim());
} catch (Exception e) {
System.out.println("internet connection loss ");
stat = "ERORR";
e.printStackTrace();
}
return stat;
}
#Override
protected void onPostExecute(String status) {
progress.dismiss();
}
}
You are probably doing too much in onPreExecute
Remove progress.cancel() from your doInBackground method and put it in to a onPostExecute method in your AsyncTask (like the second link you posted)
You shouldn't have anything talking to the UI in a background thread - that should all be done in pre/post execution.
you code should look like this:
AsyncTask<String, Void, String>()
{
private ProgressDialog progressDialog = ProgressDialog.show(this, "", "Loading...");
#Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
#Override
protected String[] doInBackground(String... params)
{
//ALL CODE GOES HERE.
}
}
When you call the asynctask you must not use the get() method or the progress dialog won't work correctly.

Android: Progress dialog not shown at 1st time (using Thread or AsyncTask for longDuration operation)

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

Categories

Resources