Android development primer: Multiple Screen Support for Android, using Intents

This entry is part 6 of 50 in the series Android Development Primer

We saw that on creating an Android Application Project, a skeleton “Hello World” application is created. The “Hello World” module is always the first step to learning anything. I’m sure you did a Hello World program when you were learning your first programming language. Quite boring isn’t it? Well, let’s get a bit creative.

We will add a few elements to our application and see how they work.

Create a new application project or edit the Hello World Application. Open up the MainActivity.java file and activity_main.xml and get ready for some coding.

If you have a problem while adding code snippets to you code, please have a look at the complete code at the bottom.

In the activity_main.xml follow the below steps:

  • Drag and drop an EditText from the Palette on the left.
  • Drag and drop a Button from the Palette on the left.
  • Click on the EditText and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the EditText to “@+id/et” and click Yes/OK on any dialog that appears. Remember the name.
  • Click on the Button and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the Button to “@+id/but” and click Yes/OK on any dialog that appears. Remember the name.
  • For now, leave the EditText and the Button in their respective places. We will concentrate on how to make them work and not how to place them in the layout.

Save the activity_main.xml.
Now follow the below steps carefully:

  • Navigate to <yourpackagename> -> src. Right Click on <com.yourname.yourappname> and select New -> Class.
  • You are creating a new Class. In the Name field enter Second.
  • In the Superclass browse and type Activity. Select the android.app.activity. This makes your class an Activity.
  • Hit Finish and you the class opens up.
  • Navigate to <yourpackagename> -> res -> layout. Right Click on <com.yourname.yourappname> and select New -> Android XML File.
  • Name it second and choose relative layout from the Root Element list.
  • Hit Finish and the XML file opens up.

In the Second.java file add the following code inside the class.

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}

If you have read my previous posts you will know exactly what we are doing here.

Now open second.xml and follow the below steps:

  • Drag and drop a TextView and change the Id attribute to “@+id/tv”.
  • Enter in the Text attribute – “This is the second Activity.”

Save second.xml. Switch over to MainActivity.java and add the following code in the onCreate() function.

Button but = (Button) findViewById(R.id.but);
  EditText et = (EditText) findViewById(R.id.et);
  but.setOnClickListener(new OnClickListener()
 {
  public void onClick(View v)
 {
 Intent intent = new Intent(MainActivity.this,Second.class);
 startActivity(intent);
 }
 }
 );


As you type in the first statement, you’ll notice that Eclipse places a small cross so as to indicate there is an error in that line. What is the error? We have not imported the Android Button widget in our activity and so Eclipse doesn’t know what we mean when we type in “Button”. Hit Ctrl+1 on your keyboard. This is a shortcut to bring up suggested fixes to the errors. Select Import ‘Button’ (android.widget). You will now see that the statement just after the ‘=’ symbol is now erroneous. Hit Ctrl+1 again and select Add cast to ‘Button’. This way we have used type casting and import statements with which you must already be familiar from your Java knowledge. Do the same for the EditText statement.

  • OnClickListener() :  This adds a listener to the button that triggers when it is clicked
  • OnClick() : Holds the set of instructions that need to be executed when the button is clicked
  • Intent : This is a very important feature of Android. For the time being, it’ll be sufficient for you to know that an Intent is used to call other Activities. We can also pass data using this across activities. We’ll see this in a while. The syntax of the constructor is new Intent(<currentactivityobject>, <destinationactivityclass>). The object of current activity is MainActivity.this and the class of the destination activity is Second.class.
  • startActivity() : It is used to start off a new activity while pushing the current one to the Back Stack. It takes an intent as an argument.

What we’ve done is we’ve added a button and configured it to fire the Second Activity when clicked. Run this application using the emulator. When the MainActivity is up and you click the button to go to the second Activity, your application will crash unexpectedly. Why? Because we have not added the Second activity to the AndroidManifest.xml file.

How do you get to know what went wrong? Well, here’s how. On the top right you can see Java and DDMS. DDMS (Dalvik Debug Monitor Server) tells you exactly what went wrong. Click on it and scroll to the top of the group of lines in red. You will see ActivityNotFoundException. It also says – “Have you declared this activity in your AndroidManifest.xml?”. So that’s how we know that we haven’t declared the Second activity in the Android Manifest file.

The Android Manifest file needs to recognize each and every activity in your application.

  • Open up AndroidManifest.xml file from the project contents list and from the tabs at the bottom select AndroidManifest.xml
  • Just before </application> add this – <activity android:name=”.Second” />
  • Save.

Launch the application again and this time it should work just fine. 🙂

You must be wondering why we did not make use of the EditText that we added to the layout. I told you before that we can send data across activities using Intents. That is preciseld what this EditText is for. Here we go.

  • Add this line in the MainActivity.java before the startActivity() function :-

    intent.putExtra("data", et.getText().toString());
    



  • Add the following lines in Second.java after the setContentView() function :
    TextView tv = (TextView) findViewById(R.id.tv);
     tv.setText(getIntent().getStringExtra("data"));
    

As you can see we can set the text to be displayed in the TextView from java too and this takes precedence over the xml.
What we have done here is that we will be displaying whatever text the user enters in the MainActivity in the Second Activity. Launch the application and see it work.

img1    img2

COMPLETE SOURCE CODE :

MainActivity.java

package com.nero.myfirstapp;

import android.os.Bundle;
 import android.app.Activity;
 import android.content.Intent;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;

public class Main extends Activity {

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Button but = (Button) findViewById(R.id.but);
 final EditText et = (EditText) findViewById(R.id.et);
 but.setOnClickListener(new OnClickListener() {

@Override
 public void onClick(View v) {
 Intent intent = new Intent(Main.this,Second.class);
 intent.putExtra("data", et.getText().toString());
 startActivity(intent);
 }
 });
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
 }
 }

Second.java

package com.nero.myfirstapp;

import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;

public class Second extends Activity {
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.second);
 TextView tv = (TextView) findViewById(R.id.tv);
 tv.setText(getIntent().getStringExtra("data"));
 }
 }

activity_main.xml

<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" >

<EditText
 android:id="@+id/et"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_marginLeft="30dp"
 android:ems="10" >

<requestFocus />
 </EditText>

<Button
 android:id="@+id/but"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignLeft="@+id/et"
 android:layout_below="@+id/et"
 android:layout_marginLeft="53dp"
 android:text="Button" />

</RelativeLayout>

second.xml

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

<TextView
 android:id="@+id/tv"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentTop="true"
 android:text="This is the second Activity" />

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nero.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
 android:minSdkVersion="7"
 android:targetSdkVersion="17" />

<application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.nero.myfirstapp.Main"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity android:name=".Second" />
 </application>

</manifest>
Series Navigation<< Android development primer: Layout elements in AndroidAndroid development primer: Looking into Eclipse IDE >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

41,055 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>