ProgressDialog not showing/only showing after asyncTask - android

i'm trying to add a indeterminate progressDialog to my UI once i click a list element that calls a AsyncTask, but unfortunately, if I call the dialog on the onPreExecute like this:
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setProgressStyle(R.style.AppTheme_Dark_Dialog);
dialog.setIndeterminate(true);
dialog.setMessage(activity.getString(R.string.Buscando));
dialog.show();
}
Obs: Worth noting that the Async is not a subClass of the Activity Class, i'm passing the activity as a parameter to the constructor.
and
#Override
protected void onPostExecute(BuscaPendentesFechamento buscaPendentesFechamento) {
super.onPostExecute(buscaPendentesFechamento);
if(dialog.isShowing())
dialog.dismiss();
}
the dialog simply doesn't show at all, although it is created and called(alredy checked, the activity instance is correct)
and if I set the dialog on the activity itself, like:
final ProgressDialog progressDialog = new ProgressDialog(RegistraPeso.this, R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage(getString(R.string.Buscando));
progressDialog.show();
BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
response = exportProjectRequisition.execute(nomeEquip,RegistraPeso.this);
progressDialog.dismiss();
the Dialog shows on the Ui, but only after the AsyncTask alredy performed, and not before it is called, and according to the code, it should be showing before the Async even gets created.
What can I do? What am I doing wrong? Please help.
Edit: Added where the Dialog is created:
private ProgressDialog dialog;
private RegistraPeso activity;
BuscaPendentesFechamento(RegistraPeso activity) {
this.dialog = new ProgressDialog(activity);
this.activity = activity;
}
Edit: Added the doInBackground:
#Override
protected BuscaPendentesFechamento doInBackground(String... params) {
ArrayList<UmData> jsonArrayResponse = JSONParser.makeHttpRequestArray(
Constants.URL_PENDENTES_FECHAMENTO,
Constants.METHOD_POST, requisition.writeJSON(params[0]),
requisition.getContext());
if(jsonArrayResponse!=null)
requisition.setJsonArrayResponse(jsonArrayResponse);
else {
UmData umData = new UmData();
umData.setItemUm("Server not responding");
jsonArrayResponse = new ArrayList<>();
jsonArrayResponse.add(umData);
requisition.setJsonArrayResponse(jsonArrayResponse);
}
return requisition;
}

Application context would not work in this case . Replace line below
BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(getApplicationContext());
To
BuscaPendentesFechamento exportProjectRequisition = new BuscaPendentesFechamento(YourActivity.this);
I see your code you are calling dismiss() just after execute(). Remove this line.
progressDialog.dismiss();

OP here, the problem was solved by changing the code based on [this][1]
[1]: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? post here, sent to me by #MikeM, The problem was that I was getting the response using the .get() from the AsyncTask, and it was transforming the Async into a Syncronous Task.
Thanks for the support Mike!

Related

Show ProgressDialog when loading heavy UI

I use asynctask quite often however this time it doesn't work!
I have a UI contains a viewpager and fragments. To populate the view, it takes about 3 secs. Now I want to show the ProgressDialog until it finishes by using AsyncTask. But the ProgressDialog is not showing!!!!
Anybody can tell me the solution? Thanks
onCreate(...){
setContentView(...)
new LoadUI(MyActivity.this).execute();
}
public class LoadUI extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
Context context;
public LoadUI(Context mContext) {
this.context = mContext;
pd = new ProgressDialog(mContext);
aViewPager = (ViewPager) findViewById(R.id.aPagerDay);
}
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
//Create ViewPager
//Create pagerAdapter
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd.isShowing()) {
pd.dismiss();
}
super.onPostExecute(result);
}
}
You can try out two options:
Either use the AsyncTask's method get(long timeout, TimeUnit unit) like that:
task.get(1000, TimeUnit.MILLISECONDS);
This will make your main thread wait for the result of the AsyncTask at most 1000 milliseconds.
Alternatively you can show a progress dialog in the async task until it finishes. See this thread. Basically a progress dialog is shown while the async task runs and is hidden when it finishes.
You have even third option:" if Thread is sufficient for your needs you can just use its join method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
The problem is the GUI is not ready in onCreate(). And nothing will be shown if I try to show Dialog in this state. A solution is move the dialog to activity onStart():
#override
onStart(){
new LoadUI(MyActivity.this).execute();
}

How to show ProgressDialog while loading UI items?

I have a listview and I'm loading dynamically items into it.
The problem is when I'm activating that activity. It takes too long, so I have to show some progress dialog while loading the UI.
I really don't know how to do it, since doInBackground (If using Async task) doesn't allow the developer to mess with the UI.
What should I do ?
Here is my UI load code :
LeagueTableRow leagueTableRow_data[] = new LeagueTableRow[]
{
new LeagueTableRow(1,R.drawable.logo,"aaa",12,9,3,14),
new LeagueTableRow(3,R.drawable.logo,"aaa",12,9,3,14),
new LeagueTableRow(4,R.drawable.logo,"aaa",12,9,3,14),
new LeagueTableRow(5,R.drawable.logo,"aaa",12,9,3,14),
new LeagueTableRow(2,R.drawable.logo,"aaa",12,9,3,14)
};
LeagueTableRowAdapter adapter = new LeagueTableRowAdapter(context,
R.layout.leaguetablecontent, leagueTableRow_data);
listViewLeagueTable = (ListView)findViewById(R.id.listViewLeagueTable);
View header = (View)getLayoutInflater().inflate(R.layout.leaguetableheader, null);
listViewLeagueTable.addHeaderView(header);
listViewLeagueTable.setAdapter(adapter);
That can be achieved with the help of AsyncTask (an intelligent backround thread) and ProgressDialog
A ProgressDialog with indeterminate state would be raised when the AsyncTask starts, and the dialog is would be dismissed once the task is finished .
Example code
What the adapter does in this example is not important, more important to understand that you need to use AsyncTask to display a dialog for the progress.
private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected ContactsListCursorAdapter doInBackground(Void... params) {
cur1 = objItem.getContacts();
startManagingCursor(cur1);
adapter1 = new ContactsListCursorAdapter (viewContacts.this,
R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});
return adapter1;
}
protected void onPostExecute(ContactsListCursorAdapter result) {
list.setAdapter(result);
dialog.dismiss();
}
}
If you set the emptyview using listView.setEmptyView . The view will show in the place of list until you do a setadapter on the list. So As soon as you do setAdapter the emptyview will disappear. You can pass Progressbar to the setEmptyview in your case to show the progressbar.
Edit:
Use Setadapter in OnPostExecute of the Asynctask.
OnPostExecute, OnPreExecute, OnProgressUpdate, OnCancelled all run on UI thread. If you still insist on ProgressDialog, then create dialog in OnPreExecute and dismiss it in OnpostExecute and OnCancelled of the Asynctask
Please use AsyncTask if loading of list is taking too much time.Place a progress bar on the top of list view use that in AsyncTask.Hope this will help you

Android: Fill a Spinner with progress dialog

I have a button, and when I clicked on it, I load other Activity, onCreate of this I call a method that fills a spinner with data from a Web Service.
Well, When I click at this button the screen stay "frozen" and then shows the Activity. So, I thought that it could be a good thing shows a progress dialog for user, and after gets the return of the Web Service, ends the progress dialog.
I tried use Handler, and now I'm trying to use AsyncTask, but, geting NullPointerException, because my program is filling spinner before web service get called.
private void fillSpinner(){
//runWebService();
new CallWebServiceAsyncTask().execute(null);
mAdapter = new PlanesAdapter(this, allPlanes);
mList.setAdapter(mAdapter);
}
class CallWebServiceAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(PlanesActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... v) {
runWebService();
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
because my program is filling spinner before web service get called.
you should fill data after getting data in onPostExecute Method
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
mAdapter = new PlanesAdapter(this, allPlanes);
mList.setAdapter(mAdapter);
}
What #SamirMangroliya suggested is correct but you even need to know where you are going wrong. When you call an AsyncTask you are asking the application to do some actions in the background which will take place in the non-UI thread. Now when you call execute() on your AsyncTask object the application code written in the function doInBackground(Void... v) runs in background and your control returns to the next statement following the call to execute() [new CallWebServiceAsyncTask().execute(null)], which in your case is the action of filling the adapter values. These values are yet to be received from the webservice. The only place where you can be sure that your background action is completed is the function onPostExecute(Void result) where as suggested you can create your adapter.

ProgressDialog in AsyncTask not updating or dismissing

I am using an AsyncTask to handle complex background operations (compiling a log file to send) and I use a ProgressDialog to show the user progress. I have tried using showDialog() but it never seems to show or dismiss (it is never called), and I followed tutorials on how to do it...
So I am using unmanaged ones, and it won't dismiss my message. I am also wanting to update the message as it starts to compile the log file (as it seems to lag there - or maybe the text view is just really long so it doesn't update like it is supposed to).
I have moved my code around a bit so it look like there are problems (like onProgressUpdate()), but I don't know how to make it work. I have looked around this site and nothing seems to be having the problem I am (not exactly anyways). RunOnUiThread() doesn't work, new Thread(){} doesn't work, and onProgressUpdate() I can't get to work (the documentation is confusing on this).
It also never dismisses. I have set up a listener and it never dismisses.
Does anyone know what is wrong with my code? I thought AsyncTask was supposed to be simple.
private class BuildLogTask extends AsyncTask<Void, Void, String> {
String temp;
ProgressDialog progressdialog = new ProgressDialog(context); //variable is defined at onCreate (held as private, not static)
#Override
protected String doInBackground(Void... params) {
temp = buildLog();
logdata = temp;
publishProgress();
createLogFile();
return temp;
}
protected void onProgressUpdate() {
progressdialog.setMessage("Compiling Log File...");
}
#Override
protected void onPreExecute() {
Log.w(TAG,"Showing Dialog");
send.setEnabled(false);
ProgressDialog progressdialog = new ProgressDialog(context);
progressdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressdialog.setMessage("Gathering Data...");
progressdialog.setCancelable(false);
progressdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.e(TAG,"Progress Dialog dismissal.");
}
});
progressdialog.show();
}
#Override
protected void onCancelled(){
Log.e(TAG,"Progress Dialog was Cancelled");
progressdialog.dismiss();
logdata=null;
}
#Override
protected void onPostExecute(String result) {
progressdialog.dismiss();
send.setEnabled(true);
previewAndSend();
}
}
You have two different progress dialogs there, one local to onPreExecute() and one global. The one ur dismissing in your onPostExecution() is your global one which was never actually shown. Remove the local declaration and it should work.
There are two problems.
The signature for on onProgressUpdate is not correct. Try this instead:
#Override
protected void onProgressUpdate(Void... progress) {
progressdialog.setMessage("Compiling Log File...");
}
You're masking the progressDialog member variable with a local variable in onPreExecute()
EDIT: Second problem identified:
Try it,
Replace:
progressdialog.show();
For:
progressdialog = progressdialog.show();
Good luck.

Android: Progress Dialog Doesn't Show

I have some data I load into the database the first time a user enters my Activity, and want to show a ProgressDialog while this data is loaded for the first time. My Activity is an ExpandableListActivity and I don't create the SimpleExpandableListAdapter or call setListAdapter passing my adapter until I'm sure the data is actually there. My onCreate looks like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategoryDbHelper = new CategoryDBHelper(this);
// Build default categories... if not there yet
CategoryDbBuilder builder = new CategoryDbBuilder(this);
if (!builder.hasCategoriesInTable()) {
showDialog(PROGRESS_DIALOG_ID);
builder.fillDbWithDefaultCategories();
removeDialog(PROGRESS_DIALOG_ID);
}
populate();
}
I've overwritten onCreateDialog as such:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG_ID: {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading categories for the first time. Please wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
return dialog;
}
}
return null;
}
The populate() method reads the database and sets up my list adapter, then calls setListAdapter.
This seems like it should be simple, but it's turning out to be a huge pain. Any help would be appreciated. :-)
Use AsynTask put your database loading processing in background function and in post execution display result. and there is another function to processing something until background process running here is example of asynTask
Android - I want to show file upload progress to the user
Just use this simple line:
mProgressDialog = ProgressDialog.show(context, "", "msg to show", true);
You can dismiss it with:
mProgressDialog.dismiss();

Categories

Resources