I am trying to include a ProgressDialog in my application. But it is not showing up.
Here's the code snippet where i use the ProgressDialog:
public class abcActivity extends Activity {
public boolean onOptionsItemSelected(MenuItem item) {
case XYZ:
ProgressDialog dialog = ProgressDialog.show(abcActivity.this, "", "Please wait for few seconds...", true);
callSomeFunction();
dialog.dismiss();
showToast(getString(R.string.SomeString));
break;
}
}
Does anyone know why the dialog is not showing up? Any clues?
I think your code is wrong in a sense that you do all in the UI thread. You have to put callsomefunction() into a background thread.
public void runSomething()
{
showDialog(BACKGROUND_ID);
Thread t = new Thread(new Runnable()
{
public void run()
{
//do something
handler.post(finishThread);
}
});
t.start();
// The progress wheel will only show up once all code coming here has been executed
}
And as well
protected Dialog onCreateDialog(int id)
{
if(progressDialog == null) progressDialog = new ProgressDialog(this);
return progressDialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog)
{
if(id == BACKGROUND_ID)
{
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setMessage("running for long ...");
}
}
Runnable finishThread = new Runnable()
{
public void run()
{
//long running
if(progressDialog != null) progressDialog.dismiss();
}
};
i think issue is in your switch condition pls verify it.
here is another method to display dialog in android try this.
public static final int DIALOG2_KEY = 1;
public static ProgressDialog dialog1;
showDialog(DIALOG2_KEY); // use it where you want to display dialog
dialog1.cancel(); // use it to cancel the dialog
#Override
public Dialog onCreateDialog(int id) {
if (id == 1) {
dialog1 = new ProgressDialog(this);
dialog1.setMessage("Please wait...");
dialog1.setIndeterminate(true);
dialog1.setCancelable(true);
}
return dialog1;
}
Ensure you have this code called by debugging or adding a log. The code seems right to me.
Also, if you want to perform some operations in background and show a progress dialog while the performing, please use AsyncTask with ProgressDialog bounded, like here.
ProgressDialog is deprecated in Android O , Use ProgressBar now.
Related
I have a dialog fragment with a simple indeterminate progress bar in the centre, which i use to show network activity:
public class NativeLoadingDialogFragment extends DialogFragment {
public NativeLoadingDialogFragment() {
// Blank
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
ProgressBar indeterminateProgressBar = new ProgressBar(getActivity());
indeterminateProgressBar.setIndeterminate(true);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(indeterminateProgressBar);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
return dialog;
}
public boolean isShowing() {
return getDialog() != null;
}
}
I have used the dialog fragment throughout my app with no issues, it shows up without issue in lots of places when i call dialog.show(getFragmentManager, null), however when I try to call it in onResume of my settings activity it does not show!
I have an activity for settings, which launches the system settings to change the language of the phone. Once the user changes the language and my activity resumes I detect if the language has changed and do a network call:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mLoading = new NativeLoadingDialogFragment();
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(EXTRA_LANGUAGE)) {
String language = savedInstanceState.getString(EXTRA_LANGUAGE);
String currentLanguage = AppUtils.getDefaultLanguageCode(
SmartBankConstant.DEFAULT_LANGUAGE,
SmartBankConstant.SUPPORTED_LANGUAGES);
if (!language.equals(currentLanguage)) {
updateLanguage(Language.stringToLanguage(currentLanguage));
}
}
}
}
private void updateLanguage(Language newLanguage) {
....
getSpiceManager().execute(new SetLanguageRequest(newLanguage),
new SetLanguageRequestListener(this));
mLoading.show(getFragmentManager(), null);
getFragmentManager().executePendingTransactions();
}
The code definitely runs but no dialog appears! If the network call fails I have a retry option that calls the updateLanguage(Language newLanguage) method again, and the dialog actually appears that time! What am I doing wrong?
Try with this approach. It checks if the dialog is already displayed, otherwise it shows it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mLoading = new NativeLoadingDialogFragment();
if (savedInstanceState != null) {
...
}
mLoading.show(getFragmentManager(), null);
}
private void updateLanguage(Language newLanguage) {
...
if (mLoading != null && !mLoading.isVisible()) {
mLoading.show(getFragmentManager(), null);
getFragmentManager().executePendingTransactions();
}
}
I don't know why, but running fragment transaction in the next loop helped to solve this issue.
new Handler().post(new Runnable() {
#Override public void run() {
// for some reason this must be called in the next loop
dialogFragment.show(getSupportFragmentManager(), tag);
}
});
I want to show another alert message(alert box/alert dialog) after the progress bar reaches 100%. How do I do that?
And Also is there any way to style that box (or both of them)?
Below is my code for an ProgressBar:
public class MainActivity extends Activity {
Button progress_button;
ProgressDialog pro_dialog;
Handler pro_handler;
int progress;
private static final int MAX_PROGRESS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// intiliazing the buttons
progress_button = (Button) findViewById(R.id.button1);
progress_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Creating progress dialog interface setting
// title,progressstyle,max_progress
pro_dialog = new ProgressDialog(MainActivity.this);
pro_dialog.setTitle("Making everything OK is in progress! Please be patient.");
pro_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pro_dialog.setMax(MAX_PROGRESS);
progress = 0;
pro_dialog.show();
pro_dialog.setProgress(0);
pro_handler.sendEmptyMessage(0);
}
});
// set onclick listener for buttons
pro_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (progress >= MAX_PROGRESS) {
pro_dialog.dismiss();
} else {
progress++;
pro_dialog.incrementProgressBy(2);
pro_handler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
First of all, it would make more sense if you could replace:
pro_dialog.incrementProgressBy(2);
with this:
pro_dialog.setProgress(progress);
Current code dismisses dialog after progress variable reaches MAX_PROGRESS, but current value of this variable isn't presented by the progress dialog.
If you would like to show AlertDialog, you can do it for example after "pro_dialog.dismiss()".
Case of Progress Dialog styling has been discused here.
I'm having the following issue developing in android 2.2 (API 8):
I have a customized Dialog class like this:
public AuthDialog(final Context context, OnDismissListener dismissListener, OnCancelListener cancelListener) {
super(context);
setOnDismissListener(dismissListener);
setOnCancelListener(cancelListener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpassdialog);
setTitle("Enter email and password");
setCancelable(true);
setCanceledOnTouchOutside(true);
authEmail = (EditText) findViewById(R.id.authEmail);
authPass = (EditText) findViewById(R.id.authPass);
alertMessage = (TextView) findViewById(R.id.auth_alert);
Button authButton = (Button) findViewById(R.id.authButton);
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (checkCredentials())
dismiss();
else
showAlert();
}
};
authButton.setOnClickListener(onClickListener);
}
private void showAlert() {
alertMessage.setText("Wrong user/pass");
authEmail.setText(null);
authPass.setText(null);
}
private boolean checkCredentials() {
// Empty user/pass for now
boolean checkEmail = authEmail.getText().toString().equals("");
boolean checkPassword = authPass.getText().toString().equals("");
return checkEmail && checkPassword;
}
#Override
public void onBackPressed() {
cancel();
}
And I create a new AuthDialog like this:
private void authenticateThenAccept() {
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
accept();
}
};
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel();
}
};
AuthDialog dialog = new AuthDialog(context, dismissListener, cancelListener);
dialog.show();
}
I'm using the debugger, and I see that when I cancel (using the back button or pressing outside the dialog) the app dismisses the dialog instead of cancelling.
Anybody has had this kind of issue with Dialogs?
Thanks in advanced.
onDismiss() is always fired when dialog closes. The documentation for setOnCancelListener() states: "This will only be invoked when the dialog is canceled, if the creator needs to know when it is dismissed in general, use setOnDismissListener", i.e. it's not either onCancel or onDismiss but both when a dialog is canceled. I agree though that it would have made more sense had that not been the case.
Assuming this dialog should be modal, make your dialog a new activity.
setCancelable(false) will prevent the back button from doing anything. Many developers just turn off the ability of the back button to close the dialog since it's unclear whether that is a cancel or ok action to the user.
I have a little problem; I hope you can help me.
While progressDialog is running, the user presses the BACK Button. The current Activity progressDialog goes to Background, but progressDialog is running.
My problem is that when the user clicks on the BACK button, progressDialog should be foreground Activity, stop current progress and ask "Do you want to continue or exit?"
If the user presses Continue, progressDialog should continue the remaining work.
Otherwise, close the current activity.
CODE HERE:
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
return true;
}
return super.onKeyDown(keyCode, event);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
progressDialog.setCancelable(true);
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}
You need to override back button event. You can do this as:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing()) {
Log.d(this.getClass().getName(), "back button pressed");//write your own logic here, Whatever you want to do
}
return super.onKeyDown(keyCode, event);
}
Well, I had the same issue. The simplest method that worked for me is using progressDialog.setCancelable(true).. This declares whether the dialog is cancelable by hitting the back key.. Try it and let me know if it works for you or not. Good luck
Similar issue , When progressDialog.setCancelable(true) is set then hitting back button does not execute code written in back button code but just cancels the progress dialog..Hitting the key again works.
i want to cancel the progress dialog and execute some piece of code together which is not working.
Clicking back button twice does not make sense to me.
You can use progressDialog.setCancelable(true) and then use progressDialog.setOnCancelListener() to provide the OnCancelListener to execute your code to be executed onCancel().
See the Android documentation on Dialogs.
I have an Overlay extension which has 2 dialogs as private attributes - one Dialog and one ProgressDialog. After clicking on the Overlay in the MapView, the Dialog object appears. When the user clicks a button in the Dialog it disappears and the ProgressDialog is shown. Simultaneously a background task is started by notifying a running Service. When the task is done, a method (buildingLoaded) in the Overlay object is called to switch the View and to dismiss the ProgressDialog. The View is being switched, the code is being run (I checked with the debugger) but the ProgressDialog is not dismissed. I also tried hide() and cancel() methods, but nothing works. Can somebody help me?
Android version is 2.2
Here is the code:
public class LODOverlay extends Overlay implements OnClickListener {
private Dialog overlayDialog;
private ProgressDialog progressDialog;
..............
#Override
public void onClick(View view) {
.......
final Context ctx = view.getContext();
this.progressDialog = new ProgressDialog(ctx);
ListView lv = new ListView(ctx);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, R.layout.layerlist, names);
lv.setAdapter(adapter);
final LODOverlay obj = this;
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view).getText().toString();
Intent getFloorIntent = new Intent(Map.RENDERER);
getFloorIntent.putExtra("type", "onGetBuildingLayer");
getFloorIntent.putExtra("id", name);
view.getContext().sendBroadcast(getFloorIntent);
overlayDialog.dismiss();
obj.waitingForLayer = name;
progressDialog.show(ctx, "Loading...", "Wait!!!");
}
});
.......
}
public void buildingLoaded(String id) {
if (null != this.progressDialog) {
if (id.equals(this.waitingForLayer)) {
this.progressDialog.hide();
this.progressDialog.dismiss();
............
Map.flipper.showNext(); // changes the view
}
}
}
}
Not sure if this is the cause of your issue, but the method you are calling on ProgressDialog is static, but you are calling it on an instance of the class. Here's the method definition:
public static ProgressDialog show (Context context, CharSequence title, CharSequence message)
As you can see, the method returns a ProgressDialog, it does not perform the show operation on your instance of the class. Update your code to use one of these:
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Wait!!!");
progressDialog.show();
or
progressDialog = ProgressDialog.show(ctx, "Loading...", "Wait!!!");
ProgressDialog.show(...) methods do in fact perform a show() on the dialog before returning it. Here is Android.jar source:
public static ProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate,
boolean cancelable, OnCancelListener cancelListener) {
ProgressDialog dialog = new ProgressDialog(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setIndeterminate(indeterminate);
dialog.setCancelable(cancelable);
dialog.setOnCancelListener(cancelListener);
dialog.show();
return dialog;
}
All the overloads of this method refer to this one.