我正在開發一個應用程序,我需要在兩個片段之間進行通信。我知道兩個片段之間的通信是通過使用接口完成的。我在片段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()'裏面設置一個斷點,看看爲什麼它是空的。 –
您可以使用接口與碎片進行通信。 –