java – 在其他类中实现的调用接口方法的null指针异常

我试图调用接口OnSelectedListener的方法getFailureDialog().
该方法在MainActivity.java中实现.但是当我打电话给这个方法时,我得到了
空指针异常.

我知道它是因为OnSelectedListener仍然没有初始化,你在未初始化的对象上调用getFailureDialog().显然,接口方法永远不会被初始化.但是,如何从我的类Common.java中调用方法getFailureDialog()?

我只在下面放置相关的源代码 –

源代码:

SharedFragment.java

public class SharedFragment extends DialogFragment 
{       
    Bundle bundle = getArguments();
    final String email = bundle.getString("email");

    Thread t=new Thread(new Runnable() 
    {
        public void run() {
        common.myRecord(email);
    }
    });   t.start(); 
}

Common.java

public class Common
{
OnSelectedListener mCallback;


    public interface OnSelectedListener 
    {
        public void getFailureDialog();
    }

    public void myRecord(String email)
    {
        mCallback.getFailureDialog();  //null pointer exception here
    }
}

MainActivity.java

public class MainActivity implements Common.OnSelectedListener
{

@Override
    public void getFailureDialog()
    {

        RecordFailure fd = new RecordFailure(); 
        fd.show(getSupportFragmentManager(), "dialog");
    }
}

错误日志

03-22 15:50:39.032: W/dalvikvm(20796): threadid=16: thread exiting with uncaught exception (group=0x4204c450)
03-22 15:50:39.052: E/AndroidRuntime(20796): FATAL EXCEPTION: Thread-30126
03-22 15:50:39.052: E/AndroidRuntime(20796): java.lang.NullPointerException
03-22 15:50:39.052: E/AndroidRuntime(20796):    at com.cornmail.util.Common.myRecord(Common.java:2062)

解决方法:

OnSelectedListener mCallback;

永远不会被初始化,或者正在使用空值进行初始化.

public class Common
{
    OnSelectedListener mCallback = new OnSelectedListener(){
        public void getFailureDialog(){
            JOptionPane.showMessageDialog(null, "An Error Has Occurred.");
        }
    };


    public interface OnSelectedListener 
    {
        public void getFailureDialog();
    }

    public void myRecord(String email)
    {
        mCallback.getFailureDialog();  //now this works.
    }
}
上一篇:java.lang.NullPointerException:需要位置


下一篇:Java – Array中的NullPointerException