My Fragment总是抛出
java.lang.NullPointerException: Attempt to invoke interface method 'void FragmentClass$InputCallbacks.OnTextChanged(java.lang.CharSequence)' on a null object reference
因为这行:
UserInput.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mListener.OnTextChanged(s);
}
});
我对mListener的其他用途并没有抛出一些东西。 我想这是因为使用了新的Textwatcher(){....}但是我没有经验足以自己解决这个问题: - /
整个班级抛出错误:
public class ToolbarInputOneAddress extends Fragment {
private InputCallbacks mListener;
public ToolbarInputOneAddress() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.toolbar_input_one_address, container, false);
Address address = mListener.getAddress();
EditText UserInput = (EditText) v.findViewById(R.id.InputField);
if (address != null) {
StringBuilder Sb = new StringBuilder();
UserInput.setText(SuggestAddresses.createFormattedAddressFromAddress(address, Sb));
}
UserInput.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mListener.OnTextChanged(s);
}
});
ImageButton ReturnButton = (ImageButton) v.findViewById(R.id.btn_navigation_drawer_back);
ReturnButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onReturnButtonClicked();
}
});
return v;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (InputCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement InputCallbacks");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface InputCallbacks {
void OnTextChanged(CharSequence s);
void onReturnButtonClicked();
Address getAddress();
}
}
答案 0 :(得分:0)
我想我解决了。 我像这样在
这样的组中声明我的回调片段public interface $Callbacks {
void $Callback1(String s);
void $Callback2();
Address $Callback2();
}
原来我有多个使用相同名称定义的回调组。我认为这没关系,因为我在我的活动中明确指出implements
。
由于我将回调组名称更改为不同的名称,因此我不再使用NPE:
TL,DR:
我改变了
implements $fragment1.callbacks $fragment2.callbacks $fragment3.callbacks
到
implements $fragment1.f1callbacks $fragment2.f2callbacks $fragment3.f3callbacks
在我的活动中实现所述片段回调