Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

java - null pointer exception on calling interface method implemented in other class

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.

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-

Source code:

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");
    }
}

Error Log

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...