Search code examples
javaandroidandroid-intentandroid-activitymobile-application

Getting a crash every time i press a button"Android Studio"


I am trying to make a mobile application,but when ever i try to press the button i get a crash. The button should take me to a new activity page, i have already connect the other pages with the button in a right way. i am just wondering if this code is correct or not:

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




    }

    public void onButtonClick(View v)
    {
        Button a1= (Button) findViewById(R.id.button);
        a1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondPage.class);
                startActivity(intent);
            }
        });

    }
    public void onButtonClick1(View c)
    {
        Button a1= (Button) findViewById(R.id.button2);
        a1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this, ThirdPage.class);
                startActivity(intent);
            }
        });

    }
    public void onButtonClick2(View d)
    {
        Button a1= (Button) findViewById(R.id.button3);
        a1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this, FourthPage.class);
                startActivity(intent);
            }
        });

    }
    public void onButtonClick3(View f)
    {
        Button a1= (Button) findViewById(R.id.button4);
        a1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this, FifthPage.class);
                startActivity(intent);
            }
        });

    }

}

i just learned java from some videos in the youtube,so i am not sure if i did the activity function well or not. Thank you


Solution

  • There can be few reasons after it

    1) Make sure you defined activity in Manifest file

    2) check for android:onClick="" in xml file..

    OR

    Try Binding Buttons in onCreate() method.

    and You can simply use this for onClick

    a1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondPage.class);
                startActivity(intent);
            }
        });