Unable to dismiss progress dialog - android

Here is my code segment I am trying to dismiss dialog but it is not getting dismissed and also i don't get any error on logcat.Please correct me where i am wrong ?
All the Log.v statement get executed.Even log.v statement after pd.dismiss() (Log.v("TAG","progress dismiss");) gets printed.
Please point my mistake or suggest some alternative way to dismiss the progressdialog.
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//do something
} else {
Log.v("TAG","above progressDialog");
final ProgressDialog pd = new ProgressDialog(ChangePassword.this);
ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);
new Thread() {
public void run() {
try {
sleep(2000);
Log.v("TAG","in try block");
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
pd.dismiss();
// Log.v("TAG","progress dismiss");
}
}.start();
Log.v("TAG","after start");
public void run()
{
try{
if (!(txtOldPass.getText().toString())
.equals(SetGetValues.getPassword())) {
Toast.makeText(ChangePassword.this,
"Invalid Old Password", Toast.LENGTH_SHORT)
.show();
txtOldPass.setText("");
txtNewPass.setText("");
txtCnfPass.setText("");
} else {
if (!(txtNewPass.getText().toString())
.equals(txtCnfPass.getText().toString())) {
Toast.makeText(ChangePassword.this,
"Re-Enter New Password",
Toast.LENGTH_SHORT).show();
txtOldPass.setText("");
txtNewPass.setText("");
txtCnfPass.setText("");
} else {
try {
handler = new Handler();
handler.postDelayed(new Thread (new Runnable(){
JSONStringer loginuser = new JSONStringer()
.object()
.key("userid")
.value(SetGetValues.getUserid()
.trim())
.key("password")
.value(txtCnfPass.getText()
.toString().trim())
.key("oldpassword")
.value(txtOldPass.getText()
.toString().trim())
.endObject();
StringEntity entity = new StringEntity(
loginuser.toString());
JSONObject results = bc
.returnJSONObject(loginuser,
"url");
String message = results
.getString("message");
String isvalid = results
.getString("isvalid");
if (isvalid.contains("FALSE")) {
} else {
//pd.dismiss();
Toast.makeText(
ChangePassword.this,
"Password changed successfully",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
//TODO: handle exception
e.printStackTrace();
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}), 1000);
}
}
});

You are not dismissing the same ProgressDialog that you are showing. Replace this:
final ProgressDialog pd = new ProgressDialog(ChangePassword.this);
ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);
with this:
final ProgressDialog pd = ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);

if (pd.isShowing()) {
pd.dismiss();
}
Instead of using thread Use Async Task
usage

You problem probably is, that you're trying to modify the UI (dismiss the dialog) from another thread. I'm surprised that you don't get an error message. Try dismissing the dialog from the UI thread, for example by using .runOnUIThread().

Because you are trying to use element of UI Thread progressDialog in a non UI thread .
This will be allowed through AsyncTask , handler or RunOnUIThread(runnable) only .
read more about them and use any one .

Related

Setting text on ProgressDialog crashes app

I'm learning android and I don't know why this code doesn't work. Can you tell me why it doesn't work and take me correct code?
final ProgressDialog dialog = ProgressDialog.show(LoginScreen.this, "", "Loading. Please wait...", true);
Thread loggingStatus = new Thread() {
public void run() {
try
{
sleep(2000);
dialog.setMessage("Logging in. Please wait.");
sleep(2000);
dialog.dismiss();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
loggingStatus.start();
You have to move the portion of the background task that updates the ui onto the main thread. There is a simple piece of code for this:
putting runOnUiThread( new Runnable(){ .. inside run():
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread loggingStatus = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
sleep(2000);
dialog.setMessage("Logging in. Please wait.");
sleep(2000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
};
loggingStatus.start();
You should not set the Text of ProgressDialog in background thread . All UI updation should be done only on UI thread(Main thread)
Either use AsyncTask or Handler for this logic or functionality

Progress dialog is not showing while calling a web service

I am new to android. I want to show progress dialog when user click on login button. I tried this but the dialog is not showing
btn_logIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
getUserCredentials();
}
}); //end of anonymous class
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(this);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
}
}); //end of anonymous class
dialog.show();
} //end of showProgressDialog()
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
callWebService(userName, password);
}
} //end of getUserCredentials()
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SocketTimeoutException e) {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
} //end of callWebServide()
Am i doing anything wrong. When i click on login button and service is not running then it shows message that Service is not connected, Please make sure your server is running", but the dialog isn't showing...Why? My logic is when user click on login button and fields have values then start showing progress dialog and if anything happens like when result come or server is not running or if any exception happen , then i remove the dialog and show the appropriate message, but dialog isn't showing...Why? What i am doing wrong? Please help..
Thanks
Try this,
Change your getUserCredentials() like this,
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
Thread t=new Thread(new Runnable() {
public void run() {
callWebService(userName, password);
}
}); t.start();
}
}
And your callWebService method like this,
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
} catch (SocketTimeoutException e) {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
e.printStackTrace();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
});
}
}
Update 1
To answer your questions from your comments,
1)Yes Async Task is more efficient. It has its own methods to do the same task what I have described here.
AsyncTask has the following methods,
i)onPreExecute()-which can be used to start your Dialog
ii)doInBackground()-which acts as the background thread.
iii)onPostExecute()-which gets called at the end where you can dismiss the dialog.
The reason why I didn't mention is that, there are possibilities that you might have to change your working code's structure to adapt to Async task.
2)runonUiThread- as the name indicates, anything inside this will be considered as it is running in the main UI thread. So basically to update the screen you have to use this. There are also other methods available, like Handlers which can also do the same task.
Use AsyncTask for it when ever task started at that time initialise your widget and then call your webservice from run method and close your progress bar on stop method.

Only the original thread that created a view hierarchy can touch its views

Im Adding Progress Dialog in some Activity .But im getting Exception mention in title.how to resolve it.
dialog = ProgressDialog.show(Notification.this, "loading please wait",
"Loading. Please wait...", true);
new Thread() {
public void run() {
try{
performBackgroundProcess1();
//sleep(3000,000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
dialog.dismiss();
}
}.start();
Any thing wrong with this.all Background process is performed in performbackgroundprocess method.
You cant call dialog.dismiss(); in the background thread.
You can make Threads send messages to handlers when they are done and in the handler you can dismiss the dialog. Handlers work in ui thread
There is a tutorial about it
use runOnUiThread as:
new Thread() {
public void run() {
try{
performBackgroundProcess1();
//sleep(3000,000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
CurrentActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
}.start();

Android ProgressDialog does not work

Could someone tell me why my code is not working? I want to display a ProgressDialog, but the problem with the code below is that it does not appear, even when it has spent a lot of time processing the function ConsultaComercio. I have seen a lot of examples but I don't understand what I am doing wrong. I appreciate your help. Thanks in advance.
pd = ProgressDialog.show(this, "", "Loading...", true);
Toast.makeText(getApplicationContext(), "Cargando.... " + String.valueOf(numero_prueba), Toast.LENGTH_SHORT).show();
new Thread() {
public void run() {
try{
// Do some Fake-Work
ConsultaComercio();
numero_prueba=60000;
} catch (Exception e) { }
// Dismiss the Dialog
pd.dismiss();
}
}.start();
in your onCreate() do this,
Handler handler=new Handler()
{
public void handleMessage(Message msg)
{
if(pd.isShowing())
{
pd.dismiss();
}
};
and change your thread like this,
Toast.makeText(getApplicationContext(), "Cargando.... " + String.valueOf(numero_prueba), Toast.LENGTH_SHORT).show();
new Thread() {
public void run() {
try{
// Do some Fake-Work
ConsultaComercio();
numero_prueba=60000;
} catch (Exception e) { }
// Dismiss the Dialog
handler.sendEmptyMessage(0);
}
}.start();
You can't update the UI from just any thread. It must be an AsyncTask.

ProgressDialog dismissal in android

I want to open a ProgressDialog when I click on the List Item that opens the data of the clicked Item form the Web Service.
The ProgressDialog needs to be appeared till the WebContent of the clicked Item gets opened.
I know the code of using the Progress Dialog but I don't know how to dismiss it particularly.
I have heard that Handler is to be used for dismissing the Progress Dialog but I didn't found any worth example for using the Handler ultimately.
Can anybody please tell me how can I use the Handler to dismiss the Progress Dialog?
Thanks,
david
Hi this is what you want
public void onClick(View v)
{
mDialog = new ProgressDialog(Home.this);
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable()
{
#Override
public void run()
{
statusInquiry();
}
}).start();
}
here is the web webservice that is called
void statusInquiry()
{
try
{
//calling webservice
// after then of whole web part you will send handler a msg
mHandler.sendEmptyMessage(10);
}
catch (Exception e)
{
mHandler.sendEmptyMessage(1);
}
}
and here goes handler code
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
mDialog.dismiss();
break;
}
}
}
};
A solutiion could be this:
ProgressDialog progressDialog = null;
// ...
progressDialog = ProgressDialog.show(this, "Please wait...", true);
new Thread() {
public void run() {
try{
// Grab your data
} catch (Exception e) { }
// When grabbing data is finish: Dismiss your Dialog
progressDialog.dismiss();
}
}.start();

Categories

Resources