[android] How to open a second activity on click of button in android app

I am learning to build android applications and I need some specific help. I can't seem to get my head around which bits of template code I am required to change, and which bits are static.

In the LAYOUT folder I have my ACTIVITY_MAIN.XML which reads

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="horizontal">

 <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/main_buttons_photos" />

 </LinearLayout>

Next, I have my second activity ACTIVITY_SEND_PHOTOS.XML which is

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".SendPhotos" />

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/title_activity_send_photos"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>

I then have my MainActivity.java (is this the .class?) this reads package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;

 public class MainActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.activity_main, menu);
     return true;
 }
 /** Called when the user clicks the Send button */
 public void sendMessage(View view) {
     // Do something in response to button
 }
 }

and then my SendPhotos.java file which is;

 package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.support.v4.app.NavUtils;

 public class SendPhotos extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_photos);
    getActionBar().setDisplayHomeAsUpEnabled(true);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_send_photos, menu);
    return true;
 }


 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
 }

 }

I would like the button in my main activity to link through to my sendphotos activity, simply opening up that activity, nothing fancy, not sending any data or anything.

I know that somewhere I need my

 Intent i = new Intent(FromActivity.this, ToActivity.class);
 startActivity(i);

but I have no idea what to replace ToActivity.class with or what else I need where.

This question is related to android android-intent android-activity

The answer is


Replace the below line code:

import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
   Button button;
    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
      }
       public void onClick(View v) {
        if(v.getId==R.id.button1){
      Intent i = new Intent(FromActivity.this, ToActivity.class);
               startActivity(i);
            }
        }
     }

Add the below lines in your manifest file:

   <activity android:name="com.packagename.FromActivity"></activity>
   <activity android:name="com.packagename.ToActivity"></activity>

If you have two buttons and have the same id call to your button click events like this:

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

    btn1= (Button)findViewById(R.id.button1);

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

    btn2=(Button) findViewById(R.id.button1);//Have same id call previous button---> button1

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

        }
    });

When you clicked button1, button2 will work and you cannot open your second activity.


From Activity : where you are currently ?

To Activity : where you want to go ?

Intent i = new Intent( MainActivity.this, SendPhotos.class); startActivity(i);

Both Activity must be included in manifest file otherwise it will not found the class file and throw Force close.

Edit your Mainactivity.java

crate button's object;

now Write code for click event.

        Button btn = (button)findViewById(R.id.button1);
         btn.LoginButton.setOnClickListener(new View.OnClickListener() 
       {

                @Override
                public void onClick(View v) 
                {
                 //put your intent code here
                }
   });

Hope it will work for you.


This always works, either one should be just fine:

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            startActivity(new Intent("com.tobidae.Activity1"));
        }
        //** OR you can just use the one down here instead, both work either way
        @Override
        public void onClick (View v){
            Intent i = new Intent(getApplicationContext(), ChemistryActivity.class);
            startActivity(i);
        }
    }
}

Replace your MainActivity.class with these code

public class MainActivity extends Activity {

Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 b1=(Button)findViewById(R.id.button1);
 b1.setOnClickListener(new View.onClickListener()
 {
  public void onClick(View v)
   {
       Intent i=new Intent(getApplicationContext(),SendPhotos.class);
       startActivity(i);
    }
 }
 )
}

Add these Code in your AndroidManifest.xml after the </activity> and Before </application>

<activity android:name=".SendPhotos"></activity>

 <Button
            android:id="@+id/btnSignIn"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circal"
            android:text="Sign in"
            android:textColor="@color/white"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etPasswordLogin" />

IN JAVA CODE

Button signIn= (Button) findViewById(R.id.btnSignIn);

signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInPage.this,MainActivity.class));
            }
        });

}


Button btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(MainActivity.this, MainActivity2.class);
        MainActivity.this.startActivity(myIntent);       
    }  
});

The answer for the complete noob from a complete noob: MainActivity is the name of the first activity. MainActivity2 is the name of the second activity. button1 is the I.D of the button in xml for MainActivity Activity.


Try this

  Button button;

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent i = new Intent(getApplicationContext(),SendPhotos.class);
                        startActivity(i);
                    }
                });

 }

add below code to activity_main.xml file:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonClick"
        android:text="@string/button" />

and just add the below method to the MainActivity.java file:

public void buttonClick(View view){
  Intent i = new Intent(getApplicationContext()SendPhotos.class);
  startActivity(i);
}

You can move to desired activity on button click. just add
android:onClick="timerApp"this line.

xml:

 <Button
        android:id="@+id/timer_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="timerApp"
        android:text="Click To run Timer Activity" />

In your main activity just add this method:

 public void timerApp(View view){
        Intent intent= new Intent(MainActivity.this,TimerActivity.class);
        startActivity(intent);
    }

OR in onCreate() method add below code

Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, TimerActivity.class);
        startActivity(intent);       
    }  
});

just follow this step (i am not writing code just Bcoz you may do copy and paste and cant learn)..

  1. first at all you need to declare a button which you have in layout

  2. Give reference to that button by finding its id (using findviewById) in oncreate

  3. setlistener for button (like setonclick listener)

  4. last handle the click event (means start new activity by using intent as you know already)

  5. Dont forget to add activity in manifest file

BTW this is just simple i would like to suggest you that just start from simple tutorials available on net will be better for you..

Best luck for Android


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items