Wednesday, June 25, 2014

II. Calling a new Activity Android

To start a new activity in android, we use the intent class.

For example. We have a button that executes a method switchScreen(View view) when clicked.

on switchScreen(View view), we are going to start a new activity.
It should look something like this.

public void switchScreen(View view)
{
    Intent intent = new Intent(this, SecondActivity.class); //Creates a new instance of SecondActivity
    startActivity(intent);//Starts the intent

//NOTE: To use Intent class, we must import the intent. Simple click F2 with the intent and import it.
//Or in Eclipse, press shift +o to import missing packages.
}

putting few content with the content.

When starting intents, we can send some values with it.
This values can be fetch on the SecondActivityClass..

To put some values with the intent, we are going to use PutExtra.

Intent intent = new Intent(this, SecondActivity.class); //Creates a new instance of SecondActivity
//intent.putExtra("key","value");  key is the name of the holder. for example categorid, value is value itself. ex: 1065
intent.putExtra("categoryid", "1065"); //set an extra message or value with the intent.
startActivity(intent);//Starts the intent


To fetch the values of the intent. We are going to fetch it with the OnCreate method of the SecondActivity.java

Here's the syntax.
Bundle bundle = new Bundle();
Intent FirstClassIntent = getIntent();
bundle = FirstClassIntent.GetExtra();

String catid = bundle.getString("categoryid");


No comments: