Android AsyncTask onPreExecute not called indeterminantly - android

I have an AsyncTask that is supposed to show a progress bar while it uploads some stuff via Internet. Sometimes it works like a charm and sometimes it does not show any progress bar. Here is the code:
public class Upload extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(Activity.this);
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity.this, "wait...", "", true, true);
}
#Override
protected Void doInBackground(Void... params) {
//upload stuff
return null;
}
protected void onPostExecute(Void result) {
try {
if (dialog.isShowing())
dialog.dismiss();
dialog = null;
} catch (Exception e) {
// nothing
}
Intent next = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(next);
}
}
}
The doInBackground and onPostExecute work always, and sometimes altogether it works like a charm. But sometimes, there is no progress bar while it is uploading. Is this a race condition? I do not think so, but I cannot find any explanation.

You're creating the object twice in the class. The ProgressDialog.show already returns a created ProgressDialog object, but you have instantiated it first at the top. The ProgressDialog should be instantiated once, so try removing the instantiation at the top and try again, like so:
private ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity.this, "wait...", "", true, true);
}

Maybe it is because void parameter that causes that problem. Just try to use Integer as your parameters.:
public class Upload extends AsyncTask<Integer, Integer, Integer>

Related

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.

UI delayed showing with asynctask

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();
}

Display "Loading : Progress Bar " in Android Intent till Data Load

I am working on an android app, in that app i have intent2 which on click redirects to intent3 and takes some time then loads a table and displays server data into it.
Sometimes if there is a lot of data, it tales pretty much time to get the dataload and the time blank screen is displayed increases.
i wish to show a loading bar till the data loads.
how can i show the ProgrssBar till only when data is not displayed ?
Probably your best bet would be to use AsyncTask in your "intent3":
You could do it like this:
private class performBackgroundTask extends AsyncTask <Void, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(ClassName.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected void onPostExecute(Void unused)
{
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
#Override
protected Void doInBackground(Void... params)
{
// Do your background data fetching here
return null;
}
}
You probably need to run an AsyncTask on onCreate when you open the new activity, the structure of the asynctask would be like this (taken from the google doc), notice that if you want to increament a progress bar you have to implement onProgressUpdate and call publishProgress in the doInBackground method
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute()
{
// show your progress bar
}
protected Void doInBackground(Void... params) {
// do your work and publish the progress
publishProgress(progress);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Void result) {
//dismiss your progress bar
}
}
This code is just an example, of course you need to adapt it to your logic/code.
Check out this simple and complete example

How can I dismiss ProgressDialog in AsyncTask

I am using a ProgressDialog to be shown while my background process goes on, but after background process is completed the ProgressDialog is not dismissed still.
Here is my code
private class async extends AsyncTask<String, Void, Boolean> {
final ProgressDialog progressDialog = new ProgressDialog(getParent());
#Override
protected Boolean doInBackground(String... params) {
GetJson json = new GetJson();
boolean success = false;
JSONObject mJsonObject = json
.readJsonObject("url");
try {
success = mJsonObject.getBoolean("success");
} catch (Exception e) {
}
return success;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
}
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
progressDialog.show(getParent(), "Working..", "Please wait...");
}
}
private final class YourTask extends AsyncTask<Void, Void, Object> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(YourActivity.this, "Title", "Message", true);
}
#Override
protected Object doInBackground(final Void... params) {
// Doing something
}
#Override
protected void onPostExecute(final Object result) {
// Check result or something
dialog.dismiss();
}
}
You can call progressDialog.dismiss() in your AsyncTask's onPostExecute() method.
In onPostExecute() method call dismiss() on your dialog.
I dont know, if you solved this problem, probably yes.
But for next users what will have the same problem (i had it right now too)..
The problem is in your declaration.
final ProgressDialog progressDialog = new ProgressDialog(getParent());
or in your "second" declaration
progressDialog.show(getParent(), "Working..", "Please wait...");
Because in the first one you put in there the getParent parameter (probably MainActivity.this)
and the same you do in calling show method.
Therefore is there 2 parents.. and if you call dismiss() in post execute..it dismiss the first one..but not the another one what have then dialog.isShowing() equal to false.
So important is have there just 1!!!!! parent content..so you can assign the content in declaration with:
new ProgressDialog(content);
or you can do
ProgressDialog dialog=new ProgressDialog();
dialog.setMessage("Loading");
dialog.show(getParent());
and then dismiss it and everything is allright.
or you can do:
ProgressDialog dialog=new ProgressDialog(getParent());
dialog.setMessage("Loading");
dialog.show();
but never give in there twice parents, contents, whatever..
AsyncTasks should not handle at ALL a dialog. Dismissing the dialog in the PostExecute phase can easily lead to an IllegalStateException as the underlying activity can already be destroyed when the dialog gets dismissed. Before destroying the activity the state of the activity will be saved. Dismissing the dialog afterwards will lead to an inconsistent state.

Displaying a progress dialog when upgrading database

The next version of my app needs to upgrade the database and this takes quite a bit of time. I'd like to show a progressDialog to update the user on the progress. Problem is, I can't quite figure out how and where to create the dialog.
My basic setup is that I have an activity which is essentially a splashscreen. It's on this screen I would like to show the progress. I have a separate DbAdapter.java file where a DatabaseHelper class extends SQLiteOpenHelper, where I override onUpgrade (the upgrade part is working fine).
I've tried a few different places to implement the progress dialog, but I don't seem to find the right spot. I tried passing context from my splashscreen activity to onUpgrade, but when onUpgrade runs it seems to be getting the context from my ContentProvider instead.
Does anyone have a good example of how to display a progress dialog when upgrading a database?
You need to implement an AsyncTask. Example:
class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
//show your dialog here
progressDialog = ProgressDialog.show(this, "title", "message", true, false)
}
#Override
protected Void doInBackground(Void... params) {
//update your DB - it will run in a different thread
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide your dialog here
progressDialog.dismiss();
}
}
Then you just have to call
new YourAsyncTask().execute();
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
ProgressDialog myProgressDialog = null;
public void DownloadFiles() {
myProgressDialog = ProgressDialog.show(this, "Please wait !",
"Updating...", true);
new Thread() {
public void run() {
try {
//Your upgrade method !
YourUpdateFunction();
} catch (Exception e) {
Log.v(TAG, "Error");
}
myProgressDialog.dismiss();
}
}.start();
}

Categories

Resources