Cannot fix Java null pointer error

前端 未结 4 704
悲哀的现实
悲哀的现实 2021-01-29 06:19

I have some code that when I run it returns a null pointer error. This is the code and error from the logcat:

import android.support.v7.app.AppCompatActivity;
im         


        
4条回答
  •  旧时难觅i
    2021-01-29 07:01

    You are not setting the onClickListener for your red button, you are reassigning the listener to the blue button.

    Button red = (Button) findViewById(R.id.red_button);
    blue.setOnClickListener(new View.OnClickListener() {
    

    Have you also defined the onClick property in the xml layout file? If so then you need to ensure you have a method matching the name you have specified. For example if you have entered

    onClick="buttonClicked"
    

    You need to define a method called

    public void buttonClicked() { /* OnClick functionality here */ }
    

    See: @https://stackoverflow.com/a/38547338/1540698 from @vucko for your second issue.

提交回复
热议问题