Android Development 101- Part 2:Graphical Elements

In this tutorial, we will be continuing from where we left off with the “hello world” application.  This time adding a graphical user interface (GUI) and a “toast”. The GUI will consist of a button, textbox and a label. The “toast” will be issued onto the screen when the button is pressed.

Some may wonder what a toast is.  Well, for non-programmers, a toast is a text notification that for the most part is used only to display an error on the screen (I am a big fan of using toasts instead of an alert on the screen as its less intrusive).  For this article we will use a toast to display a message on the screen that will take the text in the textbox and issue a “Hello Greg” onto the bottom of the screen.  After this article completed you will be able to successfully make toast commands, design the layout of the hello world program, and pull text from a textbox.

We are going to start off by copy our existing Hello World project so that we can use the original in every way but have two separate projects to show the difference and both can be used as references.  To do this we will right click on the root of our HelloWorld project in the right hand pane (Navigation Explorer), navigate to copy (not Copy Qualified Name) and click it.  Then find a blank space in the Navigation Explorer, right click again and click paste.  You will be asked to supply a new name for this project and whether to use the default location.  We will name the new project ImprovedHelloWorld and we will leave the checkbox checked that says “use default location”.  Press OK and the new project will be generated from the old one.

The first thing we are going to accomplish is changing the strings.xml file to add another node under app_name.  We will do this by copying the node above it and pasting the copied material directly under the last </string> element.  Then we will change the name of the string to press and in between we will write Press Me!.  Next we will alter the hello node and change the text to say Enter Your Name Here: instead of Hello Android, Hello World!. This being accomplished we now need to design the GUI (Graphical User Interface).

To do this navigate to main.xml and we are going to go over what everything does up to this point.  We first off have a node called LinearLayout which essentially creates a space for adding objects such as textboxes, buttons and the like and will format the layout for us.  So LinearLayout will organize one thing right after the other in a one column and one row type of deal.  Next we have a TextView which in any other label we could call a label.  Now to go over what all of the parameters are in the nodes we just mentioned.  android:layout_width & android:layout_height are used to determine what will happen to an object when it is used within a layout.  There are two options when using this and they are fill_parent or wrap_content.  fill_parent will do exactly as it states, it will size the object so that it will fill the screen either vertically or horizontally.  wrap_content will format the object to expand or shrink to the size of the content displayed within.  Both of these variables can be used in many different objects including but not limited to Layouts, Text Views, Text Boxes, and Buttons.  android:text is used in certain objects like TextViews and TextBoxes to display text to the user.  As of right now, we are presenting the user with text but calling it from strings.xml instead of entering the text right in the node itself.  To reference strings.xml all that is needed is to put @string/press, where press is the name of your variable, inside the quotations.

Now that we are familiar with the terms, we will need to modify this to first house a label, textbox and finally a button.  To do this we will simply add a textbox and button since we already took care of the label in the string.xml.  To add a Textbox we will start on a new line under ending of the <TextView /> node.  Just to be clear I will add code inline and explain why we are adding it afterwards. <EditText android:id=”@+id/helloName” android:layout_width=”fill_parent” android:layout_height=”wrap_content” />.  EditText will be our textbox in this instance.  Also when giving items an ID it is best to follow these practises of adding @+id/ before your variable name which makes it possible to tie into your .java file later.  Next we will add <Button android:id=”@+id/go” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/press” /> directly underneath the ending of our EditText node.  Notice we are referencing the string.xml and calling the node that says Press Me! which will appear on our button now.  If you were to run this project now you would be able to see the layout of the program we just made but we are unable to get it to do anything except enter text in the textbox.

This next section will contain a lot of code and I will provide most of the screenshots of the code to help you through.  First, it is good to realize every time you would like to reference an object in your layout we need to import it.  We will need to add imports for our button and textbox.  We can do that bu adding these lines of code to the imports section at the top:

import android.widget.Button;
import android.widget.EditText;


After that we will need to include four more imports, the first being for event listen to add to our button, the second will be for the toast that we will call when the event handler runs, the third being the context of the application and the fourth to get the view of the application and handle the layout and interaction.  These imports can be added under the previous ones and will look like this:

import android.view.View.OnClickListener;
import android.widget.Toast;
import android.content.Context;
import android.view.View;


After these are added to your imports we are ready to get into coding the event handler for our button and the onCreate functions, which is called when the program is started.  To make things easier and to complement the screenshot, I will post the rest of the code and explain what the important lines are doing and why we are using them.

public class HelloMain extends Activity {
EditText helloName;


We are creating a reference to our textbox above any function so that it only has to be declared once but instantiated many times if need be.

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.go);
// Register the onClick listener with the implementation above
button.setOnClickListener(mAddListener);
}

Above we capture the button from the layout using a variable.  With this variable we are going to assign it an onClick Event Handler as shown on the last line above.  Below we are creating the Event Handler for it to be hooked in above.  After creating this function it will be able to pull the text from the TextBox and display it with static text.

// Create an anonymous implementation of OnClickListener
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v)
{
long id = 0;
// do something when the button is clicked
try
{
helloName = (EditText)findViewById(R.id.helloName);

Here we instantiate the TextBox we declared earlier and capture the Textbox in the layout by finding it by the ID that we gave it.

Context context = getApplicationContext();
CharSequence text = &quot;Hello &quot; + helloName.getText() + &quot;!&quot;;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();


The above code will take Context (the facet to our applications enviroment) and and add it to our Toast along with our dynamic CharSequence text and the length the Toast will appear onscreen, which in this case we want it to be longer.  It is key to note how to make a Toast as it is more efficient that popping up textboxes to the user as well as it is less distracting.

}
catch (Exception ex)
{
Context context = getApplicationContext();
CharSequence text = ex.toString() + &quot;ID = &quot; + id;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
};
}


The last thing we are doing for this function is putting all the important stuff mentioned above into a try catch statement which will try our important code and if there is an error it will display a Toast letting us know there was an error and a message about that error.  For functions such as these is it crucial to have precautions in place to catch errors and not have a program force close.  It is important to put the user first in thinking about UI and any error messages that might occur.  If an error somehow sneaks into your program try catch statements will catch the error and make it “cute and fuzzy” for the user.

Top half of code:


Bottom half of code, elapsed by previous view of code:

After we have coded the main content for our .java file, we can now proceed to run the application and view our completed Improved Hello World program.  Notice that when you press the button and your textbox has not text in it that the program will still function correctly.  This is a good feature to have so that you don’t start seeing Toasts containing error messages.  The completed product should look like this when the button is pressed:


This would conclude our Improved Hello World example but the learning is far from over.  Next post we will examine Databases and a look into some simple queries as well as building a database from the ground up.  As always, if you have any problems with coding this article, feel free to leave a comment and I will assist in any way possible! If you can’t wait for the next post you can read up on databases before the next posting.  Until next time, Happy Hacking!

Continue on to Part3: Introduction to Databases

82 thoughts on “Android Development 101- Part 2:Graphical Elements

  1. I really wish i’d read more comments before getting this far. The tutorial is missing all sorts of details that need to be guessed.

    I’m a pro windows software engineer and can just about manage to work out the gaffs, but anyone new to programming/IDEs would be stuffed.

    To those making comments like “Open source is all about hacking”, you are idiots.. open source is about open source. Hacking is about hacking.

    Maybe I should never have come anywhere near a site of self proclaimed “hackers”..

  2. Actually, it is not a good idea to create 2 applications with the same package name (and install them both on the device). I was getting a warning: “Warning: Activity not started, its current task has been brought to the front”, and was wondering why the ‘improvedhelloworld’ app wasn’t showing up on the device. After perusing Motodev forums and Eclipse-related development, I have come to the conclusion that renaming my package to make it unique is a good idea. I realize that Java has a robust namespace paradigm, but for the sake of sanity I’d rather have unique package names.

    Otherwise this was a great tutorial, and I can’t wait to proceed to part 3!
    Keep up the good work,
    Igor

  3. This is Great – Tanks

    MAN! Eclipse “Problem” flagging is not very interactive. Once you make a typo it’s hard to get the red X to go away.

    Why do I have this error?:
    Description Resource Path Location Type error: Error: No resource found that matches the given name (at ‘text’ with value ‘@string/press’). main.xml /helloworld_v1.1/res/layout line 17 Android AAPT Problem

  4. Just getting started in programming and am having some difficulty with this program. Basically, and not to beat a dead horse, but I’m in the same boat as John, except changing the quotations didn’t solve the issue. Still getting

    “main cannot be resolved or is not a field”

    same goes for “go” and “helloName”. I had originally copy/paste them in, but have since erased and typed them in. Kinda stuck and want to keep moving forward, advice???

  5. @lowlysoundtech
    Delete and replace the ” ” quotes, from what you copied from this site, in Main.xml file.

    You’ll that some of the ” are italicized. That is what is causing the errors.

    *Late reply, but maybe others will hae the same questions.*

  6. hey guys. . . .i don’t have a java compiler on my mobile. . . .where could i find tutiorials to use the ruby packages to code an app for android? please, i’m desperate! really desperate!

  7. We’re a group of volunteers and opening a new scheme in our community. Your site provided us with valuable info to work on. You’ve done a formidable job and our whole community will be thankful to you.

  8. Greg,
    Fantastic stuff. Thank you for taking the time to pass such detailed information on to the rest of us.

    I’ve run into an issue that has me totally baffled but might be an easy thing for some of you more experience folks.

    Started off with errors similar to previous posts about R.id.go and the like, got those resolved, now I’m getting four more errors.

    Line 28
    private OnClickListener mAddListener = new OnClickListener();{
    error1 “Cannot instantiate the type View.OnClickListener

    Line 29
    public void onClick(View v){
    error2 “syntax error on token ‘(‘, ; expected”
    error3 “syntax error on token ‘)’, ; expected”
    error4 “void is invalid type for variable onClick

    anyone know how to help me out?

  9. It seems that I am having a problem similar to other user’s issues.

    <Button
    android:id="@id/go"

    The error that it gives me-
    Multiple annotations found at this time
    error:Error:No resource found that matches the given name (at'id' with value '@id/go').
    error:Error:No resource found that matches the given name(at 'text' with value '@string/press')

  10. I got an error in my main.xml file…
    I think there is something wrong in the naming of the id… :

    android:id=”@+id/helloName”
    &&
    android:id=”@+id/go”

    it wont run and compile properly.. Please help

    1. Try double checking the look of the double quotes. I have found that when pasting them into the Eclipse editor when copying them from this page, they go in as some odd double quotes that have a slant to them. Replace them with a double quote typed from your keyboard.

      This got that error to go away for me.

      Cheers,
      C

  11. @Ashley and other who had this error (and me!)

    error:Error:No resource found that matches the given name(at ‘text’ with value ‘@string/press’)

    make sure you are editing the new strings.xml from the copied project and not the original one.

    hope that helps someone

    1. Because it ends the line that instantiates a new object started by

      private OnClickListener mAddListener = new OnClickListener(){…

      You must end it with
      …};

      NOT
      …}

      The overbearing statement here is an instantiation of a new object (albeit with a lotta code doing so), NOT an instantiation of a function or whatever.

    2. You’re in the middle of instantiating a new object here. You’re ending a line started with

      private OnClickListener mAddListener = new OnClickListener(){…

      so you gotta end it with

      …};

      NOT

      }

      Because the overall statement here is an instantiation of a new object (albeit with a lot of code). NOT an instantiation of a new function or w.e else you think it might be.

  12. I can’t understand why people write code that doesn’t use proper indentation. This makes it very difficult to read and instead of concentrating on the programming concepts being discussed, you spend much of your time just trying to makes sense of the code. Indentation and white space are used for a reason and one attribute of good programming is readability and maintainability of the code.

  13. I am getting the following errors and don’t know how to resolve them:
    these two lines are giving the same error
    button.setOnClickListener(mAddListener);
    private onClickListener mAddListener = new onClickListener()
    error
    onClickListener cannot be resolved to a type

    on line
    ChartSequence text = “Hello ” + helloName.getText()
    error
    onChartSequence cannot be resolved to a type

    Any help? Anybody still monitoring this post?
    thank you so much

    1. Hello Gala,

      Regarding your lines:

      “button.setOnClickListener(mAddListener);
      private onClickListener mAddListener = new onClickListener()”

      I was having a time with this as well, my Eclipse “cursor-hover-help” note suggests that this should be:

      “mAddlistener” (Lowercase “L” in “listner”)

      not:

      “mAddListener” as it says in the tutorial text.

      No worries to the poster though, I greatly appreciate the time and effort, and can only imagine how time consuming and challenging it is to try and share some knowledge with us. Please keep it up!

  14. I fixed the problem with InprovedHelloWorld. I copied the code stright from the webpage but got an error in my layout.main.xml Turns out that if you change the quotation marks used in the statements to the quoteation marks on your keyboard all is well. I believe there is an American and a European quotation mark that are not interchangable in some instances. Best of luck,
    Jim

  15. Ran in to some the same issues as above:
    1. Add the import statements to HellowMain.java
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    2. Change retype quotes in main.xml

    I also had to add a hint to <EditText in Main.xml

  16. Random guy who decided to design a game and doesn’t know shiz about programming.
    Thanks Greg, I did a different helloandroid tutorial and had many problems but after 4 hours got it running…mostly a lot of trial and error and googling…found your series after that but read the previous and this one so far…this is really helpful because it explained how everything works. Cannot wait to read the next ones.

  17. Been programming in .NET and wanted to play with my phone. For one thing, the emulator is ridiculously slow, so I’ve been testing on an older Android phone: much, much faster. Any reasons why that’s a bad idea?

    Also, the tutorial is a great info not just into Android “app fabbing” but is also a good intro into Java / XML. Thanks, and keep it up!!

Leave a Reply to KevinCancel reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.