将元素绑定到代码后,为什么我的代码总是收到空指针异常?我在Android Studio中使用Java

尽管我已经正确绑定了元素,但是我正在接收java.lang.NullPointerException。


试图检查元素的ID,它匹配,但是我仍然收到相同的异常。


MainActivity.java

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);



    //Text to Speech

    tts = new TextToSpeech(this, this);


    speakButton = findViewById(R.id.speakButton);


    speechText = findViewById(R.id.speechText);


    speakButton.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

            speakOut();

        }

    });

    // End


    loadFragment(new HomeFragment());


    BottomNavigationView navigation = findViewById(R.id.navigation);

    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

}


TranslatorFragment.java

public class TranslatorFragment extends Fragment {


public Button speakButton;


public TranslatorFragment(){

    //Empty Constructor

}


@Override

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    return inflater.inflate(R.layout.translator_fragment, container, false);

}


public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

}


@Override

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    super.onViewCreated(view, savedInstanceState);

    speakButton = view.findViewById(R.id.speakButton);

}

}


它应该运行正常,但是我收到了java.lang.NullPointerException


牛魔王的故事
浏览 203回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java