在其他类中实现的调用接口方法上的空指针异常

我正在尝试调用getFailureDialog()接口的方法OnSelectedListener。该方法在中实现MainActivity.java。但是当我调用该方法时,我得到了异常" title="空指针异常">空指针异常。

我知道这是因为OnSelectedListener它仍未初始化,因此您正在调用getFailureDialog()未初始化的对象。显然,接口方法永远不会初始化。但是,如何getFailureDialog()从类中调用该方法Common.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();

}

public class Common

{

OnSelectedListener mCallback;

public interface OnSelectedListener

{

public void getFailureDialog();

}

public void myRecord(String email)

{

mCallback.getFailureDialog(); //null pointer exception here

}

}

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;

永远不会初始化,或者正在使用null值初始化。

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.

}

}

以上是 在其他类中实现的调用接口方法上的空指针异常 的全部内容, 来源链接: utcz.com/qa/424236.html

回到顶部