为什么((MainActivity)getActivity())给我一个NullPointerException?

时间:2018-01-12 19:26:35

标签: java android nullpointerexception

直升机,

我有以下代码:

EventPopup.java

class EventPopup extends Dialog {

private boolean delete;
private boolean edit;
private boolean editall;

private ReadEvent event;

...     }

DayFragment.java(这是一个片段)

final EventPopup eventpopup = new EventPopup(getContext(), readevent);

            eventpopup.show();

            eventpopup.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {

                    if(eventpopup.getDelete()) {
                        ((MainActivity) getActivity()).refreshViewPager();
                    } else if (eventpopup.getEdit()) {
                        ((MainActivity) getActivity()).doEditEvent(readevent, eventpopup.getEditAll());
                    }
                }
            });

MainActivity.java:

public void refreshViewPager() {
    doubleViewPager.getAdapter().notifyDataSetChanged();
}

为什么这一行有时会在某些设备上给出NullPointerException(在其他设备上没有)?:

                    ((MainActivity) getActivity()).refreshViewPager();

错误消息是:

  

java.lang.NullPointerException:

     

at de.ubik.terminkalender.DayFragment $ 8 $ 1.onDismiss(DayFragment.java:1378)

     

在android.app.Dialog $ ListenersHandler.handleMessage(Dialog.java:1749)

     

在android.os.Handler.dispatchMessage(Handler.java:102)

     

在android.os.Looper.loop(Looper.java:154)

     

在android.app.ActivityThread.main(ActivityThread.java:6692)

     

at java.lang.reflect.Method.invoke(Native Method)

     

at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1468)

     

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

我有以下结构:MainActivity(with viewpager) - > DayFragment(作为片段) - >对话。当我关闭对话框时,我想检查对话框中是否有单击按钮。单击时,然后在MainActivity中刷新viewpager。如何实现?

3 个答案:

答案 0 :(得分:2)

onDismiss

这意味着您的对话框已被解除,这与您的Activity分离,这意味着getActivity()将返回null。最好找到另一种刷新viewpager的方法。你如何做到这一点取决于你为什么要刷新。

答案 1 :(得分:0)

尝试以下方法

//Find the Google Chrome HWND hGoogleChrome = FindWindowEx(NULL, NULL, L"Chrome_WidgetWin_1", NULL);

答案 2 :(得分:0)

如@Deev所提到的,你总是会得到一个null,解决方法是从一些以getActivity为参数的方法调用你的Dialog。

示例代码:

 //call this from your fragment 
 showDialog(getActivity());

并在你的片段中将其置于某个地方

public void showDialog(final Activity activity){
    final EventPopup eventpopup = new EventPopup(activity, readevent);
        eventpopup.show();
        eventpopup.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

                if(eventpopup.getDelete()) {
                    ((MainActivity)activity).refreshViewPager();
                } else if (eventpopup.getEdit()) {
                    ((MainActivity) activity).doEditEvent(readevent, eventpopup.getEditAll());
                }
            }
        });
}

这肯定会有用。