Search code examples
javaandroidonclicklistener

Unable to implement OnClickListener into separate Java class


OnClickListener works fine when I implement on MainActivity class of Java .But its a messy practice to use on same class of main interference. So I add a separate Java class ButtonListener.java and wrote the following code

public class ButtonListener extends MainActivity implements View.OnClickListener {

            @Override
            public void onClick(View v) {
            switch(v.getId()) {
                case R.id.button2:
                    CL.setBackgroundColor(Color.parseColor("#00ff00"));
                    break;
                case R.id.button:
                    CL.setBackgroundColor(Color.BLUE);
                    break; }}}

and following is code of MainActivity.java

public class MainActivity extends AppCompatActivity  {
   public ConstraintLayout CL;
   public Button blue,green;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blue= (Button)findViewById(R.id.button);
        green=findViewById(R.id.button2);
        CL= findViewById(R.id.CL) ;
        ButtonListener B= new ButtonListener();

        blue.setOnClickListener(B);
        green.setOnClickListener(B);
}}

I am trying this code but when ever I open my app and click on the button, it crashes.


Solution

  • You're receiving NullPointerException because your cl is not initialized.

    The extends MainActivity give you access to cl variable but it never been written to and it's completely different than MainActivity.cl.

    What you're trying can be achieved with a custom listener (Strong note: You do not need to extend MainActivity to implements listener)

    public class ButtonListener implements View.OnClickListener {
        private ConstraintLayout CL;
        public ButtonListener(ConstraintLayout cl) {
            this.CL = cl;
        }
    
        @Override
        public void onClick(View v) {
           // bla bla
        }
    }
    

    And in your MainActivity, replace:

    ButtonListener B= new ButtonListener();
    
    blue.setOnClickListener(B);
    green.setOnClickListener(B);
    

    With:

    ButtonListener B= new ButtonListener(CL); // pass contraints layout here
    
    blue.setOnClickListener(B);
    green.setOnClickListener(B);