androidbuttonandroid-activityswitching

can't switch between activities in android


i am new to android development. i am to switch between activities on my app, i have done the code but when i run the app it doesn't work. when i click on the button which is supposed to take me to the second activity nothing happens.

this is the code on the main java class

package youngadults.camden;

import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.os.Bundle;

public class FrontPage extends ActionBarActivity {

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

    public void onClick(View v) {
        Intent myIntent = new Intent(this, youngadultsp.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(myIntent);
    }

}

this is the code on the xml page of the main class

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frontpagelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/lg" >

    <Button
        android:id="@+id/uyounadults"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_below="@+id/umusicfan"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:background="@drawable/button_custom"
        android:onClick="onClick"
        android:text="@string/uyoungadults" />

    <Button
        android:id="@+id/umusicfan"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_below="@+id/ushop"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:background="@drawable/button_custom"
        android:text="@string/umusicfan" />

So when I click on the button with the id "uyoungadults" it should take me to youngadultsp.class but unfortunately nothing happens.


Solution

  • change your onCreate method to something like this :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.front_page);
        findViewById(R.id.uyounadults).setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
    
                 Intent myIntent = new Intent(FrontPage.this, youngadultsp.class);
                 myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                 startActivity(myIntent);
    
           }
        });
    }