You are on page 1of 35

Android Message: How to send/receive

SMS using the built-in messaging


application in Android
This article is focused on the practicalities of sending and receiving text
and data messages within the Android system.
26

6414

Like (0)

(0)

Android offers full access to SMS functionality from our applications with the SMSManager.

Basically by using the SMS Manager, we can replace the native SMS application or create

new type of presentations that can send text messages, react to the received texts, or use

SMS as a data transport layer. SMS message delivery is not always timely, so SMS is not

really suitable for anything which requires real-time responsiveness.

Basically the widespread adoption of SMS networks make it particularly good tool for

delivering content to non-Android users and reducing the dependency on the third-party

servers. As a technology, SMS implements a mechanism that allows you to send text

messages to other mobile phone users, irrespective of whether they have Android

phones or not. SMS is supported by almost every phone on earth, so the latency is not an

issue, and updates are infrequent, in such situation SMS data messages are an excellent

process.
Sending SMS Messages:
Short Message Service messaging in Android is handled by the SmsManager. We can get a

reference to the SMS Manager by using the static method SMSManger.getDefault, that type

of protocol is shown below.

Listing 1: Creating SMS manager

SmsManager smsManager = SmsManager.getDefault();

Actually to send SMS messages our applications require the SEND_SMS permission. To

request this permission, add it to the manifest file through a uses-permission tag that is

shown below.

Listing 2: Setting permission

<uses-permission android:name=”android.permission.SEND_SMS”/> .

Sending Text Messages:


Our target is to send information in a text message format. Use sendTextMessage from the

SMS Manager, passing in the address (phone number) of our recipient and the text message

that we want to send, as shown in the snippet below:

Listing 3: Setting receiver and messages

String sendTo = “9231821234”;


String myMessage = “Android supports programmatic SMS messaging!”
smsManager.sendTextMessage(sendTo, null, myMessage, null, null);

Basically the final two parameters let you specify objectives of tracking the transmission and

successful delivery of our messages or text. We will also discuss the broadcast receivers

namespace and coding status in the next section.


Now here we will discuss the code that is generally built-in in our programming design when

we want to send message to our nearest friends etc.

Listing 4: Sample showing message creating

protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) findViewById(R.id.editTextSMS);
sendBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
sendSMSMessage();
}
});
}

The above method name is onCreate(Bundle savedInstanceState) and it is responsible for

setting up the buttons, fields, textboxes etc for showing and storing the data. This

sendSMSMessage(); method is used for generating the programming model of sending SMS

as well as data.

Listing 5: Sample showing message sending

protected void sendSMSMessage()


{
Log.info("Send SMS", "");
String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();
try
{
SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null,
message, null, null);
Toast.makeText(getApplicationContext(), "SMS
sent.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"SMS
failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}

The above method is used for sending messages from one system to another. This

programming model is totally based on try catch block. By using the try catch block, SMS

sent is written inside it for catching errors during execution.

Listing 6: Sample showing menu creation

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Basically when we create any SMS program, we also add menu items as per our

requirement. Here onCreateOptionsMenu (Menu menu) method is used to generate our

menu.
Figure 1: Shows the phone number and text messages option
Figure 2: Shows that receiver accepts the text message.

How to track and confirm SMS message delivery


It is one of the vital and important standard feature to track the transmission and delivery

of our outgoing SMS messages, implement and register Broadcast Receivers that listen for

the actions you specify and creating the Pending Intents you pass in to the

sendTextMessage method.

The first Pending Intent parameter, sentIntent, is fired when the message is either

successfully sent or fails to send. The result code for the Broadcast Receiver that receives

this Intent will be one of the following:

#No Function Application


1 Activity.RESULT_OK It is to indicate a successful
transmission.
2 SmsManager.RESULT_ERROR_GENERIC_FAILUR It is to indicate a nonspecific
E failure
3 SmsManager.RESULT_ERROR_RADIO_OFF When the connection radio is
turned off
4 SmsManager.RESULT_ERROR_NULL_PDU To indicate a PDU failure

Table 1: Shows functions and their applications

The second Pending Intent parameter, deliveryIntent, is fired only after the destination

recipient receives your SMS message.

The following code snippet shows a typical pattern for sending an SMS and monitoring the

success of its transmission and delivery:

Listing 7: Sample showing broadcast receiver

String SENT_SMS_ACTION = “SENT_SMS_ACTION”;


String DELIVERED_SMS_ACTION = “DELIVERED_SMS_ACTION”;

// create the sentIntent parameter


Intent sentIntent = new Intent (SENT_SMS_ACTION);
Pending Intentsent = PendingIntent.getBroadcast (getApplicationContext (), 0,
sentIntent, 0);

// create the delivery Intent parameter


Intent deliveryIntent = new Intent (DELIVERED_SMS_ACTION);
Pending Intentdeliver = PendingIntent.getBroadcast (getApplicationContext (),
0,deliveryIntent,0);

// Register the Broadcast Receivers


registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context _context, Intent _intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
[… send success actions … ];
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
[… generic failure actions … ];
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
[… Radio off failure actions …];
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
[… null PDU failure actions … ];
break;
}
}
},
new IntentFilter(SENT_SMS_ACTION));
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context _context, Intent _intent)
{
[… SMS delivered actions … ]
}
},
new IntentFilter(DELIVERED_SMS_ACTION));
// Send the message
smsManager.sendTextMessage(sendTo, null, myMessage, sentPI, deliverPI);

The above code describes the broadcast receiver and its details. The first four lines create

different types of intents like send intent and delivery intent etc. Next, the broadcast

receiver is registered by using registerReceiver() method. The switch-case statement inside

the receiver describes different types of messages. The transmission is monitored by using

these messages inside onReceive() method.

Monitoring Outgoing SMS Messages:


It is an important procedure that Android debugging bridge supports sending SMS messages

between multiple emulator instances. Now to send an SMS from one emulator to another,

you need to specify the port number of the target emulator as the “to” address. Actually the

android will automatically route our message to the target emulator instance, where it will

be handled as a normal Short Message Services.

Sending Data Messages:


We can send the binary data via Short Message Services by using the sendDataMessage

method on an SMS Manager. Actually the sendDataMessage method works much like

sendTextMessage; nevertheless it includes additional parameters for the destination port

and an array of the bytes that constitute the data which we want to send. The subsequent

skeleton code confirms the basic structure of sending a data message system:

Listing 8: Sample showing data message sending

//Syntax are given here


Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI =
PendingIntent.getBroadcast(getApplicationContext(),0,sentIntent,0);
short destinationPort = 80;
byte[] data = [ … our data or information store here … ];
smsManager.sendDataMessage(sendTo, null, destinationPort, data, sentPI, null);

The above code describes the process for sending data messages. Intent and port is

mentioned in the first three lines. In the 4th line the data is mentioned as an array of bytes.

Then this data is sent along with the port number, intent etc.

Emergency Responder SMS Example:


Emergency Responder is also very important part for our SMS service process. Through this

illustration, we will create an SMS application that turns an Android phone into an

emergency response system. Once it is complete, we can set our phone to automatically

respond to our friends and family members.

We will use location-based services to tell exactly where to find us. The robustness of the

SMS network infrastructure makes SMS an excellent option for applications like this where

reliability and accessibility are critical.

Process 1: Start by creating a new EmergencyResponder project that features an

EmergencyResponder Activity.

1. import android.app.Activity;

2. import android.app.PendingIntent;

3. import android.content.Context;

4. import android.content.Intent;

5. import android.content.IntentFilter;

6. import android.content.BroadcastReceiver;

7. import android.content.SharedPreferences;

8. import android.location.Address;

9. import android.location.Geocoder;

10. import android.location.Location;


11. import android.location.LocationManager;

12. import android.os.Bundle;

13. import android.telephony.gsm.SmsManager;

14. import android.telephony.gsm.SmsMessage;

15. import android.view.View;

16. import android.view.View.OnClickListener;

17. import android.widget.ArrayAdapter;

18. import android.widget.Button;

19. import android.widget.CheckBox;

20. import android.widget.ListView;

All the twenty import files which are mentioned here are interrelated with one another.

The import android.app.Activity application is working to generate the activity set, the

import android.content.BroadcastReceiver is used for the communication process, import

android.location.Location is used for location detection, import

android.telephony.gsm.SmsManager is used for communication with the telephone system,

and import android.widget.ArrayAdapter is used for ArrayAdapter system processing.

Process 2:

public class EmergencyResponder extends Activity


{
@Override
//Add permissions for the finding our location as well as sending and
receiving incoming //SMS messages to the project manifest.
<?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.paad.emergencyresponder”>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.EmergencyResponder”android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
<uses-permission
android:name=”android.permission.ACCESS_GPS”/>
<uses-permission android:name=”android.permission.ACCESS_LOCATION”/>
<uses-permission
android:name=”android.permission.RECEIVE_SMS”/>
<uses-permission android:name=”android.permission.SEND_SMS”/>
</manifest>

This above code is setting up for the emergency purpose message services.

Process 3:

This is modifying the main.xml layout resource. Include a List View to show the people

requesting a status update and a series of buttons that users can press to send/response

SMS messages. Use external resource references to fill in the button text; we will create

them in the following section:

Process 4:

This is the step four which is used to finalize the SMS program.

<?xml version=”1.0” encoding=”utf-8”?>


<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView
android:id=”@+id/labelRequestList”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”These people want to know if you’re ok”
android:layout_alignParentTop=”true”/>
<LinearLayout
android:id=”@+id/buttonLayout”
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:padding=”5px”
android:layout_alignParentBottom=”true”>
<CheckBox
android:id=”@+id/checkboxSendLocation”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Include Location in Reply”/>
<Button
android:id=”@+id/okButton”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/respondAllClearButtonText”/>
<Button
android:id=”@+id/notOkButton”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/respondMaydayButtonText”/>
<Button
android:id=”@+id/autoResponder”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Setup Auto Responder”/>
</LinearLayout>
<ListView
android:id=”@+id/myListView”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_below=”@id/labelRequestList”
android:layout_above=”@id/buttonLayout”/>
</RelativeLayout>

In the above program we are assigning some control points like labelRequestList,

buttonLayout, checkboxSendLocation, okButton , notOkButton, autoResponder, myListView.

These all are built-in here which controls the working of our SMS sending program blocks.

Actually we update the external strings.xml resource to include the program.zip file. We

should also define the text message when distinguishing requests for status responses.

<?xml version=”1.0” encoding=”utf-8”?>


<resources>
<string name=”app_name”>Emergency Responder</string>
<string name=”respondAllClearButtonText”> Yes I am fine don’t think about me.
</string>
<string name=”respondRaniydayButtonText”>RANIYDAY! RANIYDAY!
RANIYDAY!</string>
<string name=”respondAllClearText”> Yes I am fine don’t think about
me!</string>
<string name=”respondRaniydayText”>Tell Esha I love her.</string>
<string name=”querystring”>Are you fine and Ok?</string>
</resources>

This is the last step of the Graphical User Interface that we will complete.

In the modern mobile technology, SMS is very popular for sending information in a very fast

way. SMS does not wait for the receiver, as it is not like receiving phone calls. You just need

to send the text and rest will be handled by the system. So the flexibility of SMS makes it a

very good friend of the modern technology. Android application is also very popular for

different apps. One of the most important is SMS application.

Assumptions

The authors are assuming the reader has some basic knowledge of Android and have
all of the tools installed and working—specifically Eclipse, the Android SDK and the
Android ADT plug-in for Eclipse.

Readers may also benefit from reading our Quick Tip: Enabling Users to Send Email
From Your Android Applications – The Easy Way.

Step 0: Creating a Simple Android Project


Begin by creating a new Android project. You can also follow along using the source
code provided as a supplement to this tutorial.

Step 1: Designing the Form

First, you need to give some thought to want kind of data you want to collect from the
user. The form may have any number of fields. Consider the types of data you want to
collect and choose the appropriate type of control. For example:

 To collect text input, use EditText controls


 To limit the user to a fixed set of responses, use Spinner controls, similar to a
drop-down menu
 To collect boolean (yes/no) input, use CheckBox controls
 To allow the user to trigger events, use Button controls

For this tutorial, you will be designing a feedback form. This form collects five pieces of
data from the user:

 The user’s name (a string)


 The user’s email (a string)
 The type of feedback (options: Praise, Gripe, Suggestion or Bug)
 The feedback message (a string)
 Whether or not the user wants an email response (a boolean)

Step 2: Creating the Layout Resource

Begin by creating a layout resource for the form screen. The form will have a bunch of
fields, which could span more than a single screen (depending on the device screen
size), so you should consider wrapping the entire form within a ScrollView control to
enable scrollbars.
The ScrollView control must have exactly one child view, so consider which layout
control is most appropriate for the form you want to create. Forms are often contained
within a vertically oriented LinearLayout control, so that the form fields cascade down
the page vertically, one after another. This also helps the user’s focus move from field to
field naturally.

A simple form layout resource might look like this:

01
02 <?xml version="1.0" encoding="utf-8"?>
03 <ScrollView
04 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
05 android:layout_width="wrap_content"
06 android:layout_height="wrap_content"
07 android:scrollbars="vertical">
08 <LinearLayout
android:layout_width="fill_parent"
09
android:orientation="vertical"
10 android:layout_height="fill_parent">
11
12 <!--Put form controls here-->
13
14 </LinearLayout>
15 </ScrollView>
16

Step 3: Add a TextView Control (Form


Description)

Next, you need to add a TextView control within the LinearLayout control. The TextView
control called TextViewTitle displays the form description and purpose to the user. This
control displays a string resource called @string/feedbacktitle, which must be defined
within the /res/values/strings.xml string resource file.

Here is the XML to add to your form layout resource file:

1 <TextView
android:id="@+id/TextViewTitle"
2
android:layout_width="wrap_content"
3
4 android:layout_height="wrap_content"
android:text="@string/feedbacktitle"
5 android:textSize="10pt">
6 </TextView>
7

Step 4: Add an EditText Control (Name)

Now you need to add your first EditText control just below the TextView control you just
created. This EditText control called EditTextName acts as a form field for the user’s
name. You can use the hint attribute to supply a string to display in the EditText control
when it’s empty (e.g. “Type your name here…”). You can also set the inputType
attribute of the EditText control to apply name entering logic.

Here is the XML to add to your form layout resource file:

1 <EditText
2 android:id="@+id/EditTextName"
3 android:layout_height="wrap_content"
4 android:hint="@string/feedbackname"
5 android:inputType="textPersonName"
android:layout_width="fill_parent">
6 </EditText>
7

Step 5: Add another EditText Control (Email)

Next, you need to add your second EditText control just below the EditText control
called EditTextName. This EditText control called EditTextEmail acts as a form field for
the user’s email address. Again, set the hint attribute to supply a string to display in the
EditText control when it’s empty. This time, set the inputType attribute of the EditText
control to textEmailAddress, which will make entering emails easier on the user.

Here is the XML to add to your form layout resource file:


1 <EditText
2 android:id="@+id/EditTextEmail"
3 android:layout_height="wrap_content"
4 android:hint="@string/feedbackemail"
5 android:inputType="textEmailAddress"
android:layout_width="fill_parent">
6 </EditText>
7

Step 6: Add a Spinner Control (Feedback Type)

Next, you need to add a Spinner control just below the EditText control you just created.
This Spinner control called SpinnerFeedbackType allows the user to select the type of
feedback from a fixed list of options (Praise, Gripe, Suggestion, or Bug).
First, you need to define these choices as individual string resources in
the strings.xmlresource file.

1
<?xml version="1.0" encoding="utf-8"?>
2 <resources>
3 <!--Other string resources also defined in this file… -->
4 <string name="feedbacktype1">Praise</string>
5 <string name="feedbacktype2">Gripe</string>
<string name="feedbacktype3">Suggestion</string>
6
<string name="feedbacktype4">Bug</string>
7 </resources>
8
Next, create a string array resource using the individual string resources as follows in
/res/values/arrays.xml:

1
<?xml version="1.0" encoding="utf-8"?>
2 <resources>
3 <string-array name="feedbacktypelist">
4 <item>@string/feedbacktype1</item>
5 <item>@string/feedbacktype2</item>
6 <item>@string/feedbacktype3</item>
<item>@string/feedbacktype4</item>
7 </string-array>
8 </resources>
9
Now you are ready to configure the Spinner control in your form layout. Begin by
supplying the prompt attribute, which will provide a helpful string at the top of the
Spinner control. Next, specify the list of string choices using the entries attribute—
specifically, set the entries attribute to the string array you just defined:
@array/feedbacktypelist.

Here is the XML to add to your form layout resource file:

1 <Spinner
2 android:id="@+id/SpinnerFeedbackType"
3 android:layout_height="wrap_content"
4 android:prompt="@string/feedbacktype"
5 android:layout_width="fill_parent"
android:entries="@array/feedbacktypelist">
6 </Spinner>
7
Step 7: Add a Multi-Line EditText Control
(Feedback)

Next, you need to add one more EditText control just below the Spinner control. This
EditText control called EditTextFeedbackBody acts as a form field for the feedback text.
Again, set the hint attribute to supply a string to display in the EditText control when it’s
empty. This time you want to give the user ample space to write praise, gripes,
suggestions, or describe bugs in the application. Therefore, you may want to set the
inputType attribute of the EditText control to textMultiLine and specify the number of
lines to draw using the lines attribute.

Here is the XML to add to your form layout resource file:

1
<EditText
2 android:id="@+id/EditTextFeedbackBody"
3 android:layout_height="wrap_content"
4 android:hint="@string/feedbackbody"
5 android:inputType="textMultiLine"
android:lines="5"
6
android:layout_width="fill_parent">
7 </EditText>
8

Step 8: Add a CheckBox Control

Next, you need to add a CheckBox control just below the EditText control you just
created. This CheckBox control called CheckBoxResponse allows the user to choose
whether or not they want to request an email response from the app developer. You can
use the text attribute to supply a string to display next to the CheckBox control.

Here is the XML to add to your form layout resource file:

1 <CheckBox
android:id="@+id/CheckBoxResponse"
2
android:layout_height="wrap_content"
3 android:text="@string/feedbackresponse"
4 android:layout_width="fill_parent">
5 </CheckBox>
6

Step 9: Add a Button Control

Finally, you are ready to finish off the form with a Button control. If you want to have a
button with text on it, use the Button control; if you prefer a button with a picture on it,
use an ImageButton control instead. We will use a Button control here. First, set the text
on the Button control using the text attribute. Next, you can easily register a click
handler (as opposed to registering it programmatically in your Activity) for your Button
control using the onClick attribute.

Here is the XML to add to your form layout resource file:

1 <Button
2 android:id="@+id/ButtonSendFeedback"
3 android:layout_height="wrap_content"
4 android:text="@string/feedbackbutton"
5 android:onClick="sendFeedback"
android:layout_width="fill_parent">
6 </Button>
7
Excellent! You’ve finished designing your form. Now, all you need to do is implement
the sendFeedback() method in your Activity.
Step 10: Implement a Button click handler

In the Button control, you specified the onClick attribute as sendFeedback. Now you will
need to implement a method called sendFeedback() within your Activity class. For
example:

public void sendFeedback(View button) {


// Do click handling here
}

Step 11: Reading Input from EditText Controls

Now that your form is designed and the controls have been implemented, you next need
to collect the form data from the individual fields when the Button control is clicked.

For an EditText control, you use the getText() method.

final EditText nameField = (EditText)


findViewById(R.id.EditTextName);
String name = nameField.getText().toString();

final EditText emailField = (EditText)


findViewById(R.id.EditTextEmail);
String email = emailField.getText().toString();

final EditText feedbackField = (EditText)


findViewById(R.id.EditTextFeedbackBody);
String feedback = feedbackField.getText().toString();

Step 12: Reading Input From Spinner Controls


Your form included a Spinner control. You use the getSelectedItem() method to read the
data from this form control.

final Spinner feedbackSpinner = (Spinner)


findViewById(R.id.SpinnerFeedbackType);
String feedbackType =
feedbackSpinner.getSelectedItem().toString();
In this case, the selected item in the Spinner control is the String chosen by the user of
the selected item.

Step 13: Reading Input from CheckBox Controls

Finally, your form included a CheckBox control. In this case, the result is just a flag to
tell your application if the box was checked or not.

final CheckBox responseCheckbox = (CheckBox)


findViewById(R.id.CheckBoxResponse);
boolean bRequiresResponse = responseCheckbox.isChecked();
You can use this Boolean value however you want in your app.

Step 14: Generate the Appropriate Email Details

Now that you’ve got all your form data, you’re ready to craft a message. Simply process
all the data fields and build an appropriate feedback message. For example, you might
use some fields in the message subject, and others in the message body. You can use
format strings to help build the appropriate strings, the specifics of which will be
discussed in an upcoming quick tip.
Conclusion

In this tutorial, you learned how to use various types of input controls to design a
feedback form within an Android application. The EditText control is versatile and
powerful, allowing for many different types of text and freeform input. The Spinner and
Checkbox controls help limit the user’s input to a specific set of responses. The Button
control is a simple way to generate an event to process the form input.

There are many other controls worth exploring for use within forms. There is a lot more
we could cover regarding good form design, how form controls fit into the Activity
lifecycle, and how input methods and such factor into things, but for now, focus on
gaining a good handle on the basics of form controls and how to use them.

We hope you enjoyed this tutorial and look forward to your feedback!

Designing a simple form in android


Posted on February 22, 2013 by Sudharshan

A Form is used to interact with the user. To design a form we will have to start with the various
elements of a form. Consider a Registration form where we get user details, validate it and register
with our service. We use basic details like username,password and contact number. To design such a
form we will have to use the following views or elements:

 TextView(label) which can be used to display plain text


 EditText(TextBox) which are used to get values from the user
 Spinners(Drop-down listbox) for selecting an option from the list
 Button to call a function or event
 RadioButton, CheckBox for selecting options

Here is a sample register form:


Here is the code for the above form:

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView_enter_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:textSize="18sp"
android:text="@string/enter_name" />

<EditText
android:id="@+id/editText_enter_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView_enter_name"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:inputType="text"
android:textSize="17sp"
android:ems="10" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/textView_enter_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText_enter_name"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:textSize="18sp"
android:text="@string/enter_user_name" />

<EditText
android:id="@+id/editText_enter_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView_enter_username"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:inputType="text"
android:textSize="17sp"
android:ems="10" >
</EditText>

<TextView
android:id="@+id/textView_enter_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText_enter_username"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:textSize="18sp"
android:text="@string/enter_password" />

<EditText
android:id="@+id/editText_enter_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView_enter_password"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:inputType="textPassword"
android:textSize="17sp"
android:ems="10" >
</EditText>

<TextView
android:id="@+id/textView_enter_rpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText_enter_password"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:textSize="18sp"
android:text="@string/enter_rpassword" />

<EditText
android:id="@+id/editText_enter_rpassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView_enter_rpassword"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:inputType="textPassword"
android:textSize="17sp"
android:ems="10" >
</EditText>

<Button
android:id="@+id/button_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText_enter_rpassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="@string/register" />

</RelativeLayout>

There are various attributes that we are dealing with.The text size,color and style can be altered for
each of the views.The <TextView></TextView> tag is used to define a label or textview. The
various attributes used to format text are:

android:text="[Enter text here]"

android:textSize="[font size in sp]"

android:textColor="[hex-code or
pre-defined android color using @android:color/(color-name)]"

android:textStyle="[specify normal bold italics]"android:typeface="[pre-defined font]"


The text value set to the TextView can be specified directly within double quotes, but it is highly
recommended to reference it form strings.xml. The strings.xmlconsists of all the strings or text
within the app and any change made here is reflected throughout the app.

These are the same with EditTexts or TextBoxes. In addition you must also specify the input type as
either plain text or password or a phone number etc.

Note: “We are using Relative Layout here!”

So it is really important to specify the view id as each item is relative to the other. Any change in id
after positioning can cause other dependent views to disappear or stick to the top of the screen. This
is because we are positioning relative as in android:layout_below=”some_id”. If this id changes or
doesn’t exist then it causes the view to disappear. It is very crucial that we change it everywhere in
the layout.

In addition to view position there is one very important role played by android:id attribute. The id
identifies each view uniquely and this is used in java classes to refer the various elements. It is also
the responsibility of the developer to avoid naming conflicts and use unique identifiers for each view.

Reading Input from Forms:

Here is a simple activity to handle the form. An activity is created by default. We need to define the
form elements and reference it.
TextView textView_name,textView_password,
textView_username,textView_repeat_password;
EditText editText_name,editText_password,
editText_username,editText_repeat_password;
Button button_register;

Import form elements (press Ctrl+Shift+O to import).


Referencing Views & Set OnClickListener:

textView_name=(TextView) findViewById(R.id.textView_enter_name);
textView_username=(TextView) findViewById(R.id.textView_enter_username);
textView_password=(TextView) findViewById(R.id.textView_enter_password);
textView_repeat_password=(TextView) findViewById(R.id.textView_enter_rpassword);

editText_name=(EditText) findViewById(R.id.editText_enter_name);
editText_username=(EditText) findViewById(R.id.editText_enter_username);
editText_password=(EditText) findViewById(R.id.editText_enter_password);
editText_repeat_password=(EditText) findViewById(R.id.editText_enter_rpassword);

button_register=(Button) findViewById(R.id.button_register);

The id provided should be same as provided in the layout.

To handle
button click we use button,setOnClickListener(listener).

button_register.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {

}
});

Here is a better way to implement OnClick event.

button_register.setOnClickListener(this);

@Override
public void onClick(View arg0) {
}

All we need to do is to let the Class implement OnClickListener.

public class MainActivity extends Activity implements OnClickListener

To handle OnClick for multiple buttons we can switch between different ids.Anddon’t forget to
include break statement.

@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.button_register:
break;
}

Here is the complete code to handle register form.

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {

TextView
textView_name,textView_password,textView_username,textView_repeat_password;
EditText
editText_name,editText_password,editText_username,editText_repeat_password;
Button button_register;
String username="",name="",password="",repeat_password="";

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

textView_name=(TextView) findViewById(R.id.textView_enter_name);
textView_username=(TextView) findViewById(R.id.textView_enter_username);
textView_password=(TextView) findViewById(R.id.textView_enter_password);
textView_repeat_password=(TextView)
findViewById(R.id.textView_enter_rpassword);

editText_name=(EditText) findViewById(R.id.editText_enter_name);
editText_username=(EditText) findViewById(R.id.editText_enter_username);
editText_password=(EditText) findViewById(R.id.editText_enter_password);
editText_repeat_password=(EditText)
findViewById(R.id.editText_enter_rpassword);

button_register=(Button) findViewById(R.id.button_register);
button_register.setOnClickListener(this);
}

@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;
}

@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.button_register:
//Get Input From EditText
name=editText_name.getText().toString().trim();
username=editText_username.getText().toString().trim();
password=editText_password.getText().toString();
repeat_password=editText_repeat_password.getText().toString();

//Validate the Input


if(name.length()>0 && username.length()>0 && password.length()>0 &&
repeat_password.length()>0){
if(password.equals(repeat_password))
{
//Do Registration here
}
else
{
Toast.makeText(getApplicationContext(), "Oops! Something Went
Wrong!",
Toast.LENGTH_SHORT).show();
}
}

break;
}
}
}

OnClick we get text from editText convert toString() and trim() it.trim() is used to remove extra
spaces at the beginning and end of the string. If the length is greater than 0 it is not empty and valid.
We can register with server here. Otherwise we Toast an error message. Toast notifications are
nothing but popups to display messages.

You might also like