调用在其他类中实现的接口方法时出现空指针异常 [英] null pointer exception on calling interface method implemented in other class

查看:50
本文介绍了调用在其他类中实现的接口方法时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call the method getFailureDialog() of the interface OnSelectedListener. The method is implemented in MainActivity.java. But when I call the method, I am getting the null pointer exception.

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

I know that its because OnSelectedListener is still not initialized and you are calling getFailureDialog() on uninitialized object. Obviously, interface methods are never initialized. But then how do I call the method getFailureDialog() from my class Common.java?

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

I am placing only the relevant source code below-

源代码:

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;

从未被初始化,或者被初始化为空值.

is never getting initialized, or is being initialized with a null value.

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.
    }
}

这篇关于调用在其他类中实现的接口方法时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆