I could show dialog if I uses an Activity instance but when I uses Context or Application Context instance Dialog is not showing.
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(msg);
if (null != positiveLabel) {
builder.setPositiveButton(positiveLabel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if (null != listener) {
listener.onOk();
}
}
});
}
if (null != negativeLable) {
builder.setNegativeButton(negativeLable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if (null != listener) {
listener.onCancel();
}
}
});
}
builder.create().show();
Can you please give me a solution to show dialog without using Activity instance
The problem is something I faced recently too, you cant create a dialog without and activity instance. getApplicationContext() call doesn't work too. The way I did this is to make the call to a method that creates the dialog, from an activity, and pass "this" i.e. the reference to that activity as a parameter.
If you are going to reuse this code, as a reusable component or as a mechanism to create dialogs at multiple places, create a base activity class and have this method in there, and use it in sub-classed activities as needed.
For some reason [at least in android 2.1] a toast can be on the application context but not a progress dialog
MyActivity.this is an activity specific context which does not crash
MyActivity.getApplicationContext() is global and will crash progress bars and in later versions also toasts.
This is one of the MOST important things that you must always remember about Contexts. There are 2 types of contexts,
Activity contexts
andApplication contexts
. You will observe in many UI related classes, a Context is passed. This is not the Application context! In such cases you must always pass an Activity Context. Except for aToast
, no other UI component will work with Application context.Application Context is always passed when you want some service or component which is Application related, like the Telephony Manager, Location Manager etc.
For UIs, you must always pass a context that is UI related which is the Activity.