Tutorial:Hello Android

From Notes

Jump to: navigation, search

This tutorial builds on the Android Hello World tutorial by adding:

  • A simple menu.
  • A sub activity with a returned result.

Before trying this tutorial, work through the Android tutorial located here: [1].

Contents

Adding a Menu

Let's add a configure menu item to the HelloAndroid Activity. When selected, this will start a configure Activity that will allow the user to enter a name. When the sub-activity finishes, the program will say Hello name for whatever name is entered.

To add a menu to the HelloAndoid Activity, we will override two methods inherited from the Activity class:

  • onCreateOptionsMenu(Menu menu) -- This method creates an options menu, the default menu for an Activity. This is the menu that comes up when you press the phone's Menu key.
  • onOptionsItemSelected(MenuItem item) -- This is the method that is called when the user selects a menu item. It handles whatever action is associated with that item.

Here is the code for onCreateOptionsMenu():

   public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, CONFIGURE_ID, 0, R.string.configuration_menu);
        return result;
    }

The menu parameter is the menu into which you add menu items. The menu items should be identified by class constants (CONFIGURE_ID). The call to the super class creates the default menu for the Activity.

Here is the code for onOptionsItemSelected():

    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case CONFIGURE_ID:
            configure();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

A switch statement is used to branch to the action associated with the selected menu item. In this case we simply call the configure() method.

Starting a Sub-Activity and Returning a Result

An Intent object is used to start a sub-Activity:

    private void configure() {
    	Intent i = new Intent(this, ConfigurationActivity.class);
    	startActivityForResult(i, CONFIGURE_ID);
    }

In this case, we start the Activity expecting a result to be returned. The name of the Activity is ConfigurationActivity, which we be coded as a separate class. First, let's look at how the result is handled:

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)   // Cancel case
			return;
		switch(requestCode) {
		case CONFIGURE_ID:
		    Bundle extras = data.getExtras();
		    String name = extras.getString("Name");
		    Toast.makeText(this, "Hello " + name, Toast.LENGTH_SHORT).show();
		    TextView tv = (TextView) findViewById(R.id.hello_message);
		    tv.setText("Hello " + name);
		    break;
		}
	}

To handle a result from an Activity, we override the onActivityResult() method. The requestCode parameter identifies the request that was made when the sub-Activity was launched. The resultCode specifies whether the sub-Activity worked or not. A 0 code means that everything was fine. Non-zero codes are used as error codes. The data parameter refers to an Intent object that holds the results of the sub-Activity.

In this case, we use the getExtras() method to retrieve the Name string from the Intent. Results are stored in a Bundle, which is an associative array that associates a String key, such as "Name" with some kind of object. In this case "Name" is associated with a String object, namely the name that was input by the user. Hence we use getString() to retrieve the associated object.

The Configuration Activity

The ConfigurationActivity is an Activity subclass. It will display a View containing an EditText widget, where the user can type a name, and Ok and Cancel buttons: Image:Configlayout.png

When the user clicks Ok the EditText value will be retrieved and put into an Intent object that will be passed back to the calling Activity. For this simple example, all of this code can go into the onCreate() method:

   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.configure);  
        
        final EditText nameText = (EditText) findViewById(R.id.name_field);
        Button okButton = (Button) findViewById(R.id.ok);
        okButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {		// When the OK button is clicked
            	Bundle bundle = new Bundle();		// Get the name and put it in the Bundle
            				// Here the bundle mapping is "Name" --> the name typed by user
            	bundle.putString("Name", nameText.getText().toString());  
            	
            	Intent intent = new Intent();
            	intent.putExtras(bundle);		// Put the Bundle in an Intent
            	setResult(RESULT_OK, intent);		// Return the Intent
            	finish();
            }
                   
        });
        
        Button cancelButton = (Button) findViewById(R.id.cancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	setResult(RESULT_OK, null);
            	finish();
            }
                   
        });findViewById(R.id.name_field);
    }

Note how the ClickListeners are created for the Ok and Cancel buttons. The Ok listener retrieves the text from the EditText and adds it to a Bundle, which is then added to the Intent. The Intent is passed back using the setResult() method.

Updating the Manifest

Finally, in order to start a sub-Activity, it is necessary to add an Activity tag to the project's Manifest:

 <activity android:name=".ConfigurationActivity"></activity>

Running the App

This example uses XML resource files for the main and configure layouts. These are contained in the source code: Media:helloandroid.zip. Download the zip file. Unzip it and then use it to create a new Android project.

Exercises

  1. Add a new EditText field to the ConfigurationActivity for something like age or date.
  2. Add some other kind of Widget to the ConfigurationActivity, such as a Spinner or a DatePicker or a AutoComplete field. See here for ideas: http://developer.android.com/guide/tutorials/views/index.html.

References

Personal tools
NSF K-12