Android Essentials: Creating Simple User Forms

Android Essentials: Creating Simple User Forms

Tutorial Details
  • Technology: Eclipse + Android SDK
  • Difficulty: Beginner
  • Completion Time: 30 - 45 Minutes
This entry is part 1 of 14 in the series Android Essentials

Android applications often rely upon data supplied by users. This tutorial walks you through the creation and use of a number of the most common controls used to collect data from the user, including:

  • The EditText control
  • The Spinner control
  • The Checkbox control
  • The Button control

For this tutorial, you design and implement a form within your Android application which allows the user to supply important feedback to the developer. The user is given a number of options for submitting different types of feedback. This feedback can then be sent to the developer as an email. The form you create will ultimately look like this:

Android SDK: Creating Forms

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:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">
    <LinearLayout
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:layout_height="fill_parent">
<!--Put form controls here-->
    </LinearLayout>
</ScrollView>

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:

<TextView
    android:id="@+id/TextViewTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/feedbacktitle"
    android:textSize="10pt">
</TextView>

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:

<EditText
    android:id="@+id/EditTextName"
    android:layout_height="wrap_content"
    android:hint="@string/feedbackname"
    android:inputType="textPersonName"
    android:layout_width="fill_parent">
</EditText>

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:

<EditText
    android:id="@+id/EditTextEmail"
    android:layout_height="wrap_content"
    android:hint="@string/feedbackemail"
    android:inputType="textEmailAddress"
    android:layout_width="fill_parent">
</EditText>

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).

Android SDK: Creating Forms

First, you need to define these choices as individual string resources in the strings.xml resource file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!--Other string resources also defined in this file… -->
	<string name="feedbacktype1">Praise</string>
	<string name="feedbacktype2">Gripe</string>
	<string name="feedbacktype3">Suggestion</string>
	<string name="feedbacktype4">Bug</string>
</resources>

Next, create a string array resource using the individual string resources as follows in /res/values/arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="feedbacktypelist">
		<item>@string/feedbacktype1</item>
		<item>@string/feedbacktype2</item>
		<item>@string/feedbacktype3</item>
		<item>@string/feedbacktype4</item>
	</string-array>
</resources>

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:

<Spinner
    android:id="@+id/SpinnerFeedbackType"
    android:layout_height="wrap_content"
    android:prompt="@string/feedbacktype"
    android:layout_width="fill_parent"
    android:entries="@array/feedbacktypelist">
</Spinner>

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:

<EditText
    android:id="@+id/EditTextFeedbackBody"
    android:layout_height="wrap_content"
    android:hint="@string/feedbackbody"
    android:inputType="textMultiLine"
    android:lines="5"
    android:layout_width="fill_parent">
</EditText>

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:

<CheckBox
    android:id="@+id/CheckBoxResponse"
    android:layout_height="wrap_content"
    android:text="@string/feedbackresponse"
    android:layout_width="fill_parent">
</CheckBox>

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:

<Button
    android:id="@+id/ButtonSendFeedback"
    android:layout_height="wrap_content"
    android:text="@string/feedbackbutton"
    android:onClick="sendFeedback"
    android:layout_width="fill_parent">
</Button>

Excellent! You’ve finished designing your form. Now, all you need to do is implement the sendFeedback() method in your Activity.

Android SDK: Creating Forms

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.

Android SDK: Creating Forms

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!

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Series NavigationAndroid Essentials: Using the Contact Picker»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Siegfried

    Thanks for the info!

    Just a side note: looks like there is a <!–more–> missing somewhere in this article

    • http://androidbook.blogspot.com/ Shane Conder & L
      Author

      A missing what?

      • Siegfried

        Sorry, it's a "more" tag, because the article was showing up full on MobileTuts first page.

        Let's see if wraping in code tags it appears:

        <code><!–more–></code>

      • Mayank

        for those for whom the applcation is crashing change this in code from

        plain/text to
        text/plain

        Thanks
        Mike

    • http://androidbook.blogspot.com/ Shane Conder & L
      Author

      Apparently not. But, as it turns out, it wasn't a missing more tag — it was whitespace in it. It's not detected properly if it has whitespace in it. Oh well. Thanks for pointing it out! :)

  • http://michaelkral.com Michael Kral

    This is a really cool tut, glad to see continuing android tutorials.

  • http://fermindiaz.wordpress.com/ Fermin Diaz

    Hi there, nice tutorial, congrats, If you could, I’ll like that you make a video tut. where we can see the detailed explanation about this tut. Many Thanks.

  • quixotic

    Very nicely done tutorial! So far the one I’ve learned the most from. Thanks!!

  • http://www.dekwant.eu Marc

    Very clean and clear written article about the creation of forms in Android.
    I have written some supporting classes to support the lack of form validation. It contains a validator interface, an abstract inplementation,a validationresult class and 2 examples of custom implemented validations. 1 for regular expressions on text and a simple one to check if a checkbox is checked.

  • Sathish

    Hi

    Nice tutorial…

  • Sathish

    Hi

    Can i know how to connect mysql database to android application and how to read xml file in webview form ( it should read HTML TAGS ).

    I am searching code for long time.

  • Ankan

    Nice one , but please do tell how to enter these values in the database too !!

  • priya

    Really nice tutorial, can you plz… show us HOW TO SAVE, VIEW, DELETE & UPDATING THE VALUES. thnxz

  • Kunal

    Any similar tutorial to build forms from xml in iPad or iPhone ??

  • http://donnola.u-lost.net/feed u-lost

    cmon with more android… loved this article, just to change lang for a while it is “chiaro semplice e scritto bene”… we want more about layoutting android. there’s not much about layout on stackoverflow….

    kutgw!

    giacomo

  • Matt

    I’m sorry but is there something wrong with the source file link that you put up. I downloaded everything and it doesn’t contain anything that is in this tut, I mean literally nothing that you’ve done here is in there. Am I not getting to the right site?

  • http://www.poraddarky.cz Dárky

    Thanks you very much for this tutorial – simple and very useful!

  • KC

    Very useful tutorial. Thanks very much.

  • gicko@my

    awesome tutorial….but,how to connect with sqlite database? it is posibble? if posibble,can u show how to do it..

  • http://patmahoneyjr.com Patrick Mahoney

    I needed to take input from an EditText in my app, and found this so it’s great! I’m just wondering though, why does the EditText have to be final?

  • donut

    hi friends i ve jus now started creating a new app and my app contains 5 forms.here is my question how to create 2nd form

  • Dhruvisha

    This article is great for beginners.
    Very nice afford ans looking forward for more articles like this.

  • Arun

    Really very good stuff for the beginners . i love it

  • http://www.yourdigitalspace.com Swamykant

    Very useful article for beginners. thanks for share.

  • http://www.mobosurvey.com Tuan Bui

    if you need to create online forms that works on mobile phones, I recommend checking out http://www.mobosurvey.com. MoboSurvey’s goal is to make survey/form creation, distribution, and data mining a seamless process for our customers. Create free online surveys or questionaires that are accessible from any internet capable devices. Work on smart phones, tablets, and desktops.

  • Rajani

    nice tutorial

  • Yana

    Hi! I have downloaded the source code and imported it in Eclipse. I was able to run it in my emulator but when I click “Send” in feedback, it just force closes. Why is this happening? What can be my solution for this? Thanks!

  • Helen

    Regarding the spinner…
    How would I detect the difference between these 2:

    1. The spinner is displayed to the user with item 7 already picked, and he clicks “7″.
    2. The spinner is displayed to the user with item 7 already picked, and he picks a different value.

    #1 never seems to trigger any event, so it’s impossible to do.

    Help!

    • http://n/a Justin

      Helen, email me I will show you my source code. I am able to run the code (emulator & AVD) and select from spinner.

      I have a question regarding the button event handler. If I want to submit this form, and have it sent to ‘test@email.com’ what is the code? I am new to programming, and find the absence of this code (step 14) crippling! lol I would appreciate any help, thanks guys.

      • Justin

        Also, I forgot to mention, aside from the Last step, this was a great article!

  • matt

    Is there any way to add a file upload field like in an HTML form..???? On selecting it… i should be able to select a file from the memory…. I’ve seen tutorials that tell how to upload a file but i still have no idea how to prepare a form for this….

  • Dinu

    Hi ,

    Its been a very nice tutorial and i am actually a beginner to android development. Followed each and every step of this tutorial but i have being struch with the following error ……”Unfortunately Message Launcher has been Stopped”. Please Provide me if anyone faced the same problem

  • Student

    Hey great tutorial! But how do I download this tutorial? I couldn’t get it running properly.. Is there a link ? or can anyone send me? thank you in advance :)

  • abraham

    first of, your tutorials are awesome!

    i got the form to work, however, when i click the send feedback button, and choose gmail app, the body of the email only gets populated with the first string from:

    String message = formatFeedbackMessage(feedbackType, name,
    email, feedback, bRequiresResponse);

    if i rearrange the order of the the strings, example formatFeedbackMessage(name, email…..) or (email, name…..) then the message body will change to the first string.

    any idea what i could be doing wrong?

    thanks!

  • http://www.prasannajeetpani.in Prasannajeet Pani

    The tutorial is perfect. But when I test it in my Samsung Galaxy S2 editTextFeedbackBody doesn’t allow the sentences to start with a capital letter by default.

    When i try to introduce android:inputType=”textCapSentences” it loses its multiline look. Can you please provide a solution to it?

  • Félix

    Prasannajeet Pani, separate the two by | , like so:

    android:inputType=”textMultiLine|textCapSentences”

    Worked for me ;)

    Ps: Never mind my previous post, figured it out, missing a lot of import statements.

  • Rana Zain

    very nice keep it up.

  • http://www.facebook.com/maritova Daniel Andersen

    Excellent tutorial! One reason why it’s so good is that it doesn’t just tell what to do, but why a developer might choose to do it that way.

  • vino

    where did u get the source code for this project?

  • Ronnie

    i dont understand what is XML doing. Can anyone explain it?

  • kais

    hi! shows how to create and handle run trougth page form in android.