My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:
AlertDialog.Builder builder = new Al
After taking a look at the API, you can pass the dialog your activity or getActivity if you're in a fragment, then forcefully clean it up with dialog.dismiss() in the return methods to prevent leaks.
Though it is not explicitly stated anywhere I know, it seems you are passed back the dialog in the OnClickHandlers just to do this.
For future readers, this should help:
public void show() {
if(mContext instanceof Activity) {
Activity activity = (Activity) mContext;
if (!activity.isFinishing() && !activity.isDestroyed()) {
dialog.show();
}
}
}
If your Dialog is creating on the adapter:
Pass the Activity to the Adapter Constructor:
adapter = new MyAdapter(getActivity(),data);
Receive on the Adapter:
public MyAdapter(Activity activity, List<Data> dataList){
this.activity = activity;
}
Now you can use on your Builder
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
If you are outside of the Activity then you need to use in your function "NameOfMyActivity.this" as Activity activity, example:
public static void showDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Your Message")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
//Outside your Activity
showDialog(NameOfMyActivity.this);
Try to use the context of an activity which will be under the dialog. But be carefull when you use "this" keyword, because it will not work everytime.
Forexample, if you have TabActivity as host with two tabs, and each tab is another activity, and if you try to create dialog from one of the tabs (activities) and if you use "this", then you will get exception, In this case dialog should be connected to host activity which host everything and visible. (you can say most visible parent Activity's context)
I did not find this info from any document but by trying. This is my solution without strong background, If anybody with better knownledge, feel free to comment.
I was using ProgressDialog
in a fragment and was getting this error on passing getActivity().getApplicationContext()
as the constructor parameter. Changing it to getActivity().getBaseContext()
didn't work either.
The solution that worked for me was to pass getActivity()
; i.e.
progressDialog = new ProgressDialog(getActivity());