我正在开发一个应用程序,我需要在两个片段之间进行通信。我知道两个片段之间的通信是通过使用接口完成的。我在片段1中创建了一个接口并在活动中实现它,但是当我运行该应用程序时,它会崩溃。下面片段通信不起作用make java.lang.nullpointerexception
是我的代码
片段一个代码
public class Fragment_one extends Fragment {
EditText editText;
Button button;
SendData sd;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_one,container,false);
editText = (EditText)view.findViewById(R.id.editText);
button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data ;
data = editText.getText().toString();
sd.SendData1(data);
}
});
return view;
}
interface SendData
{
String SendData1(String name);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
sd = (SendData)context;
}catch (ClassCastException e){
throw new ClassCastException ("You have to impliment it");
}
}
}
当我调试应用程序,我知道sd
是null
。但数据正在被设置为文本。
任何一个可以帮助我走出这个问题
什么是'SendData'? –
在你的'onAttach()'里面设置一个断点,看看为什么它是空的。 –
您可以使用接口与碎片进行通信。 –