Setting an onClick listener to a layout

692 views Asked by At

I have a Relative layout (useMe) that loads one of two fragments on creation depending on the orientation of the screen. I keep getting the error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

the problem is this little bit of code right here

RelativeLayout useMe = (RelativeLayout) findViewById(R.id.startpage_activity);

useMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(StartPage.this, Question1.class);

                startActivity(intent);

            }
        });

How is the useMe a null object?

2

There are 2 answers

3
Anand Savjani On
Intent intent = new Intent(getActivity(), Question1.class);
startActivity(intent);

and define Activity in Manifest file

0
Brexx Galangue On

Are you Trying to start another Activity?, or Another Fragment?

btw, you can use this set-up of Intent:

1st: include android:OnClick= "useMe" and android:Clickable="true" in your Relative layout and do this one:

public void useMe(View view)
{
    Intent intent = new Intent(getActivity(), Question1.class);
    startActivity(intent);
    finish();
}

hope it helps :D

P.S: if OnClick in RelativeLayout is not working, try it on LinearLayout, it is working 100% just include the Onclick and Clickable thingy in in your code :)