Posted by: phillipnb | March 1, 2013

Dissecting a Simple Android Application


In this post, We will dissect a basic android application called “Foodie”. Foodie is a simple application for kids, to help them decide what to eat/snack at a particular time of a day. It has two main options called Service and Admin. Using Admin, user can add or delete food items for a particular time of the day. Later, when the user uses the option ‘Service’, the app will pick a random food item for the current time and show it to the user.

That was about the application from the user’s point of view. From a application developer’s point of view, let us dissect the code. In this post, we will not be explaining about every line of the code but explain some of the important parts of this application so that readers of this post can reuse them in their application.

onCreate()
The first thing a android developer should understand is that onCreate() is a life-cycle method. This method is called when a activity is created for the first time. This method is used to do all types setups and initialisation – e.g.creating view. According to android reference , “onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically”.

onCreateOptionsMenu()
The definition for onCreateOptionsMenu is slightly different for different versions of android. So, it is better to follow the android reference which says that “If you’ve developed your application for Android 2.3.x and lower, the system calls onCreateOptionsMenu() to create the options menu when the user opens the menu for the first time. If you’ve developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the action bar.”

In this application, as soon as the app is loaded, we need to show two buttons – one for “Service” and another for “Admin”. How do we achieve this?. One way to achieve this will be – Open the file called activity_main.xml and add the following code to it:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_admin"
android:onClick="showAdmin"/>    

When the above button is clicked, the method assigned to it in the main activity code will be run. In the above case, we have written onClick=”showAdmin”. This means when the above button is clicked, the method showAdmin in my MainActivity.java will be run. This method will look like this:

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	public void showAdmin(View view) {
	    Intent intent = new Intent(this, DisplayAdminActivity.class);
	    startActivity(intent);
	}
}

For the above button click to work, we need to do one more thing. In the showAdmin() method, if you have noticed we have mentioned about a class called DisplayAdminActivity.class. We need to create that class as shown below:

public class DisplayAdminActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_admin);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_display_admin, menu);	 		
		return true;
	}		
}

Intent
According to the Android reference, “An intent is an abstract description of an operation to be performed. “. Intent is (in its basic definition) a message that is used when we want to report about something or we want something to happen. Intent can also be explained in another way – Android application is made of many activities and when you want to move from one activity to another we use Intent. In the code shown above our intention is to move to the activity called DisplayAdminActivity. The first parameter in the class “Intent” called “this” means packageContext(Context of the application package implementing this class) and the second parameter “DisplayAdminActivity.class” is the component class that is to be used for the intent. One final note about intents – intents are case-sensitive, so be careful. If you would like to learn more about intents then please refer the Android Reference. The usage startActivity(intent) is used to start a new activity.

Intent intent = new Intent(this, DisplayAdminActivity.class); 
startActivity(intent);

setContentView()
According to the Android Reference, setContentView (View view) sets the activity content to an explicit view.

getMenuInflater()
According to Android Reference, getMenuInflater() returns a MenuInflater() with the current context. MenuInflater class is used to instantiate menu XML files into Menu objects.

Input using EditText
I have a input field to collect the food item name and then save it to the database. This can be achieved in the following way: First, add the edittext code to the xml file.

<EditText android:id="@+id/edittext1"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:inputType="text"
  android:text=""/>

Then, in the java method we can access the contents of the edit text field by:

foodval = (EditText) findViewById(R.id.edittext1);
String food_val = foodVal.getText().toString();

In addition to the edittext, I have a drop down list to allow the user to select the time. In android this is called the spinner widget. The way we create a spinner widget and get the selected content is like this:

<Spinner android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/time_arrays" />

Now, to access the selected item, the following need to be coded in the java method:

foodTime = (Spinner) findViewById(R.id.spinner1);
food_time = foodTime.getSelectedItem().toString();

OfCourse, all the above variables belong to the given class and can be declared like this

private EditText foodVal;
private Spinner foodTime;

The above inputs – food val and the time is collected when a “Save” button is clicked. For this, we first define a button in the xml file and then get access to it in the java method. After this we attached a “click” listener to it. This is how we do this:

btnSave = (Button) findViewById(R.id.save_button);
btnSave.setOnClickListener(new View.OnClickListener() 
{		 	 
   public void onClick(View v) 
   {			  			  
      String food_val = foodVal.getText().toString();
      String food_time = foodTime.getSelectedItem().toString();			  
      finish();
   }
});		

We use the method “finish()” so that the control returns back to the previous activity.

There is an option to delete a food item in this app. To do that we populate the drop down or the spinner widget with items that added previously so that the user can select the item and then click the “Delete” button. How do we populate the spinner widget? This is how we do that:

Spinner list_all_rec = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<String> adapterForSpinner = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); 
adapterForSpinner.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); 
list_all_rec.setAdapter(adapterForSpinner); 

List<String> allrecs = db.getAllRecords(); // get all records from the database 
Iterator<String> itr = allrecs.listIterator();
while (itr.hasNext())
{
   String recdata = itr.next();
   adapterForSpinner.add(recdata);
}

Suppose we want to show a simple message to the user, for a short period, something like an alert() in javascript. One way to achieve this will be by using “Toast”. Here is an example:

CharSequence myText = " Nothing to delete!";
Toast.makeText(context, myText, Toast.LENGTH_SHORT).show();

if we want to return to the previous activity after showing a “Toast Message” for a specified time, we need to use the “finish()” as soon as the Toast Message has completed displaying it, like this:

int DELAY = 2000;
Handler handler = new Handler();
handler.postDelayed(new Runnable() 
{            
@Override
public void run() {
   finish();                  
   }
}, DELAY);		      

In this app, we can delete an item selected from the drop down or spinner. To do that:

public void addListenerOnButton(final ArrayAdapter<String> adapterForSpinner)
{
    final Spinner recSelected = (Spinner) findViewById(R.id.spinner3);
    recSelected.setAdapter(adapterForSpinner);
	 		
    Button btnDelete = (Button) findViewById(R.id.delete_button);
    btnDelete.setOnClickListener(new View.OnClickListener() {		 	 
    public void onClick(View v) {	
    //Get position of item selected and proceed
    int pos = (int) recSelected.getSelectedItemId();
    Object t = recSelected.getItemAtPosition(pos);
    (adapterForSpinner).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    recSelected.setAdapter(adapterForSpinner);
    (adapterForSpinner).remove((String) t);
    db.deleteRecord((String) t); // Delete the record from the database              
              
    finish(); // return to the previous activity
    }
    });		
}

So, we saw how to populate a drop down list and how to select from a list. Now, let us see how to get the current time.

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
String temp_time = today.format("%k:%M:%S %p");

Finally, let us see how to generate random numbers:

Random rand = new Random();
int rand_num = rand.nextInt(i); // here 'i' is an integer

That is the end of dissection of this application. We have seen all the bits and pieces that make up this application. I hope this post was useful to you and you will reuse many of the things shown here in your day-to-day android programming.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: