Android - Coding and launching the application

As with the iOS example, I'll add some basic code for creating two FishingSpot instances, and displaying them in a label. When launched, the application will look as follows:

To start out, each Android application has some basic scaffolding. In this example, we have the following:

  • I've created a package named 'model' to store the basic business objects of the application. (Namely, FishingSpot.java)
  • The Main class is responsible for launching the application. (This was defined when we created the project.)
  • The activity_main.xml file represents the View (or layout) of the application. Within this view, we've defined a label.
  • The AndroidManifest.xml file contains additional specifics about the application.

The layout - activity_main.xml

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. tools:context=".Main" >
  6.  
  7. <TextView
  8. android:id="@+id/displayText"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:layout_centerHorizontal="true"
  12. android:layout_centerVertical="true"
  13. android:text="" />
  14.  
  15. </RelativeLayout>

In the above XML, the main view is a RelativeLayout with a single TextView. The TextView is named displayText, and it's centered both vertically and horizontally.

The Main.java file

  1. package com.crowleyworks.futilefishing;
  2.  
  3. import com.crowleyworks.futilefishing.model.FishingSpot;
  4.  
  5. import android.os.Bundle;
  6. import android.app.Activity;
  7. import android.view.Menu;
  8. import android.view.View;
  9. import android.widget.TextView;
  10.  
  11. public class Main extends Activity {
  12.  
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. View mainView = getLayoutInflater().inflate(R.layout.activity_main, null);
  17. setContentView(mainView);
  18. FishingSpot spot1 = new FishingSpot();
  19. FishingSpot spot2 = new FishingSpot("I3 Reef", 27.315044, -82.593842);
  20. spot2.setComments("Inshore Fishing");
  21. TextView displayView = (TextView)mainView.findViewById(R.id.displayText);
  22. displayView.setText("Spot 1: " + spot1 + "\r\n\r\nSpot 2: " + spot2);
  23. }
  24.  
  25. @Override
  26. public boolean onCreateOptionsMenu(Menu menu) {
  27. // Inflate the menu; this adds items to the action bar if it is present.
  28. getMenuInflater().inflate(R.menu.activity_main, menu);
  29. return true;
  30. }
  31.  
  32. }

The key method in this file is onCreate(). In this method, I use the LayoutInflater to instantiate the layout. Once inflated, I create two FishingSpot instances, locate the TextView, and populate the contents of it with the text from the two FishingSpot objects.