Progress Dialog not shown after exception - android

I am trying to do a file download using the below code. Everything works fine as far as the download is concerned. One problem I have is whenever there is a download failure, progress dialog does not show up. Am I missing anything obvious here? What is the cause for this?
Any help is much appreciated
public void onButtonClick(View view) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Downloading File");
mDialog.setCancelable(false);
mDialog.show();// Does not show during download exceptions- is it because the below download code fails abruptly?
new NTLMTestData ().asyncNTLMTest("http://myurl/FileName.csv", this, getApplicationContext());
}
// The below call backs get fired from async
#Override
public void onSuccess(String msg) {
mDialog.dismiss();
}
#Override
public void onFailure(Exception ex) {
mDialog.dismiss();
}

Try this way instead
public void onButtonClick(View view) {
try{
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Downloading File");
mDialog.setCancelable(false);
mDialog.show();
new NTLMTestData ().asyncNTLMTest("http://myurl/FileName.csv", this,
getApplicationContext());
} catch (Exception e){
showError();
}
}
private void showError(){
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setTitle("Error")
mDialog.setMessage("An error has occurred during download");
mDialog.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mDialog.dismiss();
}
})
mDialog.setCancelable(false);
mDialog.show();
}
// The below call backs get fired from async
#Override
public void onSuccess(String msg) {
mDialog.dismiss();
}
#Override
public void onFailure(Exception ex) {
//Leave blank
}
Hope it helps

Related

Unable to cancel Async task on button click

I am trying to cancel/end an async task on the button click of a pop-up box. However, when I click on the button the onCancelled() method is not being called. Could someone please help me with this? Below is my code:
public AuthenticationAsync(Context context, final String rid) {
this.rid = rid;
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Information");
alertDialog.setMessage("RaspberryPi Validated");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cancel(true); //Cancelling async task on button click
dialog.dismiss();
}
});
}
#Override
protected Object doInBackground(Object[] params) {
String metricData = String.valueOf(kuraPayload.getMetric("data"));
if (metricData.isEmpty())
subResponse = false;
}
#Override
protected void onCancelled() {
Log.d("Async","cancelled"); //not being called
}
#Override
protected void onPostExecute(Object o) {
if (subResponse) {
asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.get(WSConstants.ADD_RPI_WS + MQTTFactory.getRaspberryPiById(), new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(ActivityContexts.getMainActivityContext(), "RaspberryPi Validated", Toast.LENGTH_LONG).show();
alertDialog.show();
}
}
}
}
It looks like the it's never getting into onCancelled() because you are actually calling alertDialog.show() in onPostExecute(). Since doInBackground() has already completed, there is nothing to cancel.
The cancel() method is meant to be called during the execution of the doInBackground() method, which is the only method that runs on a background Thread.
Note that even if cancel() is called during execution of doInBackground(), the execution of the method won't be stopped immediately. You should do periodic checks to isCancelled() and if it returns true, then exit out of the method.
After doInBackground() has completed, if cancel() has been called, then onCancelled() will be called instead of onPostExecute().
Here is a very simple test based on your code:
public class AuthenticationAsync extends AsyncTask {
AlertDialog alertDialog;
String rid;
public AuthenticationAsync(Context context, final String rid) {
this.rid = rid;
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Information");
alertDialog.setMessage("RaspberryPi Validated");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cancel(true); //Cancelling async task on button click
dialog.dismiss();
}
});
}
#Override
protected void onPreExecute(){
//for testing, showing the dialog before the background Thread starts
alertDialog.show();
}
#Override
protected Object doInBackground(Object[] params) {
//cycle forever until the user clicks OK
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check if user clicked OK in the dialog
if (isCancelled()){
//Exit the method if the user dismissed the dialog
return null;
}
}
}
#Override
protected void onCancelled() {
Log.d("Async", "cancelled"); //this is called now
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
#Override
protected void onPostExecute(Object o) {
Toast.makeText(MainActivity.this, "postExecute", Toast.LENGTH_LONG).show();
}
}
Result:
Dialog is shown during execution of doInBackground():
After clicking OK, onCancelled() is called:
#yanchenko answered something similar there -> Ideal way to cancel an executing AsyncTask
You can use one ProgressDialog and set this dialog as Cancelable and set the CancelListener.

Set Progress Dialog properly in asynctask

I currently trying to show a progress dialog on OnclickListener of a Dialogbox since my items are taking too long to fetch from Server.
I use Async task as suggested here (Android progress dialog) and this post (android problem with progress dialog) to show progress dialog The progress dialog is shown , however the code returns exception when it goes to do background that " Looper is not set". And when I set looper nothing happens.
I am not sure at this stage what is it that I am doing wrong.
public void firstMethod()
{
final CustomObj obj = getCustomObj();//not imp
Messages.getInstance().showAlert(MainActivity.this, "message", false, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
gotoAnotherPge(obj);
}
});
}
public void gotoAnotherPge(final CustomObject obj)
{
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
new AsyncTask<Object, Object, Boolean>()
{
protected void onPreExecute()
{
pd.setMessage(String.format(Statics.getText(MainActivity.this, R.raw.dictionary, "subscriptions_loading_unsubscribing")));
pd.show();
}
protected Boolean doInBackground(Object... params)
{
try{
Looper.prepare();
final LocalPopulator lp = new LocalPopulator(MainActivity.this, 0)
{
#Override
public void populate()
{
List<Serializable> items = Arrays.asList(getItemHere(obj));
List<Serializable> listItems = new ArrayList<Serializable>();
listItems.addAll(items);
Serializable[] sItems = listItems.toArray(new Serializable[menuItems.size()]);
result = sItems;
}
};
showNextPage(true, 1, 0, lp);
Looper.loop();
}catch (Exception e){
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
return true;
}
protected void onPostExecute(Boolean result)
{
pd.dismiss();
}
};
MainActivity.this.runOnUiThread (new Runnable()
{
#Override
public void run()
{
// dismiss the progressdialog
pd.dismiss();
}
});
}

ProgresDialog doesn't show up

public Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ctx = this;
//another code......)
send = (Button)findViewById(R.id.wyslij_zapytanie_ofertowe);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ProgressDialog dialog = ProgressDialog.show(ctx, "Loading", "Please wait...", true);
try {
GMailSender sender = new GMailSender("dasdda#gmail.com", "ddx");
sender.sendMail("This is Subject",
"This is Body",
"staxxxowe#gmail.com",
"xxxyk#gmail.com");
dialog.dismiss();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
dialog.dismiss();
}
}
});
I try also instead ctx put ClassName.class and also doesn't work. Any one have idea how to solve this problem?
Most likely your problem is that you call dialog.dismiss(); "immediately" after you call dialog.show() and this may cause this "not showing" efect.
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Its probably getting dismissed even before it gets created since only a few lines later you call dialog.dismiss()

Android - How to make some validations in sequence

I need to do some validations sequentially and some of them involve complex database operations.
So, I need to do this in a separated thread of UI Thread, ok?
But some validations show messages to user, what need confirmation and
when user confirm, the next validation should be call.
This code example explains what I want to implement:
void makeValidation1(){
if(condition1Valid()){
makeValidation2();
}else{
DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
makeValidation2();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("really want to do this?")
.setPositiveButton("Yes", onClick);
builder.create().show();
}
}
void makeValidation2(){
if(condition2Valid()){
}else{
//...
}
}
boolean condition1Valid() {
// complex database Operations
return false;
}
boolean condition2Valid() {
//complex database Operations
return false;
}
//...
void makeValidation9(){
//...
}
My question is: What the best way/pattern to implement this?
1 - Create one asyncTask for each validation? (I cant create only one AsyncTask, because confirmation messages can stop flux).
2 - Create a Runnable for each validation and create thread to run that when need call next validation?
3 - ???
edit
I tested this code #BinaryBazooka, but isnt work. Any help?
public class MainActivity extends Activity implements OnClickListener {
Thread mThread;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
validations();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
mThread.run();
}
});
builder.create().show();
}
void validations(){
//this method go on separated thread
validation1();
validation2();
validation3();
}
void validation1(){
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
//wait for user confirmation
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
Log.i("TAG", "<<<<<<<<<< >>>>>>>>>>>>");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT);
}
});
}
}
I would create a new thread and sleep it during these dialog calls, you can access the UI directly from within your runnable with..
runOnUiThread(new Runnable() {
public void run() {}
});
So something like..
Thread someThread = new Thread(new Runnable() {
#Override
public void run(){
runOnUiThread(new Runnable() {
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.msg);
builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
someThread.notify();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
someThread.wait();
Works with AsyncTask. Ty.
Code:
public class MainActivity extends Activity implements OnClickListener {
//Thread mThread;
ProgressDialog mProgressDialog;
private ValidationsAsyncTask async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
async = new ValidationsAsyncTask();
async.execute();
}
});
builder.create().show();
}
void validation1(){
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
Log.i("TAG - validation1", Thread.currentThread().getName());
try {
synchronized (async) {
//wait for user confirmation
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (async) {
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
});
}
class ValidationsAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
validation1();
validation2();
validation3();
return null;
}
#Override
protected void onCancelled() {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
}
}

Async task to show an AlertDialog

For the past few days, I haven't been able to solve an issue with my dialog box. I am running a thread to show the dialog box for 5000ms and removing it. and I am trying to show a toast("SUCCESS"). The problem is I am getting the dialog box for the second time also. I am new to android development and I need to solve this with Async Task so that I can delay the second thread and show a alert dialog.builder with a positive button instead of toast. I goggled a lot but I confused to to implement this
Here I am sending my credentials to server and while sending I am showing a progress dialog box for 5000ms and I want to have a separate thread in order to show the dialog.builder with a positive button.( When the user get a response in the logcat for that I should check the responsecode==1 or not from the logcat to show the builder)
plz someone help me to solve this with some code snippet if possible.
Thanks in advance.
this is the code where I need to implement Async task
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// showDialog(0);
t = new Thread() {
public void run() {
register();
try {
while (counter < 2) {
showmsg(0);
Thread.sleep(5000);
removeDialog(0);
// Toast.makeText(Register.this, "Registerd", Toast.LENGTH_LONG).show();
showmsg(1);
// toast.show();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
++counter;
dialog = new ProgressDialog(this);
if (counter == 1) {
dialog.setMessage("Registering...");
}
else {
String resultsRequestSOAP = "";
if (Log.v("TAG", String.valueOf(resultsRequestSOAP)) == 1)
;
{
Context context = getApplicationContext();
CharSequence text = "Registerd";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
public void showmsg(int actionsToBePerformedOnScreen) {
Message msg = new Message();
msg.what = actionsToBePerformedOnScreen;
handler.sendMessage(msg);
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
showDialog(0);
break;
case 1:
// clear all images in the list
removeDialog(0);
break;
}
};
};
Easy: show dialog onPreExecute, register() in doInBackground and hide dialog in onPostExecute. Finally, do new RegisterTask().execute() in your onclick.
private class RegisterTask extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Signing in...");
this.dialog.show();
}
protected Boolean doInBackground(final Void unused) {
return Main.this.register(); //don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (result.booleanValue()) {
//also show register success dialog
}
}
}
Why you don't use Android AsyncTask?
For example:
public class MyPreloader extends AsyncTask<InputObject, Void, OutputObject>{
private Context context;
private ProgressDialog dialog;
public MyPreloader(Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
super.onPreExecute();
}
#Override
protected ResponseBase doInBackground(InputObject... params) {
InputObject input = params[0];
//some code for background work
}
#Override
protected void onPostExecute(OutputObject result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
super.onPostExecute(result);
}

Categories

Resources