Home > Android > Tutorial – How to start a new Activity

Tutorial – How to start a new Activity

March 31st, 2009 Leave a comment Go to comments

For starting a new Activity we need to use intent, which is an abstract description of an operation to be performed.

http://developer.android.com/reference/android/content/Intent.html

Suppose we are on Activity named ‘CurrentActivity‘ and on certain event (like button click..) we want to start a new Activity named ‘NextActivity’

We can create a new activity as follows.

public class NextActivity extends Activity {

//Your member variable declaration here

// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
//Your code here
}
}

After we have created the new Activity, we have to register it in file ‘AndroidManifest.xml’.
For registering we have to create an entry in ‘AndroidManifest.xml’ as

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

</activity>

Note that here we have not used intent filter , since we are going to use an explicit intent, the syntax of intent filter is

<intent-filter>

<action android:name="<action here>"/>

<category android:name="<category here>"/>

</intent-filter>

Here,
action — The general action to be performed

category — Gives additional information about the action to execute. For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level application, while CATEGORY_ALTERNATIVE means it should be included in a list of alternative actions the user can perform on a piece of data.

Note: you can also use application tab below the ‘AndroidManifest.xml’ file, and in ‘Application Nodes’ section click
‘Add’ button as shown in figure below and select the activity .

Application Node-Add Activity

Application Node-Add Activity

Next you can start this activity on any event as follows

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
CurrentActivity.this.startActivity(myIntent);

Here, you have to create and intent with CurrentActivity.this as first parameter
and the the next activity as second parameter.

After you have created the intent, you can start the new activity by calling
startActivity, on current Activity, with the created intent as parameter.

Categories: Android Tags: , ,
  • http://www.downstairzet.com Buddha Soumpholphakdy

    Thanks man. That is what I needed :)

  • Nils Thorell

    What is the best to pass a parameter to the new Activity?

  • Virendra Shakya

    Bonjour,
    thank you for short but sweet tutorial.
    Merci.

  • zeeshan

    @Nils Thorell
    Hi Nils,
    Suppose you want to pass parameters from an Activity ‘FirstActivity’ to another Activity ‘SecondActivity’.

    We can use bundle to pass parameters from ‘FirstActivity‘ to ‘SecondActivity‘. And then add this bundle to the intent, you are using to initiate activity ‘SecondActivity‘, as:

    Intent intent = new Intent(FirstActivity.this,SecondActivity.class);

    //Next create the bundle and initialize it
    Bundle bundle = new Bundle();

    //Add the parameters to bundle as
    bundle.putString(“NAME”,”my name”);

    bundle.putString(“COMPANY”,”wissen”);

    bundle.putInt(“AGE”,”22″);

    //Add this bundle to the intent
    intent.putExtras(bundle);

    //Start next activity
    FirstActivity.this.startActivity(intent);

    Now in ‘SecondActivity‘ we can retrieve the parameters values as:

    //First Extract the bundle from intent
    Bundle bundle = getIntent().getExtras();

    //Next extract the values using the key as
    String name = bundle.getString(“NAME”);
    String company = bundle.getString(“COMPANY”);
    String age = bundle.getInt(“AGE”);

  • tinyang

    Wonderful article! I have some questions though, it seems like the explicit intent is not specified in the manifest, but in the java code instead? Is that the best way to set up all explicit intents?

    I need to have one activity start another activity, should I do that only with an explicit intent? Because right now I do have an intent filter in my manifest for this application (see below).

    Notice how it has both intent.action.MAIN and intent.action.LAUNCHER. Would CATEGORY_ALTERNATIVE also apply to an app (for example, one choice of many to perform is to launch this activity) or does it just apply to data? Thanks!

  • tinyang

    tinyang :
    Wonderful article! I have some questions though, it seems like the explicit intent is not specified in the manifest, but in the java code instead? Is that the best way to set up all explicit intents?
    I need to have one activity start another activity, should I do that only with an explicit intent? Because right now I do have an intent filter in my manifest for this application (see below).
    Notice how it has both intent.action.MAIN and intent.action.LAUNCHER. Would CATEGORY_ALTERNATIVE also apply to an app (for example, one choice of many to perform is to launch this activity) or does it just apply to data? Thanks!

    Sorry, it cut out my manifest. Let me try again:

    activity android:name=”.MainMenu”
    android:label=”@string/app_name”
    intent-filter
    action android:name=”android.intent.action.MAIN”
    category android:name=”android.intent.category.LAUNCHER”
    /intent-filter
    /activity

  • zeeshan

    @tinyang
    Hi tinyang,

    The activity tag you post contains an action ‘MAIN’ and category ‘LAUNCHER’.

    This intent filter action ‘MAIN’ and category ‘LAUNCHER’, will create and icon of your application in the android device menu. and clicking on it will launch that activity and so is required.

    Also the intent-filter of ‘MAIN’ and ‘LAUNCHER’ should be in one activity only, otherwise then number of times this intent-filter appears in AndroidManifest.xml , that many times the icon will appear on the device menu.

  • Raghavendra

    Hi,
    It is grateful article. It helps me a lot. Thank you very much…….

  • http://thedevelopersinfo.wordpress.com/ sheff

    Hi. Great tutorial.

  • qlimax

    @zeeshan
    this stuff helps me a lot!
    Thank you !

  • David Scholberg

    Thank you so much for this! Because of this article, I learned in five minutes what I couldn’t learn in hours of digging through the Android documentation. You rule!

  • lapsus63

    Don’t forget to add
    Looper.prepare();
    before making the new Intent, in the case you are creating the Intent into a Thread.
    Thank you very much for this how-to !

  • Danilo Cubrovic

    Great tutorial.
    Thank you very much.

  • Gaurav

    Very handy n usefull tut :) Thanks a tonne !

  • http://www.pdxkoopans.com soch

    Thanks for explaining it.

  • http://norbdev.atw.hu NoRbDEV

    THX!!

    Very cool and simple tutorial!!

  • http://blog.yasirmturk.com Yacir M Turk

    This is a really cool article …but i m facing one problem my application contains many screens which i broke up into activities… now using this approach suppose i create first splash screen which does the initialization tasks.. then i load the next activity…. but now if the user presses the back button the splash screen is appeared again and user can do nothing except quiting it….

    how should i handle this specific thing ….thanx again

  • MQAndroid

    Very simple and usefull article. Thanks

  • Alan

    @Yacir M Turk
    Yacir,
    You need the splash screen to tell the system that it’s finished and to be removed from the activity stack:

    // in your splash screen activity
    Intent myIntent = new Intent(SplashScreen.this, NextActivity.class);
    startActivity(myIntent);
    finish(); // clears the splash screen from the stack

    Check out the Forwarding example in the android sdk samples.

  • http://icarez.wordpress.com/2010/02/10/android-lancer-une-nouvelle-activity/ Icarez’s Blog

    [...] http://www.androidcompetencycenter.com/2009/03/tutorial-how-to-start-a-new-activity/ Catégories: Android, Logiciels, Technologies Google [...]

  • sheik

    Hi,
    can anyone help me in this Q’s asked me in a interview ..

    How to start another activity without knowing the next activity class name .. for example . in the activity when we click on the url , it directs to the browser , something like that . hope am clear in asking the Q .

    thanks
    regards,
    Sheik

  • Miracle

    Actually, it’s very good!

  • raqz

    great article…but can you tel me how to return back to the main activity after completing the next activity…
    i am planning to code an application that involves different activites and returning back to main activity after the sub activity are complete..please guide..thanks

  • raqz

    Also..i want to pass objects through the bundle stuff…is that possible…?? pleaset let me know..thanks

  • mah

    raqz, you should be able to simply “finish();” in your next activity when it has completed, and whatever activity was before it should come to the front.

    As to passing objects, you need to make them Parcelable. Then you can use bundle.putParcelable() and bundle.getParcelable()

  • http://no Valentin Vázquez O.

    Tank u so much, it was so useful and just i wanted

  • WKRIP

    Thanks , this was helpful

  • http://rahulkrishnanblogs.wordpress.com Rahul Krishnan

    Hey.. thanks..that got me started with Android Intents :)

  • Soubhab Pathak

    Wonderful tutorials………….It saved my time….Thanks

  • Sevens

    Its very good tutorials and I have got relief from my headache and saved my time .
    And here i’m having some doubts on Android
    I’m new to android .
    what and all my doubts are :
    1.) CAN I Split the my web page with different different parts?
    like javascript frames and frameset.
    2.) if 1 Q is possible then .I have some buttons at my left panel with vertical layout ..and some buttons at top level with Horizontal layout.
    And if i click any buttons from either Horizontal Layout or Vertical layout..then hit ill hit server and get the data,that data would be display center of my web page without reloading ..my top
    horizontal/left vertical layout…
    I hopes my questions are clear and i can get rely soon.

    Thanks,
    Sevens.

  • mabodev

    Thanks a lot for that!! That’s absolutely brilliant!

  • Ramkumar

    Nice one.

  • http://lazyorchid.wordpress.com/2010/07/22/android-intents/ Lazy Orchid

    [...] Android Intents Thursday 22nd July 2010 @ 15:43 › tsmtom ↓ Leave a comment http://www.androidcompetencycenter.com/2009/03/tutorial-how-to-start-a-new-activity/ Categories: [...]

  • Haymi

    Thank you for the short tutorial.But i face a problem.My current activity is playing audio and i want to start another activity in the middle of the play and i also want to hear the music while doing the second activity(i.e two activities simultaneously).But an error msg comes.Can any one help me?

  • Fernando

    Hey dude i can’t star a new activity from an AlertDialog, y get the NullPointerException in starActivity while i tring, could you help me please??

  • Tiviess

    Instead of using the activity to play the audio file, run it through a service.

  • http://www.facebook.com/people/Axel-Bog-Andersen/1096122644 Axel Bøg Andersen

    Very helpful. Thanx a bunch!

  • Saikat

    delicious

  • Saikat

    delicious

  • Sa

    dur

  • http://profiles.google.com/ankit3385 ankit patel

    Hmm yammi it is working perfectly dear.
    i was stuck at this problem since last many days
    thanks bro

  • Michael

    Thank you!!!!!

  • Crevu

    Very good tutorial, it really helped !

  • http://www.facebook.com/Mike190683 Michael Unger

    Thanx. Just writing a mp3 player, and this tutorial helpt me a lot!

  • Backalleygentleman

    Thank you so much. Before reading this, I had an error because I didn’t fix my manifest.xml to include the “nextActivity”

  • Anonymous

     thanx mate, precise instructions without additional sh*t.!

  • Ryapreisner

    When you get to the next activity and request the Bundle from getIntet().getExtras, where is this done? Is this in the onCreate?

  • Sss

    thanks, this worked much better than sending the package name as a string

  • zzmaric

    Thanks. Very concise. By the way, I couldn’t log in to disqus with my Facebook account. It just said ‘An error occurred.’

  • zzmaric

    Thanks. Very concise. By the way, I couldn’t log in to disqus with my Facebook account. It just said ‘An error occurred.’

  • http://eazyigz.wordpress.com Igor Ganapolsky

    Do you speak English?

  • Burakehm

    ı want to take some values in my edit text and use on my other activity but when ı try to start my program.program has stop ahat can ı do for fix it please help me,ı want to take my float value and use other activity in the function but ı cant .

  • Himanshu

    Not Working for me… suggest an alternative

  • Mayuresh86

    nycc…

    thank you!

  • Winsontoh

    Hi can you give a more explicit example on how to do the activity? Currrently I am doing a search function where upon typing the keyword inside, it will preview a listview and upon clicking the result, it will direct them to page.