[TUT] Extend your HelloWorld App Step by Step with a Toast Message

Search This thread

coolsandie

Senior Member
Oct 22, 2011
1,986
1,062
Kochi, Kerala
coolsandie.github.io
Hi guys, this Tutorial is mainly intended for looking into some other concepts like GUI of Android development. The concept of "Toast" would be actually covered.

First you have to do this (Create a HelloWorld app) : [TUT] Making a HelloWorld App Step by Step w/pictures. - Tutorial created by rezo609

After you've created your first HelloWorld app, its time for some additional tasks!
(NOTE:- Make sure you've set your AVD already)

I know some of you guys are wondering what a Toast is, well here's the answer: Click Me!


Starting development :


Step 1: The first thing we are going to accomplish is changing the strings.xml (Path:- AppName > res > values > 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!.

5BNGU.png


Step 2: Next step, is to design the GUI (Graphical User Interface). To do this navigate to main.xml (Path:- AppName > res > layout > main.xml) and we are going to go over what everything does up to this point. Set your main.xml file as shown in the below picture.

b98zc.png


Make sure you've set the Orientation as vertical, otherwise ie, if its horizontal maybe the GUI controls won't be shown when the app is run.(in an HVGA Emulator, or maybe its me) :D Anyways you are free to toggle between vertical/horizontal and see what happens. ;)


Step 3: Now this is a tricky step, and it includes Java code modifications. I suggest you to google to know exactly what all these codes means be it functions, classes, methods, objects or imports. You can refer the Wiki or the Oracle docs if you want to learn more about Java. Anyways for keeping this Tutorial simple, just modify the Java file (Path:- AppName > src > com.example.helloworld > HelloWorldActivity.java) as shown in the below picture.

hZnVY.png



I'll also give it as CODE, but don't just copy-paste. If you run into massive errors or problems only, do that. Its better to type the codes by yourself and see what all AutoFill options/suggestions are given by Eclipse. Anyways try to correct the errors by yourself, it maybe only a spelling-mistake, but you have to identify it where.
Code:
package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.content.Context;
import android.view.View;


public class HelloWorldActivity extends Activity {

EditText helloName;
    
/** 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 onClickListener with the implementation above
button.setOnClickListener(maddListener);
}
    
    // 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);
    		Context context = getApplicationContext();
    		CharSequence text = "Hello " + helloName.getText() +"!";
    		int duration = Toast.LENGTH_LONG;
    		Toast toast = Toast.makeText(context, text, duration);
    		toast.show();
    		}
    		
    		catch(Exception e) {
    		
    		Context context = getApplicationContext();
    		CharSequence text = e.toString() + "ID = " + id;
    		int duration = Toast.LENGTH_LONG;
    		Toast toast = Toast.makeText(context, text, duration);
    		toast.show();
    		}
    	}
    };
}


Step 4: After doing all these above mentioned tasks, its time for the output. Be sure to click "Save All" (Ctrl+Shift+S) button in the Eclipse. Also make sure your Project is free from errors, otherwise it would not run. You can also clean your Project (Some errors maybe automatically fixed) by navigating to Project > Clean...

Right Click your Project > Run As > 1 Android Application
Your Emulator would start, and you'll see in the Eclipse as apk installing, running etc..
If your Project is a Success, you'll get the output as shown in the below picture:

gLYPl.png

And that's it :D
I hope you enjoyed this tutorial. Its made as simple as possible and omitted some theories from the Original source. You can get to it, and see the xml parts explained. :)
 
Last edited:

blazingwolf

Senior Member
Nov 11, 2006
2,127
405
So I decided to look at this. I've got everything as you have above but I have errors.

Current errors are in the following lines:

Code:
Button button = (Button)findViewById(R.[COLOR="Red"]id[/COLOR].go);

Code:
helloName = (EditText)findViewById(R.[COLOR="red"]id[/COLOR].helloName);

The error states: id cannot be resolved or is not a field

If I follow the listed fixes it places lines in the R.java. However, I then get errors on go and helloName for which there are no listed fixes.

Still looking to see if I can find it myself but wanted to tell you about this to see if it was just me (probably) or a missing section in the info above.

EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now. :)
 
Last edited:

pmapma1

Member
Oct 1, 2010
39
0
Pune
So I decided to look at this. I've got everything as you have above but I have errors.

Current errors are in the following lines:

Code:
Button button = (Button)findViewById(R.[COLOR="Red"]id[/COLOR].go);

Code:
helloName = (EditText)findViewById(R.[COLOR="red"]id[/COLOR].helloName);

The error states: id cannot be resolved or is not a field

If I follow the listed fixes it places lines in the R.java. However, I then get errors on go and helloName for which there are no listed fixes.

Still looking to see if I can find it myself but wanted to tell you about this to see if it was just me (probably) or a missing section in the info above.

EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now. :)


please check the imports ...
if you find line import android.R; ... remove it and then clean build....
 

coolsandie

Senior Member
Oct 22, 2011
1,986
1,062
Kochi, Kerala
coolsandie.github.io
EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now. :)

There you are :D
Actually we should edit all the XML files first like android:id="@+id/go" and it will show error in XML file for sure (Because id can't be found anywhere) but finally when you code the java file, and when the id is referenced, all errors will be gone :)

Anyways the R.java file can't be modified manually. It will revert back to original state if you do so, that is even if you apply the suggested fixes by Eclipse.
 

TommiTMX

Member
Jan 10, 2011
7
1
Hi there,

I've been wondering this so I thought I'd ask here since it seems nice and n00b friendly ;-)

I was wondering if you could tell me if there's any direct benefit to creating an OnClickListener in Java instead of using the android:OnClick="" attribute for the layout and having it go to a specified method.

Thanks,

Tom
 

coolsandie

Senior Member
Oct 22, 2011
1,986
1,062
Kochi, Kerala
coolsandie.github.io
Hi there,

I've been wondering this so I thought I'd ask here since it seems nice and n00b friendly ;-)

I was wondering if you could tell me if there's any direct benefit to creating an OnClickListener in Java instead of using the android:OnClick="" attribute for the layout and having it go to a specified method.

Thanks,

Tom

Benefit?! ... Hmm !!
It all depends upon the logic of the programmer that he/she is comfortable with. Actually there will be many methods or many ways we can create for the same process. But as this is just a Tutorial/Illustration application, we don't know exactly what its effects. Maybe in real time application there maybe some beneficiaries. Just we need to sort it out to know.
 

Shmarkus

Senior Member
Sep 17, 2011
90
32
Tallinn
can you make a tutorial how to make a background process? Or service of somekind.

E.g. process that shows blue led while BT is on

thanks in advance!
 

coolsandie

Senior Member
Oct 22, 2011
1,986
1,062
Kochi, Kerala
coolsandie.github.io
can you make a tutorial how to make a background process? Or service of somekind.

E.g. process that shows blue led while BT is on

thanks in advance!

I'll definitely try, but can't guarantee when because I'm also a learning candidate in Android app development. So making Tutorials, that I've already learned and tried. Once I've learned about it, I'll of course include the Tutorial for it. :)
 

Flowyk

Senior Member
Aug 23, 2011
223
17
why we need try/catch for one-way trigger? ... what in toast can throw exception?
 
Last edited:
  • Like
Reactions: coolsandie

coolsandie

Senior Member
Oct 22, 2011
1,986
1,062
Kochi, Kerala
coolsandie.github.io
why we need try/catch for one-way trigger? ... what in toast can throw exception?

Well, I just checked myself by removing the try-catch block, and yes you are right as no exceptions are actually caught. Anyways the code is not actually written by me, and if you checked the original source you'd have known that. :)

And Thanks for the point mate. Maybe I'll review the code from next time onwards.
 

Top Liked Posts

  • There are no posts matching your filters.
  • 10
    Hi guys, this Tutorial is mainly intended for looking into some other concepts like GUI of Android development. The concept of "Toast" would be actually covered.

    First you have to do this (Create a HelloWorld app) : [TUT] Making a HelloWorld App Step by Step w/pictures. - Tutorial created by rezo609

    After you've created your first HelloWorld app, its time for some additional tasks!
    (NOTE:- Make sure you've set your AVD already)

    I know some of you guys are wondering what a Toast is, well here's the answer: Click Me!


    Starting development :


    Step 1: The first thing we are going to accomplish is changing the strings.xml (Path:- AppName > res > values > 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!.

    5BNGU.png


    Step 2: Next step, is to design the GUI (Graphical User Interface). To do this navigate to main.xml (Path:- AppName > res > layout > main.xml) and we are going to go over what everything does up to this point. Set your main.xml file as shown in the below picture.

    b98zc.png


    Make sure you've set the Orientation as vertical, otherwise ie, if its horizontal maybe the GUI controls won't be shown when the app is run.(in an HVGA Emulator, or maybe its me) :D Anyways you are free to toggle between vertical/horizontal and see what happens. ;)


    Step 3: Now this is a tricky step, and it includes Java code modifications. I suggest you to google to know exactly what all these codes means be it functions, classes, methods, objects or imports. You can refer the Wiki or the Oracle docs if you want to learn more about Java. Anyways for keeping this Tutorial simple, just modify the Java file (Path:- AppName > src > com.example.helloworld > HelloWorldActivity.java) as shown in the below picture.

    hZnVY.png



    I'll also give it as CODE, but don't just copy-paste. If you run into massive errors or problems only, do that. Its better to type the codes by yourself and see what all AutoFill options/suggestions are given by Eclipse. Anyways try to correct the errors by yourself, it maybe only a spelling-mistake, but you have to identify it where.
    Code:
    package com.example.helloworld;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import android.view.View.OnClickListener;
    import android.content.Context;
    import android.view.View;
    
    
    public class HelloWorldActivity extends Activity {
    
    EditText helloName;
        
    /** 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 onClickListener with the implementation above
    button.setOnClickListener(maddListener);
    }
        
        // 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);
        		Context context = getApplicationContext();
        		CharSequence text = "Hello " + helloName.getText() +"!";
        		int duration = Toast.LENGTH_LONG;
        		Toast toast = Toast.makeText(context, text, duration);
        		toast.show();
        		}
        		
        		catch(Exception e) {
        		
        		Context context = getApplicationContext();
        		CharSequence text = e.toString() + "ID = " + id;
        		int duration = Toast.LENGTH_LONG;
        		Toast toast = Toast.makeText(context, text, duration);
        		toast.show();
        		}
        	}
        };
    }


    Step 4: After doing all these above mentioned tasks, its time for the output. Be sure to click "Save All" (Ctrl+Shift+S) button in the Eclipse. Also make sure your Project is free from errors, otherwise it would not run. You can also clean your Project (Some errors maybe automatically fixed) by navigating to Project > Clean...

    Right Click your Project > Run As > 1 Android Application
    Your Emulator would start, and you'll see in the Eclipse as apk installing, running etc..
    If your Project is a Success, you'll get the output as shown in the below picture:

    gLYPl.png

    And that's it :D
    I hope you enjoyed this tutorial. Its made as simple as possible and omitted some theories from the Original source. You can get to it, and see the xml parts explained. :)
    1
    After you have succeeded in this app, head over to next Tutorial : Create your First Widget Step by Step
    1
    why we need try/catch for one-way trigger? ... what in toast can throw exception?