gpt4 book ai didi

java - 调用其他类实现的接口(interface)方法时出现空指针异常

转载 作者:行者123 更新时间:2023-11-29 06:38:53 26 4
gpt4 key购买 nike

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

我知道这是因为 OnSelectedListener 仍未初始化,您正在对未初始化的对象调用 getFailureDialog()。显然,接口(interface)方法永远不会被初始化。但是,如何从我的类 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 - 调用其他类实现的接口(interface)方法时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15568234/

26 4 0
文章推荐: java - 根据 Object 中的 int 值将 ArrayList 拆分为多个