Converting a Java Program into an Android App
Example: A Simple Java Program
The code shown in Listing 1 is a simple Java program called WelcomeMsg.java that asks the user to enter a name. After entering the name, when the user presses Enter, a welcome message appears, including the name the user typed. For example, if the user enters the name "Kelly," the message, "Welcome Kelly!" appears on the screen.
Listing 1 Code in WelcomeMsg.java.
import java.io.* ; #1 class WelcomeMsg { public static void main(String args[]) { InputStreamReader istream = new InputStreamReader(System.in) ; #2 BufferedReader bufRead = new BufferedReader(istream) ; #3 try { #4 System.out.println("Enter your name: "); #5 String name = bufRead.readLine(); #6 System.out.println("Welcome "+ name + " !"); #7 } catch (IOException err) { #8 System.out.println("Error reading line"); } } }
In WelcomeMsg.java, statement #1 imports the packages required for input/output operations. Statement #2 creates a reader called istream. The reader will read from the standard input stream (System.in); that is, from the keyboard. The entered text is stored in the form of Unicode characters. Statement #3 uses the istream reader to convert the data into string form. Statement #4 defines a try..catch block to check for any errors that might have occurred while the reader entered the text. Statements #5 and #6 ask the user to enter a name that is then assigned to the string name. The entered name is then displayed on the screen by statement #8.
When the program is run, it asks the user to enter a name. After the user types a name and presses Enter, the welcome message is displayed with the entered name, as shown in Figure 1.
Figure 1 Output of the Java program
Creating an Android Project Similar to the Java Program
Now let's create the same application in Android. Assuming that the Java Development Kit (JDK) is installed on your machine, download Android Studio. Then follow these steps:
- Double-click the downloaded executable file to install Android Studio.
- After the installation completes successfully, launch Android Studio. The first screen that opens is a welcome screen, displaying icons such as New Project, Import Project, Open Project, and so on. Click the New Project icon to create a new Android project.
- In the New Project dialog, enter information for the new project, as shown in Figure 2.
- In the Application Name box, enter the name of the Android project. Let's name the application WelcomeMsg. The Module Name entry is assigned automatically; by default, it's the same as the application name. To make it a unique identifier, the Package Name assigned is com.yourname.welcomemsg. The location to store the Android project is specified in Project Location box.
- Select API 8: Android 2.2 (Froyo) from the Minimum Required SDK drop-down list, to indicate that the application requires at least API level 8 to run. Select API 17: Android 4.2 (Jelly Bean) as the Target Platform, as we expect this to be the version commonly used by your target audience. Select API 17: Android 4.2 (Jelly Bean) as the platform to compile the project. The default Theme assigned to the project is Holo Light with Dark Action Bar.
- The Create Custom Launcher Icon checkbox is checked by default. This feature allows you to configure the launcher icon for the application. Because we want to create a blank activity, click the Create Activity checkbox and then click the Next button.
- The next dialog is Configure Launcher Icon, which is used for configuring the icon for the application. Because we want to use the default icon for our application, keep the default options selected in the dialog box, and click Next.
- The next dialog prompts us to create an activity. Because we want to create a blank activity, select the BlankActivity option from the list and then click Next.
- The next dialog asks us to enter information about the newly created activity. Name the activity WelcomeMsgActivity. The layout file is assigned the default name activity_main.xml. Keeping that default name for the layout file, click Finish to create the Android project.
Figure 2 Creating a new Android project
Android Studio will automatically create several files and folders for our new Android project (see Figure 3). To customize our new project, we just need to work with two files:
- activity_main.xml. This file is shown at right in Figure 3, in the node WelcomeMsg > src > main > res > layout. It's an XML file in which we'll define the controls (TextView, EditText, Button, etc.) for our Android app's graphical user interface. Through this file, the user interacts with the Android project.
- WelcomeMsgActivity.java. This file is in the node WelcomeMsg > src > main > java > com.yourname.welcomemsg. This Java file loads the controls defined in the layout file activity_main.xml, listens for various events, and runs the required code if any of those events occur.
Figure 3 Project Explorer windows showing files and folders of our new Android project in collapsed mode (left) and expanded mode (right)
Interested in more on this topic? You might like these:
Sams Teach Yourself Android Application Development in 24 Hours, 3rd Edition
By Carmen Delessio, Lauren Darcey, Shane Conder
Organizing Controls in the Layout Container
The most popular approach for creating an Android user interface is via an XML file. The controls or views defined in the XML file for use in the Android app are laid out or organized in a layout container. Android provides several layout containers: RelativeLayout, LinearLayout, GridLayout, FrameLayout, and so on. The default arrangement is RelativeLayout. The simplest is LinearLayout, which displays the controls linearly, one below the other. (The default orientation of LinearLayout is vertical.)
To define the controls for your new Android project, open the activity_main.xml file (also known as the activity layout file) by double-clicking it in the Project window; then replace the default content with the code shown in Listing 2.
Listing 2 Code for activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Enter your name:" android:textSize="24dp"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/user_name" android:textSize="24dp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/click_btn" android:text="Click Me"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/response" android:textSize="24dp" /> </LinearLayout>
The layout file in Listing 2 uses TextView, EditText, and Button controls:
- The TextView control displays a text message on the screen in the specified font, size, and color.
- The EditText control displays a blank textbox to accept data from the user.
- The Button control in most applications displays a button which, when clicked, initiates the desired action. The caption displayed on this Button control is "Click Me."
Because controls are created by hand in XML, there's no default caption for a Button. If you don't assign a caption, the button will appear with no text on it.
In Listing 2, the EditText, Button, and the second TextView controls are assigned the IDs user_name, click_btn, and response, respectively. These IDs will be used to identify and access the corresponding controls in the Java code file. The last TextView control in Listing 2 displays a welcome message to the user.
When laid out in a LinearLayout container, these controls would appear as shown in Figure 4.
Figure 4 TextView, EditText, and Button controls arranged in a LinearLayout container
The title 5554:PhoneAVD in Figure 4 refers to the Android Virtual Device (AVD) in which we'll run our Android app. Android Virtual Devices are explained later in this article.
Writing Java Code to Load the Layout File
The controls defined in the activity layout file need to be loaded to display them on the screen. In addition to loading the controls, we want to perform certain tasks such as associating events to controls, listening for events, and taking action when events occur. To do all these tasks, write the Java code shown in Listing 3 in the Java activity file WelcomeMsgActivity.java.
Listing 3 Code in WelcomeMsgActivity.java file.
package com.bmharwani.welcomemsg; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import android.view.View; public class WelcomeMsgActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); #1 Button b = (Button)this.findViewById(R.id.click_btn); #2 b.setOnClickListener(new Button.OnClickListener(){ #3 public void onClick(View v) { TextView resp = (TextView) findViewById(R.id.response); #4 EditText name = (EditText) findViewById(R.id.user_name); #5 String str = "Welcome " + name.getText().toString() + " !"; #6 resp.setText(str); #7 } }); } }
In this Java activity file, the following tasks are performed:
- Loading the controls that are laid in the activity layout file activity_main.xml through statement #1.
- Accessing the Button control from the activity layout file using its ID, (click_btn) and mapping it to the Button object b (statement #2).
- Associating a click event with the Button control and listening for the occurrence of the click event (statement #3).
- Accessing the TextView control from the activity layout file using its ID, response, and mapping it to the TextView object resp (statement #4).
- Accessing the EditText control from the activity layout file using its ID, user_name, and mapping it to the EditText object name (statement #5).
- Creating a String, str, that contains a welcome message along with the user name entered in the EditText control (statement #6).
- Displaying the string in str through the TextView object resp (statement #7).
We can run the Android project on a physical device as well on a virtual device. For this example, we'll run the Android project by creating an Android Virtual Device (AVD) as described in the next section.
Creating an Android Virtual Device (AVD)
There are many Android devices, each with its own configuration. To test whether your Android application is compatible with a set of Android devices, we'll create an Android Virtual Device to represent that device configuration.
- To create an AVD, select Tools > Android > AVD Manager. An Android Virtual Device Manager dialog opens, displaying a list of existing AVDs. You can use this dialog to work with an existing AVD or create a new AVD.
- Click the New button to create a new AVD. The Create New Android Virtual Device (AVD) dialog box appears.
- Fill in the dialog box as shown in Figure 5.
- AVD Name. Specify the name of the AVD. For this example, use the name PhoneAVD.
- Device. Specify the device for which the application has to be tested. For this example, select the device 5.1” WVGA (480 × 800: mdpi).
- Target. Specify the target API level. Our application will be tested against the specified API, so let's set the target to the latest API, Android 4.2.2 - API Level 17.
- CPU/ABI. Indicates the processor that we want to emulate on our device. Select the ARM (armeabi-v7a) option.
- Keyboard. To use the physical keyboard on the computer along with the one displayed on the emulator screen, check the Hardware Keyboard Present checkbox.
- Skin. Select the Display a Skin with Hardware Controls checkbox. The emulator will be displayed along with physical device buttons on the right side. The controls include basics such as speaker and on/off buttons, Home, Menu, Back, and Search buttons.
- Front Camera/Back Camera. If a webcam is attached to your computer and you want to use it in your application, select webcam0 from the drop-down menu. Choose an emulated option if you don't have a webcam. Leave the default None if the application doesn't require a camera.
- Memory Options. Define the device RAM and VM Heap settings. Leave the default values here.
- Internal Storage. Define the internal storage of the device. Leave the default value (200 MiB).
- SD Card. Extends the storage capacity of the device. Large data files, such as audio and video (for which the built-in flash memory is insufficient), are stored on the SD Card. Let's set the size of the SD card to 128 MiB. The larger the allocated SD card space, the longer the AVD will take to create. Unless it's really required, keep the SD card space as low as possible.
- Snapshot. Enable this option to avoid booting the emulator and start from the last saved snapshot. This option is used to start the Android emulator quickly.
- Use Host GPU. This option enables GPU emulation, which improves the emulator's performance.
- After entering the data, click OK. The newly created AVD, PhoneAVD, is created and displayed in the list of existing AVDs, as shown at right in Figure 5. Click the Refresh button if the new AVD doesn't appear in the list immediately.
Figure 5 Creating a new Android Virtual Device (left). The newly created AVD is displayed in the Android Virtual Device Manager (right)
Our new application is ready to run! Click the Run icon on the toolbar, press Shift-F10, or select Run > Run. You'll be prompted to select the device or AVD on which to show the output. Select the PhoneAVD from the Android virtual device drop-down list, and then click OK. The Android project will run, asking you to enter a name. After typing a name, click the Click Me button, and the new welcome message will be displayed (see Figure 6).
Figure 6 Select the device or AVD to show the project output (left) and enter a name in response to the prompt. Your new Android project shows the welcome message (right)
Summary
You've learned how easily you can convert any Java application into an Android application. Just define the user interface in XML; then access and process the data entered in the user interface controls through the Java code written in the Activity file.
If you want to learn Android programming step by step, check out my book Android Programming Unleashed, and explore the features provided by this great smartphone platform.