Android AsyncTask GUI Stuck - android

I send an email programmatically in my Android app. To do that I use an Asynctask like this:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
//testMailButton.setEnabled(false);
processdialog = ProgressDialog.show(context, "Test mail sturen", "wachten a.u.b...");
processdialog.setCancelable(false);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
properties.setProperty("emailTo", emailContactField.getText().toString());
properties.setProperty("emailFrom", emailField.getText().toString());
properties.setProperty("passWFrom", passwordField.getText().toString());
String[] temp = { properties.getProperty("emailTo").toString()};
setupMail.updateUserInfo(temp,properties.getProperty("emailFrom"), properties.getProperty("passWFrom"));
loggedIn = setupMail.sendTestMail();
loginTryDone = true;
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (processdialog != null) {
processdialog.dismiss();
testMailButton.setEnabled(true);
}
}
};
But the processDialog is never showing, until the last moment, I also tried starting it before starting the task, but that didn't work either. I am not sure why it isn't working. Can anyone help me?
Thanks

I think you want to make the ProgressDialog indeterminate (loading amount not measured, because you don't know what the progress is). You can use this constructor:
public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable)
Which in your case will look like:
processdialog = ProgressDialog.show(context,
"Test mail sturen",
"wachten a.u.b...",
true, false);

Related

How te set the time for progress dialog

I have a big process called that will be called when I execute http-request and move to other activity or fragment,
The problem is, the process isn't finished yes then the display going to be blank and after that it move to another activity.
Question is, how we can set the timer and the timeout and where I can put the line code.
This is my current code
public class BigProccess extends AsyncTask<Void, Integer, Void> {
private Context mContext;
ProgressDialog mProgress;
private int mProgressDialog=0;
public BigProccess(Context context, int progressDialog){
this.mContext = context;
this.mProgressDialog = progressDialog;
}
#Override
public void onPreExecute() {
mProgress = new ProgressDialog(mContext);
mProgress.setMessage("Loading...");
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setIndeterminate(false);
mProgress.setMax(100);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setCancelable(false);
// }
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setProgress(values[0]);
// }
}
#Override
protected Void doInBackground(Void... values) {
try {
//This is to simulate there is a heavy process is running
//and we make it slow down by 500 ms for each number
for (int i =1; i<=10;i++){
publishProgress(i*10);
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgress.dismiss();
// Toast.makeText(mContext,"Done!!!",Toast.LENGTH_LONG).show();
}
}
I've tried modified the thread.Sleep to 15000ms but it won't work.
Any help would be appreciated.

progress bar is not showing

I am trying to use progress bar while updating my database. Good thing, i can successfully update my database but my progress bar is not showing. I am using a progress bar the will show also the percentage on my update. I don't know what wrong with my code below, help me figure it out please:
public class SyncBrand extends AsyncTask<String, Void, Boolean>
{
public static final int BRAND_DIALOG_DOWNLOAD_PROGRESS = 0;
public SyncBrand(Context context, String _username, String _password, String _code,String _remarks,String _date,String _province,String _infotype,
String _competitor,ArrayList<String> _brands, ArrayList<String> _segments)
{
....
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case BRAND_DIALOG_DOWNLOAD_PROGRESS:
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Updating Sub Brands..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
return progressDialog;
default:
return null;
}
}
#SuppressWarnings("deprecation")
protected void onPreExecute()
{
super.onPreExecute();
((Activity) mContext).showDialog(BRAND_DIALOG_DOWNLOAD_PROGRESS);
}
protected Boolean doInBackground(String... arg0)
{
try{
....
}catch (Exception e){
Log.e("Update SubBrand", "Error:", e);
exception = e;
return false;
}
....
return true;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
protected void onPostExecute(Boolean valid)
{
((Activity) mContext).removeDialog(BRAND_DIALOG_DOWNLOAD_PROGRESS);
if(valid){
.....
}else{
Toast.makeText(mContext, "Failed to update.Please try again.", Toast.LENGTH_SHORT).show();
mContext.startActivity(new Intent(mContext, S_2nd_Main.class));
}
}
}
A couple problems I see here. You have Void for the second argument in your AsyncTask
public class SyncBrand extends AsyncTask<String, Void, Boolean>
which means that onProgressUpdate() should expect that type of data passed to it but you have protected void onProgressUpdate(String... progress) { which tells that method to take a String parameter. Also, you don't call publishProgress() from doInBackground() which is what is used to call onProgressUpdate().
Change your AsyncTask to
public class SyncBrand extends AsyncTask<String, String, Boolean>
and add publishProgress() to doInBackground() and pass the String value you want it to update the ProgressDialog to.

Progress dialog not dismissing in async task

The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.

Android AsyncTask onPreExecute not called indeterminantly

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>

ProgressDialog not shown in AsyncTask

I have a huge database (40MB) on an SDCard. I need fetch data, with LIKE in query, which is very slow.
DB request takes about 5 seconds. Therefore, I need to do it asynchronously and with ProgressDialog.
I tried it with AsyncTask, but problem is with ProgressDialog. It was implemented this way:
private class GetDataFromLangDB extends AsyncTask<String, String, String> {
private final ProgressDialog dialog = new ProgressDialog(TranslAndActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
urDBCursor.close();
curDBCursor = null;
scaAdapter = null;
this.dialog.setMessage("Loading data...");
this.dialog.show();
}
#Override
protected String doInBackground(String... whatSearch) {
String result = "";
if (myDatabaseAdapter != null) {
curDBCursor = myDatabaseAdapter.fetchAll(whatSearch[0]);
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
prepareListView();
}
}
The problem is that ProgressDialog is not shown during the DB request.
After finished database query, it flash on screen for a short time. When user tries
to tap on screen during database request, UI is freezed, and after DB request
message about 'not responding' is shown.
I tried it with a thread this way:
public void startProgress(View view, final String aWhatSearch) {
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
if (curDBCursor != null){
curDBCursor.close();
curDBCursor = null;
}
dialog.setMessage("Loading data...");
dialog.show();
Runnable runnable = new Runnable() {
public void run() {
curDBCursor = myDatabaseAdapter.fetchAll(aWhatSearch);
// dirty trick
try {
Thread.sleep(250); // it must be here to show progress
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
}
prepareListView();
}
});
}
};
new Thread(runnable).start();
}
The result was the same, but when I used the trick with Thread.sleep(250);
ProgressDialog was shown during the database request. But it is not spinning,
it looks freezed during the DB request.
DB stuff is called this way (after tap on search button):
btnSearchAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// AsyncTask
new GetDataFromLangDB().execute(edtTextToSearch.getText().toString());
// or Thread
//startProgress(null, edtTextToSearch.getText().toString());
}
});
I found a lot of problems like this in SO, but nothing was useful for me.
Could it be that DB is on SD Card?
I put the definition of the dialog into the AsyncTask Class and it works fine for me.
Take a look at this exampel (You have to change NAMEOFCLASS in the name of your CLASS:
private class doInBackground extends AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(NAMEOFCLASS.this) {
#Override
protected void onPreExecute() {
dialog.setCancelable(false);
dialog.setTitle(getString(R.string.daten_wait_titel));
dialog.setIcon(R.drawable.icon);
dialog.setMessage(getString(R.string.dse_dialog_speichern));
dialog.show();
}
#Override
protected void onCancelled() {
dialog.cancel();
}
....
#Override
protected void onProgressUpdate(Integer... values) {
// DO YOUR UPDATE HERE
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
Maybe this SO answer could help you. It looks like similar problem. Try to use AsyncQueryHandler for querying your database
declare you Dialog box on Class (Activity) level like this
private ProgressDialog dialog = null;
show the progress dialog and call the AsyncTask class when you want to start you Busy work..like onButton click or any
dialog = ProgressDialog.show(this,"Sending Email to your account please! wait...", true);
SendingEmailTask task = new SendingEmailTask();
String s = "";
task.execute(s);
create your inner class like
private class SendingEmailTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
//do your work here..
// like fetching the Data from DB or any
return null;
}
#Override
protected void onPostExecute(String str) {
//hide progress dialog here
dialog.dismiss();
}
}
let me know if this help!!

Categories

Resources