How to start new activity on button click

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

  • How to change the color of a SwitchCompat
  • Setting ActionMode Background programmatically
  • Android Linear Layout - How to Keep Element At Bottom Of View?
  • could not access the package manager. is the system running while installing android application
  • Unlimited/Dynamic ViewPager in both directions
  • android : Error converting byte to dex
  • Related posts:

    Typical .gitignore file for an Android app
    Android Facebook authorization - can not log in when official Facebook app is installed
    How to align the image source within the ImageButton?
    ViewPager: Recursive entry to executePendingTransactions
    Where to put google-services.json file into eclipse project?
    Android: remove an image from sd card
  • Android device configuration for AOSP
  • Read a pdf file from assets folder
  • Using default ShapeDrawable in a StateListDrawable in Android 4.2
  • How to install an older version of Android Studio
  • Facebook Graph API: Getting a random N friends?
  • Android: Detect softkeyboard open
  • 15 Solutions collect form web for “How to start new activity on button click”

    Easy.

    Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
    myIntent.putExtra("key", value); //Optional parameters
    CurrentActivity.this.startActivity(myIntent);
    

    Extras are retrieved on the other side via:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String value = intent.getStringExtra("key"); //if it's a string you stored.
    }
    

    Don’t forget to add your new activity in the AndroidManifest.xml:

    <activity android:label="@string/app_name" android:name="NextActivity"/>
    

    Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).

    Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
    i.putExtra("PersonID", personID);
    startActivity(i);
    

    Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn’t null (in case if you sometimes don’t pass data), then get the data.

    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {
         personID = extras.getString("PersonID");
    }
    

    Now if you need to share data between two Activities, you can also have a Global Singleton.

    public class YourApplication extends Application 
    {     
         public SomeDataClass data = new SomeDataClass();
    }
    

    Then call it in any activity by:

    YourApplication appState = ((YourApplication)this.getApplication());
    appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic
    

    When user clicks on the button, directly inside the XML like that:

    <Button
             android:id="@+id/button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="TextButton"
             android:onClick="buttonClickFunction"/>
    

    Using the attribute android:onClick we declare the method name that has to be present on the parent activity. So I have to create this method inside our activity like that:

    public void buttonClickFunction(View v)
    {
                Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
                startActivity(intent);
    }
    

    Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.

    1. Using the onClick attribute of the Button. (Beginner)
    2. Assigning an OnClickListener() via an anonymous class. (Intermediate)
    3. Activity wide interface method using the switch statement. (Pro)

    Here’s the link to my example if you want to follow along: https://github.com/martinsing/ToNewActivityButtons

    1. Using the onClick attribute of the Button. (Beginner)

    Buttons have an onClick attribute that is found within the .xml file:

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToAnActivity"
        android:text="to an activity" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToAnotherActivity"
        android:text="to another activity" />
    

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }
    
    public void goToAnActivity(View view) {
        Intent Intent = new Intent(this, AnActivity.class);
        startActivity(Intent);
    }
    
    public void goToAnotherActivity(View view) {
        Intent Intent = new Intent(this, AnotherActivity.class);
        startActivity(Intent);
    }
    

    Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent easily.

    Disadvantage: Difficult readability when reviewing.

    2. Assigning an OnClickListener() via an anonymous class. (Intermediate)

    This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
    
            button1 = (Button) findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent Intent = new Intent(view.getContext(), AnActivity.class);
                    view.getContext().startActivity(Intent);}
                });
    
            button2 = (Button) findViewById(R.id.button2);
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent Intent = new Intent(view.getContext(), AnotherActivity.class);
                    view.getContext().startActivity(Intent);}
                });
    

    Advantage: Easy to make on the fly.

    Disadvantage: there will be a lot of anonymous classes which will make readability difficult when reviewing.

    3. Activity wide interface method using the switch statement. (Pro)

    This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity’s buttons.

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button1:
                Intent intent1 = new Intent(this, AnActivity.class);
                startActivity(intent1);
                break;
            case R.id.button2:
                Intent intent2 = new Intent(this, AnotherActivity.class);
                startActivity(intent2);
                break;
            default:
                break;
        }
    

    Advantage: Easy button management because all button intents are registered in a single onClick() method


    For the second part of the question, passing data, please see How do I pass data between Activities in Android application?

    Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
    startActivity(iinent);
    
        Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);    
        startActivity(in);
    
        This is an explicit intent to start secondscreen activity.
    

    Emmanuel,

    I think the extra info should be put before starting the activity otherwise the data won’t be available yet if you’re accessing it in the onCreate method of NextActivity.

    Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
    
    myIntent.putExtra("key", value);
    
    CurrentActivity.this.startActivity(myIntent);
    

    From the sending Activity try the following code

       //EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
        public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           ....
    
            //Here we declare our send button
            Button sendButton = (Button) findViewById(R.id.send_button);
            sendButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //declare our intent object which takes two parameters, the context and the new activity name
    
                    // the name of the receiving activity is declared in the Intent Constructor
                    Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
    
                    String sendMessage = "hello world"
                    //put the text inside the intent and send it to another Activity
                    intent.putExtra(EXTRA_MESSAGE, sendMessage);
                    //start the activity
                    startActivity(intent);
    
                }
    

    From the receiving Activity try the following code:

       protected void onCreate(Bundle savedInstanceState) {
     //use the getIntent()method to receive the data from another activity
     Intent intent = getIntent();
    
    //extract the string, with the getStringExtra method
    String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
    

    Then just add the following code to the AndroidManifest.xml file

      android:name="packagename.NameOfTheReceivingActivity"
      android:label="Title of the Activity"
      android:parentActivityName="packagename.NameOfSendingActivity"
    
    Intent i = new Intent(firstactivity.this, secondactivity.class);
    startActivity(i);
    

    The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it’s a wealth of info on the subject, and has examples too.

    You can try this code:

    Intent myIntent = new Intent();
    FirstActivity.this.SecondActivity(myIntent);
    

    Try this simple method.

    startActivity(new Intent(MainActivity.this, SecondActivity.class));
    

    Implement the View.OnClickListener interface and override the onClick method.

    ImageView btnSearch;
    
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_search1);
            ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
            btnSearch.setOnClickListener(this);
        }
    
    @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnSearch: {
                    Intent intent = new Intent(Search.this,SearchFeedActivity.class);
                    startActivity(intent);
                    break;
                }
    

    Start another activity from this activity and u can pass parameters via Bundle Object also.

    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("USER_NAME", "xyz@gmail.com");
    startActivity(intent);
    

    Retrive data in another activity (YourActivity)

    String s = getIntent().getStringExtra("USER_NAME");
    

    Starting an activity from another activity is very common scenario in android application development. To start an you need an Intent object.

    An intent object takes two parameter in its constructor

    1. Context
    2. Name of the activity to be started.

    So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity
    (HomeActivity–>DetailActivity).

    Here is the code snippet to start DetailActivity from HomeActivity.

    Intent i = new Intent(HomeActivity.this,DetailActivity.class);
    startActivity(i);
    

    And you are done.

    Coming back to button click part.

    Button button = (Button) findViewById(R.id.someid);
    
    button.setOnClickListener(new View.OnClickListener() {
    
         @Override
         public void onClick(View view) {
             Intent i = new Intent(HomeActivity.this,DetailActivity.class);
             startActivity(i);  
          }
    
    });
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.