Home > Articles > Programming > Java

Converting a Java Program into an Android App

Bintu Harwani, author of Android Programming Unleashed, helps Java programmers understand the basic differences between Java and Android applications and the steps required to convert or re-create a Java program as an Android app.
Like this article? We recommend

Like this article? We recommend

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:

  1. Double-click the downloaded executable file to install Android Studio.
  2. 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.
  3. 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.

    Figure 2 Creating a new Android project

  4. 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.
  5. 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.
  6. 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.

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:


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.

  1. 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.
  2. Click the New button to create a new AVD. The Create New Android Virtual Device (AVD) dialog box appears.
  3. 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.

    Figure 5 Creating a new Android Virtual Device (left). The newly created AVD is displayed in the Android Virtual Device Manager (right)

  4. 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.

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020