Home > Android, Eclipse, Java > Coding my first Android application

Coding my first Android application

I finally got the time to develop my first small Android application.
Technical environment :
– Eclipse Indigo
– Android SDK 2.3.3 (Gingerbread)
– An Android phone with Android SDK 2.3.4

I tried to go a little bit further than the traditional “Hello World” sample.
The application, called TeamManagement, is still a simple one : type in a name of a project member and it will display what his role is and when he arrived in the project. That’s it. I explored some nice features : relative layout, autocompletion, popup, menu at the bottom, show/remove image etc.

Main

The project inside Eclipse has the following structure :

The file /MyProject/res/values/strings.xml is where the name of the application is set.

<string name="app_name">TeamManagement 1.0</string>

I chose to organize the layout programatically, instead of declaratively (main.xml) and created a single activity called MyProjectActivity :


package com.celinio.dev;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyProjectActivity extends Activity {
	
	// the tag displayed for the class logs
	private static final String LOG_TAG = "MyProjectActivity";
		
	LinearLayout layout;
	LinearLayout subLayout;
	LinearLayout subLayoutButtons;
	LinearLayout subLayoutBottom;
	
	private TextView questionTitle;
	private TextView firstNameLabel;
	private TextView response;
	private Button checkButton;
	private Button resetButton;
	private Button aboutButton;	
	private AlertDialog alertAbout;
	private AlertDialog alertUnknownMember;
    private CheckBox chkAuto;
    private TextView autocompletionLabel;
    private AutoCompleteTextView autoTextView;
    private EditText firstNameText;
    private AnalogClock clock;
    private ImageView androidImage;
	
	public final static int mButtonHeight = 200;
    public final static int mButtonWidth = 140;
     
    private  Map members;
    
     // Pour l'autocompletion
     String[] teamMembers = 
    	    {
	            "celinio",
	            "mathieu",
	            "xavierf",
	            "guillaume",
	            "lionel",
	            "ahmed",
	            "jean",
	            "bob",
	            "frédéric",
	            "xavierm"
    	    };    	 
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
    	
        layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);         
        layout.setLayoutParams(
        		new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, mButtonHeight, 1));
        layout.setGravity(Gravity.CENTER);

        questionTitle = new TextView(this);
        questionTitle.setText("What is you role " +
        		"and when did you arrive in the project ?");
        
        firstNameLabel = new TextView(this);
        firstNameLabel.setText("First name");
        
        firstNameText = new EditText(this);
        firstNameText.setHint("Type in the entire first name");
        
        response = new TextView(this);
        response.setText("Answer ...");
        
        autocompletionLabel = new TextView(this);
        autocompletionLabel.setText("Activate autocompletion");
                
        checkButton = new Button(this);
        checkButton.setWidth(mButtonWidth);
        checkButton.setTextSize(20);
        checkButton.setText("Check");
        checkButton.setBackgroundColor(Color.BLUE);
        
        resetButton = new Button(this);
        resetButton.setWidth(mButtonWidth);
        resetButton.setTextSize(20);
        resetButton.setText("Reset");
        resetButton.setBackgroundColor(Color.RED);

        aboutButton = new Button(this);
        aboutButton.setText("About");
        
        clock = new AnalogClock(this);
        clock.setVisibility(View.GONE);
        androidImage = new ImageView(this);
        androidImage.setImageResource(R.drawable.android1);
        androidImage.setVisibility(View.GONE);
        
        members = new HashMap<String, String>();
        
        members.put("celinio", "architect - february 2010");
        members.put("mathieu", "tester - june 2010");
        members.put("xavierf", "tester - may 2010");
        members.put("guillaume", "developer - june 2010");
        members.put("lionel", "developer - october 2010");
        members.put("ahmed", "developer - july 2010");
        members.put("jean", "team leader - september 2009");
        members.put("bob", "team leader - september 2009");
        members.put("frédéric", "developer - january 2011");
        members.put("xavierm", "technical coordinator - november 2010");
                
        alertAbout = new AlertDialog.Builder(this).create();       
        alertAbout.setTitle("About");
        alertAbout.setMessage("TeamManagement version 1.0 - Author : Celinio © - 01/01/2012");        
        alertAbout.setButton("OK", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int which) {  
              return;  
          } }); 
        // Setting Icon to Dialog
        alertAbout.setIcon(R.drawable.tick);
        
        alertUnknownMember = new AlertDialog.Builder(this).create(); 
        alertUnknownMember.setTitle("Error");
        alertUnknownMember.setMessage("This member is unknown !");
        alertUnknownMember.setButton("OK", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int which) {  
              return;  
          } }); 
	     // Setting Icon to Dialog
        alertUnknownMember.setIcon(R.drawable.warning);
           
		checkButton.setOnClickListener( new OnClickListener() {
            public void onClick( View view ) {            	
    			
    			String theFirstName  = null;
    			
    			// Autocompletion disactivated
    			if (firstNameText.isEnabled()) {    				
    				theFirstName = firstNameText.getText().toString().toLowerCase();
    			} else  {
    				// Autocompletion activated
    				theFirstName = autoTextView.getText().toString().toLowerCase();
    			}
                        	
            	String role = (String)members.get(theFirstName);
            	if (null == role ) {
            		role = "Unknown";
            		alertUnknownMember.show(); 
            	}
            	response.setText("Your role and your month of arrival are : " + role);            	
                
                // Hide the virtual keyboard 
            	// The getWindowToken() function gets a unique token 
            	// identifying the window that the view is attached to.
                InputMethodManager imm = 
                		(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
                imm.hideSoftInputFromWindow(firstNameText.getWindowToken(), 0);              
            }
        });
                
        aboutButton.setOnClickListener( new OnClickListener() {
            public void onClick( View view ) {            	   
                alertAbout.show(); 
           }
       });
                
        resetButton.setOnClickListener( new OnClickListener() {
            public void onClick( View view ) {            	   
                autoTextView.setText("");
                firstNameText.setText("");
           }
       });
               
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
        		android.R.layout.simple_dropdown_item_1line, teamMembers);        
        
        autoTextView = new AutoCompleteTextView(this);
        autoTextView.setEnabled(false);
        autoTextView.setThreshold(3);
        autoTextView.setAdapter(adapter);    
    	autoTextView.setHint("Type in the first 3 letters of the first name");
    	autoTextView.setVisibility(View.GONE);

        layout.addView(questionTitle);
        addListenerOnChkAuto();
        subLayout = new LinearLayout(this);
        subLayout.setOrientation(LinearLayout.HORIZONTAL); 
        subLayout.addView(chkAuto);
        subLayout.addView(autocompletionLabel);                
        
        layout.addView(subLayout);
        layout.addView(firstNameLabel);
        layout.addView(firstNameText);
        layout.addView(autoTextView);
        
        layout.addView(createSpacer(this));
        
        subLayoutButtons = new LinearLayout(this);
        subLayoutButtons.setOrientation(LinearLayout.HORIZONTAL);
        subLayoutButtons.setGravity(Gravity.CENTER_HORIZONTAL);
        subLayoutButtons.addView(checkButton);
        subLayoutButtons.addView(createSpacer(this));
        subLayoutButtons.addView(resetButton);
        layout.addView(subLayoutButtons);
        
        layout.addView(response);
        
        subLayoutBottom = new LinearLayout(this);
        subLayoutBottom.setOrientation(LinearLayout.HORIZONTAL);
        subLayoutBottom.setGravity(Gravity.CENTER_HORIZONTAL);
 
        subLayoutBottom.addView(clock);
        subLayoutBottom.addView(androidImage);   
        
        layout.addView(subLayoutBottom);        
        layout.addView(aboutButton);
       
        setContentView(layout);
    }
        
    public void addListenerOnChkIos() {    	 
    	chkAuto =  new CheckBox(this);
     
    	chkAuto.setOnClickListener(new OnClickListener() {         	  
    	  public void onClick(View v) {
    		  
              InputMethodManager imm = 
            		  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
              imm.hideSoftInputFromWindow(firstNameText.getWindowToken(), 0); 
              
                    //is chkAuto checked ?
    		if (((CheckBox) v).isChecked()) {    			
    			autoTextView.setVisibility(View.VISIBLE);
    			autoTextView.setEnabled(true); 			    		

    			firstNameText.setVisibility(View.GONE);
    			firstNameText.setEnabled(false);		
    			firstNameText.setText("");
    			Toast.makeText(MyProjectActivity.this, 
    					"Search with completion activated",
    					Toast.LENGTH_LONG).show();
    		} else {    			
    			autoTextView.setVisibility(View.GONE);
    			autoTextView.setEnabled(false);
    			autoTextView.setText("");
    			
    			firstNameText.setVisibility(View.VISIBLE);
    			firstNameText.setEnabled(true); 
    			Toast.makeText(MyProjectActivity.this,  
    					"Search with completion disactivated", 
    					Toast.LENGTH_LONG).show();
    		}     
    	  }
    	});
     
      }
   
    private static View createSpacer(Context activity) {
    	  View spacer = new View(activity);
    	  spacer.setLayoutParams(new LayoutParams(7, 7));
    	  spacer.setBackgroundColor(Color.BLACK);
    	  return spacer;
    	}
    
    @Override
       public boolean onCreateOptionsMenu(Menu menu) 
      {
         super.onCreateOptionsMenu(menu);
         
         MenuItem itemHour = menu.add(Menu.NONE, 0, 0, "Display the clock");
         itemHour.setIcon(R.drawable.horloge);                 
         MenuItem itemImage = menu.add(Menu.NONE, 1, 1, "Display the Android logo");
         itemImage.setIcon(R.drawable.android1small);
         
         itemHour.setOnMenuItemClickListener(new OnMenuItemClickListener() {        	    
	    	 public boolean onMenuItemClick(MenuItem item){        		     		 
	    		 Log.d(LOG_TAG, "=========> itemHour clicked");        	    	  
	    		 androidImage.setVisibility(View.GONE);
	    		 clock.setVisibility(View.VISIBLE);
	             return true;
	         }
        	   	
         });   
                  
         itemImage.setOnMenuItemClickListener(new OnMenuItemClickListener() {        	    
        	 public boolean onMenuItemClick(MenuItem item){    
        		 Log.d(LOG_TAG, "=========> itemImage clicked");         	        	   	 
        		 clock.setVisibility(View.GONE);
        		 androidImage.setVisibility(View.VISIBLE);
                 return true;
             }

         });  
         
         return true;
      }
   
}

I actually use two widgets to let the user type in the first name :

private AutoCompleteTextView autoTextView;
private EditText firstNameText;

When the user launches the application for the first time, the activity is started and the widget that handles the autocompletion is not displayed (line 210) :

autoTextView.setVisibility(View.GONE);

A listener on the checkbox is added to decide whether to use completion or not. That sets the visibility of these two widgets. That’s what the addListenerOnChkAuto() method does, line 249.
The visibility is set through the use of 2 variables of type int, from the View class :

autoTextView.setVisibility(View.VISIBLE);
...
firstNameText.setVisibility(View.GONE);

In order to add a fancy menu which appears at the bottom of the screen when you hit the Menu (on the left of the Home button on my phone), you need to override the method onCreateOptionsMenu(Menu menu) (line 294) which is defined in the android.app.Activity class. That’s pretty easy and that’s pretty cool.
All I do is displaying a clock if the user selects the first item of the menu (itemHour) or the Android logo if the user selects the other item (itemImage) of the menu.

Here are a few screenshots that i took on my cellphone and that gives a clear explanation of what the program does :


Main   Main
Main   Main
Main   Main
Main   Main
Main

Categories: Android, Eclipse, Java Tags:
  1. No comments yet.
You must be logged in to post a comment.