我需要将fun getItemDetails() = object: ItemDetailsLookup.ItemDetails<String>() {
override fun getSelectionKey() = myData[adapterPosition].myKey
// ...
}
中的字符串数据从EditTexts
传递到Fragment
,我知道我必须使用Activity
。但是我仍然有相同的错误(interface
)。你能告诉我如何解决吗?这是我的代码:
Null Object
Main Activity
public class IntroActivity extends AppCompatActivity implements fragment_intro_activity_2.OnDataPass {
Button button_intro;
EditText et;
boolean showingFirst;
String wynik;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
button_intro = findViewById(R.id.button_intro);
et = findViewById(R.id.edOperetka);
FullScreencall();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_contrainer_intro,
new fragment_intro_activity_1()).commit();
showingFirst = true;
button_intro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(showingFirst==true){
getSupportFragmentManager().beginTransaction().replace(R.id.frame_contrainer_intro,
new fragment_intro_activity_2()).commit();
showingFirst = false;
}else {
//
// Toast.makeText(IntroActivity.this, "123123", Toast.LENGTH_SHORT).show();
wynik = et.getText().toString();
onDataPass(wynik);
}
}
});
}
Fragment
public class fragment_intro_activity_2 extends Fragment {
View v;
OnDataPass dataPasser;
public fragment_intro_activity_2() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_fragment_intro_activity_2, container, false);
return v;
}
public interface OnDataPass {
void onDataPass(String data);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
dataPasser = (OnDataPass) context;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
}
Logcat
这54行是这样的:Process: com.example.wynagrodzeniedodatkowe, PID: 32263
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.wynagrodzeniedodatkowe.IntroActivity$1.onClick(IntroActivity.java:54
答案 0 :(得分:0)
看着logcat消息,它告诉我下面的行
findViewById(R.id.edOperetka)
返回null,因此请确保在XML中正确创建了ID,并从代码中正确引用了ID(该ID是相同的)。
如果您不想在片段中检索EditText,则可以执行以下操作。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_fragment_intro_activity_2, container, false);
EditText et = v.findViewById(R.id.edOperetka);
return v;
}
现在,您可以像以前一样从中检索文本。