安卓&x2B;java.lang.NullPointerException:尝试调用接口方法
在编译代码时,我遇到了这个错误(“java.lang.NullPointerException:尝试调用接口方法”),我仍然不知道为什么 这是我的密码:安卓&x2B;java.lang.NullPointerException:尝试调用接口方法,java,android,nullpointerexception,Java,Android,Nullpointerexception,在编译代码时,我遇到了这个错误(“java.lang.NullPointerException:尝试调用接口方法”),我仍然不知道为什么 这是我的密码: public class FragmentDetails extends Fragment { private TextView text1, text2, text3, text4, text5 = null; private Button button1 = null; OnDe
public class FragmentDetails extends Fragment {
private TextView text1, text2, text3, text4, text5 = null;
private Button button1 = null;
OnDetailsDefinedListener mCallback;
public interface OnDetailsDefinedListener {
void executeOrder(String a, String b, String c, String d, String e);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_details, container, false);
button1 = (Button) rootView.findViewById(...);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text1 = getActivity().findViewById(...);
text2 = getActivity().findViewById(...);
text3 = getActivity().findViewById(...);
text4 = getActivity().findViewById(...);
text5 = getActivity().findViewById(...);
String a = text1.getText().toString();
String b = text2.getText().toString();
String c= text3.getText().toString();
String d= text4.getText().toString();
String e= text5.getText().toString();
//this is where my error appears
mCallback.executeOrder(a, b, c, d, e);
}
return rootView;
}
}
(这是我的错误消息)
提前感谢。您的变量
mCallback
已定义但未初始化。您必须先初始化它,然后才能使用它。mCallback
从未启动。
你必须这样做:
mCallback = new OnDetailsDefinedListenerImpl();
mCallback.executeOrder(a, b, c, d, e);
或
您应该向FragmentDetails类添加一个公共方法
public setOnDetailsDefinedListener(OnDetailsDefinedListener listener) {
mCallback = listener;
}
只需在caller类中实现它。就像添加按钮侦听器一样
mFragmentDetails.setOnDetailsDefinedListener(new OnDetailsDefinedListener() {
// You code
})
也许您需要使用onAttach(活动)片段方法
public void onAttach(Activity activity){
super.onAttach(activity);
if(activity instanceof onSomeListener){
mListener=(onSomeListener) activity;
}
}
mCallback从未启动过…问题是…因为我使用的是接口,目的是让实现它的活动拥有“做某事”的代码。另一件事是,我在另一个片段上做了完全相同的事情(没有初始化mCallback),它工作了……没有。如果某件事从未开始,你将获得NPE。永远!你是对的…我犯了错误,我刚刚找到了我所缺少的。谢谢你的帮助:)@BlueHatCoder你错过了什么?我遇到了同样的问题,不明白为什么需要初始化mCallback。@StefanBeike我无法初始化mCallback=new OnDetailsDefinedListenerImpl()。我明白了这个问题:OnDetailsDefindedListenerImpl是抽象的();无法实例化。我可能做错了什么?即使我想在其中增加价值,接口如何初始化。
mFragmentDetails.setOnDetailsDefinedListener(new OnDetailsDefinedListener() {
// You code
})
public void onAttach(Activity activity){
super.onAttach(activity);
if(activity instanceof onSomeListener){
mListener=(onSomeListener) activity;
}
}