1. Trang chủ
  2. » Kinh Doanh - Tiếp Thị

Android app development in android studio java plus android edition for beginners

202 61 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Android App Development in Android Studio Java + Android Edition for Beginners
Tác giả J. Paul Cardle, S. Yamacli
Thể loại independent publication
Định dạng
Số trang 202
Dung lượng 10,07 MB

Cấu trúc

  • CHAPTER 1. INTRODUCTION (0)
    • 1.1. The Android Operating System (9)
    • 1.2. How do Android Apps Work? (11)
    • 1.3. Programming Languages Used For Developing Android Apps (14)
  • CHAPTER 2. SETTING UP YOUR DEVELOPMENT ENVIRONMENT (0)
    • 2.1. Installation of Android Studio (15)
    • 2.2. Installation of Emulators (18)
  • CHAPTER 3. TEST DRIVE: THE HELLO WORLD APP (0)
    • 3.1. General Procedure for Developing an App (23)
    • 3.2. Creating a New Android Studio Project (24)
    • 3.3. Main Sections of the IDE (28)
    • 3.4. Folder and File Structure of an Android Studio Project (29)
    • 3.5. Building the User Interface (31)
    • 3.6. Building the Project and Running on an Emulator (35)
    • 3.7. Running on a Real Device (41)
  • CHAPTER 4. JAVA BASICS (0)
    • 4.1. What is Java? (45)
    • 4.2. Using Android Studio for Java Coding (47)
    • 4.3. Variables in Java (53)
    • 4.4. Logical Decision Making Statements in Java (65)
    • 4.5. Loops in Java (69)
    • 4.6. Methods in Java (74)
    • 4.7. Classes, Objects and Inheritance in Java (79)
  • CHAPTER 5. ANDRIOD APP #1: RED/BLUE LIGHTHEAD (0)
    • 5.1. Creating a New Android Project (87)
    • 5.3. Writing the Main Code of the App (98)
    • 5.4. Building and Running the App (107)
  • CHAPTER 6. ANDRIOD APP#2: BODY MASS INDEX (BMI) CALCULATOR (0)
    • 6.1. General Information (111)
    • 6.2. Adding and Positioning TextViews (112)
    • 6.3. Adding the EditText Widgets (115)
    • 6.4. Adding and Positioning the Button (118)
    • 6.5. Developing the Main Code of the App (119)
    • 6.6. Building and Running the App (125)
    • 6.7. Final Notes (127)
  • CHAPTER 7. ANDRIOD APP #3: SIMPLE DICE ROLLER (0)
    • 7.1. Creating the Project and Adding an Imageview Widget (131)
    • 7.2. Adding the Other Widgets and Setting up the IDs (136)
    • 7.3. Developing the Main Code of the App (136)
    • 7.4. Building and Running the App (140)
  • CHAPTER 8. ANDROID APP #4: THE COMPASS (0)
    • 8.1. Setting up the Required Permissions (143)
    • 8.2. Designing the GUI of the App (146)
    • 8.3. Writing the Main Code of the App (148)
    • 8.4. Building and Running the App (158)
  • CHAPTER 9. ANDRIOD APP # 5: SHOW MY LOCATION: USING GPS AND (0)
    • 9.1. Creating a Map Project (159)
    • 9.2. Creating and Adding an Api Key (161)
    • 9.3. The Default MapsActivity.java File (164)
    • 9.5. Implementing the Required Callbacks (166)
    • 9.6. Populating the Implemented Methods (171)
    • 9.7. Adding the Required Permissions to the Manifest File (180)
    • 9.8. Running Our App and Sending Custom Coordinates to the (182)
  • CHAPTER 10. ANDRIOD APP # 6: S.O.S. MESSAGE SENDER (0)
    • 10.1. Introduction (185)
    • 10.1. Adding the Required Permissions (185)
    • 10.2. Designing the User Interface (186)
    • 10.3. Developing the Main Code (190)
    • 10.4. Building and Running the App (198)

Nội dung

INTRODUCTION

The Android Operating System

Android is an open-source mobile operating system It is a variant of

Linux offers enhanced security, modularity, and productivity for mobile devices Android, developed by the Open Handset Alliance (OHA), has been maintained since its establishment in 2007, with Google as a key member The OHA comprises numerous leading hardware and software companies.

Android was initially developed by Android Inc., which was acquired by Google in 2005 Following this acquisition, Google made Android open-source, leading to significant growth in its adoption By 2016, Android held a remarkable market share of approximately 85%, indicating a lucrative opportunity for investment in Android app development.

Figure 1.1 Market shares of mobile operating systems between 2015-Q4 and 2016-Q3

Android features seven major releases, each with multiple minor updates, and developers often use dessert names to identify these versions, such as KitKat (Android 4.4), Lollipop (Android 5.1), and Marshmallow (Android 6.0), with Nougat (Android 7.0) also gaining traction As Android versions advance, their capabilities improve, but it's crucial for developers to choose the appropriate version for app development, as not all devices operate on the latest release; for instance, an app designed for Lollipop may not function on devices running Froyo Thankfully, Android Studio allows developers to set compatibility options to address these issues.

Android is a versatile operating system used across a wide range of devices, including smartphones, tablets, netbooks, digital TV boxes, handheld gaming consoles, and single-board computers like UDOO Before developing an app, it is essential to identify the specific target device(s) and version(s) to ensure compatibility and optimal performance.

How do Android Apps Work?

Programs operate on various platforms through different levels of software At the lowest level, machine code runs directly on the microprocessor, but due to the complexity of developing applications in this format, operating systems are employed These operating systems serve as a communication and control layer between application software and hardware To create a native application for a specific hardware and operating system, developers utilize a compiler and linker, which transform the source code into an executable file compatible with the operating system For instance, developing an application in C++ requires the compilation and linking process to generate the executable.

Figure 1.2 Machine code – hardware relation

Native applications offer superior speed but face compatibility issues across different platforms, such as the inability to run a native Windows application on Ubuntu and vice versa To address this limitation, the concept of a virtual machine has been developed A virtual machine is software that operates on the host operating system, providing an abstraction layer for developers, allowing application software to run seamlessly on top of it.

Figure 1.3 Operating system layer between the hardware and the app

Figure 1.4 Creating a native executable from the source code

A virtual machine allows application software to operate independently of the underlying hardware and operating system, exemplified by the Java Virtual Machine (JVM) The JVM is compatible with nearly all operating systems and platforms, enabling Java applications to run seamlessly regardless of the specific environment.

Developing applications for virtual machines offers the clear benefit of allowing for a single development process that enables compatibility across multiple platforms However, it is important to note that applications operating on virtual machines tend to have slower performance compared to native applications.

General development process of virtual machine applications is summarized in Figure 1.6

Figure 1.5 Virtual machine between the app and the operating system

Figure 1.6 Creating an intermediate code from the source code – intermediate code is interpreted by the virtual machine

Android applications operate on specialized virtual machines known as the Dalvik Virtual Machine (DVM) and Android RunTime (ART), both designed to function efficiently with limited system resources The executable files for these applications, known as apk files, run on these virtual machines While DVM was the default runtime environment until Android 5.0, ART, introduced in Android 4.0, became the standard from that version onward Both DVM and ART serve the same purpose of executing Android apps across different platforms, but ART offers a significant advantage through Ahead of Time (AOT) compilation, which compiles apps during installation for faster loading times, in contrast to the Just in Time (JIT) compilation used by DVM.

14 faster with lower CPU usage On the other hand, JIT compilation provides lower storage space consumption with relatively longer loading times.

Programming Languages Used For Developing Android Apps

The most recommended way to develop Android apps is by using the Java programming language alongside the Android Software Development Kit (SDK) in the Android Studio environment Alternatively, developers can utilize C++ with the Native Development Kit (NDK) for applications requiring low-level instructions, enhancing efficiency by allowing direct execution on the Android kernel While third-party tools such as Xamarin, Cordova, and React Native offer convenience in app development, they typically do not deliver the same native-like performance as apps developed with official tools.

This article outlines the standard approach to developing Android applications using Java and the Android SDK, with Android Studio as the Integrated Development Environment (IDE) Readers do not need prior knowledge of Java, as the fundamentals are covered in Chapter 4.

This book is designed to help you grasp the basics of programming without overwhelming you with complex topics I will introduce new concepts in a straightforward manner, ensuring you have a solid foundation Remember, learning a programming language is a continuous journey, and this book will provide you with the essential tools to begin your adventure with confidence.

Now, you know the aims and the method of this book Let‟s continue with installation of the Android Studio in the next chapter after having a coffee break.

SETTING UP YOUR DEVELOPMENT ENVIRONMENT

Installation of Android Studio

Android Studio operates on the Java Runtime Environment (JRE), which is compatible with Windows, Mac, and Linux systems To install Android Studio, users must follow the outlined steps, regardless of their operating system.

1 Installation of Java: Java is developed by Oracle Inc There are basically two Java packages: Java Runtime Environment (JRE) and Java Software Development Kit (JDK) JRE is used for running software written in Java programming language whereas JDK is utilized for developing Java software Therefore, installing JRE is adequate for running Android Studio because we will not develop Java software here

To download the JRE, visit the Oracle website at [this link](http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html) Once there, choose the version that matches your operating system, and follow the standard installation steps by clicking "Next" until the installation is complete.

2 Installation of Android Studio and Android SDK

The official Android Studio, which includes the Android Software Development Kit (SDK), can be downloaded from the official site at [developer.android.com/studio/index.html](https://developer.android.com/studio/index.html) The download link for the Windows version is prominently displayed at the top of the page, and additional details can be found by scrolling down.

16 down, you can find the setup files available for download for other operating systems as shown in Figure 2.2

Figure 2.1 Download options for Java Runtime Environment

Figure 2.2 Download options for Android Studio

When you download and install Android Studio, Android SDK will also be automatically installed

3 Installation of SDK updates: After the installation of Android Studio, it is better to check SDK updates For this, run Android Studio and open the SDK manager from Tools  Android  SDK Manager as shown below:

Figure 2.3 Opening the SDK Manager

The SDK Manager window will appear as shown in Figure 2.4

Please open the standalone SDK Manager by clicking the link indicated in Figure 2.4 In the standalone SDK Manager, click on the “Install … packages” as shown below:

Once you have installed the necessary packages, you will have the latest SDK and be prepared for app development However, before testing your app, it is essential to set up the emulators.

Installation of Emulators

Emulators are essential software tools that replicate the functionality of real devices, enabling developers to test applications across various platforms, such as Android phones and tablets, without needing physical access to all devices In Android Studio, these emulators are referred to as Android Virtual Devices (AVDs) Upon initial installation of Android Studio, no default AVD is provided, so developers must create one by navigating to Tools > Android > AVD Manager to begin testing their applications effectively.

Figure 2.6 Launching the AVD Manager

When AVD Manager appears, there won‟t be any AVDs created or installed Please click on the + Create a Virtual Device button as shown below:

AVD Manager will show a detailed window as in Figure 2.8 You can select various devices with different screen sizes and other hardware

You can choose from 20 properties and select device groups such as TV or Phone, with the Phone group set as the default Within this group, the Nexus 5 is also pre-selected After clicking "Next," you'll see options for the Android version of the AVD, as illustrated in Figure 2.9.

Figure 2.8 Creating a new AVD – selecting the device

The recommended targets start from Android 5.1 We can Android 7.0 with Goole APIs (Nougat) as shown in the figure Then, please click

“Next” and give a name you like to the AVD I didn‟t change the defaults in the next screen as shown in Figure 2.10 After clicking

The AVD has been successfully created and is displayed in the AVD Manager, allowing you to test your Android apps on this virtual device, which closely simulates the functionality of a real Nexus 5 phone.

To launch the AVD, simply click the “Play” button located within the square in Figure 2.11 The virtual device will then display as shown in Figure 2.12, allowing you to interact with it just like a real Nexus 5 phone.

After installing both the development environment and the emulator, we‟re now ready to develop our test drive app, Hello World, in the next chapter

Figure 2.9 Selecting the Android version of the AVD

Figure 2.10 Final settings of the AVD

Figure 2.11 Newly created AVD shown in the AVD Manager

TEST DRIVE: THE HELLO WORLD APP

General Procedure for Developing an App

Testing a compiler or development environment can be effectively done using a "Hello World" example, which simply displays the text "Hello World" on the screen While it may not be an impressive application, it serves as a crucial test to ensure that your programming setup is functioning correctly and that you're prepared for more complex projects In our first Android project, we will create an app that displays "Hello, World!" in the center of the device screen This app can be tested on the emulator we previously set up, or, if available, directly on an Android device.

I‟d like to point out general steps of app development before setting off for developing our first app:

1 Creating an Android Studio project,

2 Setting up the User Interface (UI) of the app,

3 Connecting the UI components such as buttons, textboxes, etc to the

4 Coding in Java – the actual programming part

5 Building the project: this means creating the executable (file that actually runs on device or the emulator) This is not difficult as it sounds; Android Studio does the entire job with a single click,

6 Trying the app on an emulator,

7 Running the app on a real Android device (optional),

8 Publishing the app on Google Play (optional).

Creating a New Android Studio Project

Upon launching Android Studio for the first time, users encounter a dialog box with several options: starting a new Android project, opening an existing project, checking out a project from a version control site like GitHub, importing a project from another development environment such as Eclipse, or importing an Android code sample from version control To begin developing your first Android project, select the first option indicated in the dialog.

Figure 3.1 Creating a new Android Studio project for our first app

Upon initiating a new project, a dialog box will prompt you to enter the project settings In the first textbox, labeled “1,” you should input the project name, which will also serve as the app's name; for instance, “Hello World,” though you can choose any name you prefer The subsequent textbox, indicated by “2,” requires the company domain, a unique string akin to a web address that helps differentiate developers in the Google Play market You may use any distinct domain here, especially if you do not plan to upload your app to Google Play, as this example focuses on development for educational purposes.

You have the flexibility to choose any domain for your project, as illustrated in the figure Additionally, it's important to select a preferred location on your computer to save the project files, indicated by "3." You can save your project files in any location that suits you.

After clicking "Next," the Target Android Devices window will appear, where you should select the Phone and Tablet checkboxes Set the Minimum SDK to API 15, which corresponds to Android 4.0.3, ensuring that the app can run on devices with Android version 4.0.3 or higher Once you've made your selections, click "Next" to proceed.

In the user interface template selection dialog, various options are available, such as login and maps activities For our purpose of displaying text on the screen, selecting the Empty Activity is sufficient An activity represents a screen within an app that contains user interfaces, making it essential to include at least one activity in an Android app, as these applications are visual programs featuring one or more user interfaces.

After choosing the default activity in Android Studio, we are prompted to name the activity and its corresponding layout file Since our app will consist of a single activity, we can retain the default names Once we click "Finish," Android Studio will automatically generate the project files and folders, which may take some time, and the IDE will then display as shown in Figure 3.6.

Figure 3.4 Adding an activity template to the app

Figure 3.5 Customizing the newly added activity

Main Sections of the IDE

Android Studio is a powerful integrated development environment (IDE) designed to simplify app development with its numerous features To ensure a thorough understanding of app development concepts, I will provide a gradual explanation of this IDE rather than overwhelming readers with all the details at once Let’s begin by exploring the main sections of Android Studio, as illustrated in Figure 3.6.

Figure 3.6 Basics sections of Android Studio

The sections of Android Studio in the figure above can be summarized as follows:

Section 1 The project files and folders can be viewed from here In addition, new files can be added from this pane We need to double-click on the filenames here to open them in the middle pane The project structure will be explained in detail in the next subsection

Section 2 The opened files can be activated from the tabs located here for viewing in the middle pane

Section 3 This is the middle pane Contents of the active files can be viewed and changed from here For the project shown in Figure 3.6, the

29 file called “MainActivity.java” is the active tab in Section 2 therefore the middle pane in Section 3 shows the contents of this “MainActivity.java” file

Section 4 This section is also controlled via tabs The developer can switch project files, structures, captures and favourites for viewing in the left pane

Section 5 The current or previous compilation, building or debugging processes are shown here For the snapshot of Figure 3.6, it is indicated that the “Gradle build finished in 14 seconds” Gradle is the build system of Android Studio Therefore, the message says that the building engine completed its previous task in 14 seconds

Section 6 This is the Run button of Android Studio When we set up the user interface and write the Java code of a project, we click this button to make the Android Studio build the project (which means creating the executable file from project files) and then we can run it on an emulator or on a real device.

Folder and File Structure of an Android Studio Project

In Android Studio, the file structure of an Android project can be viewed in different ways by using the selection button located above the left pane This allows users to choose their preferred method for viewing the file hierarchy, with the default option being the "Android" mode, which effectively groups files and folders When in "Android" mode, the left pane displays the default files and folders, and users can navigate through the contents of folders using the arrows indicated in the interface.

The default folders (shown inside the rectangles in Figure 3.8) and their contents are explained as follows:

Figure 3.7 Switching among different ways of viewing files and folders

1 manifests folder: This folder has the AndroidManifest.xml file inside

This file contains the configuration parameters of the project such as permissions, services and additional libraries

2 java folder: The source code files written in Java programming language reside in this folder You can see that the java file of the activity named “MainActivity.java” is automatically created in this folder

3 res folder: The resource files are contained in this folder Resources basically mean all the needed files except the source code For example, if we want to include an mp3 file in our project, we place this file inside the “res” folder

Figure 3.8 Default folder and file structure of an Android project

The media, image and layout files residing in the resources folder are accessed via Java code written in MainActivity.java as we‟ll see in a while.

Building the User Interface

Android Studio simplifies user interface design by utilizing the "activity_main.xml" file, found in the "res/layout" folder, which holds all layout information for the active screen.

When opening an xml file outside of Android Studio, it typically launches in a text editor or web browser In contrast, Android Studio processes the xml file and presents the associated activity layout with its components To view the activity_main.xml file in Android Studio, simply double-click it in the project explorer, and the activity layout will appear in the central pane.

Figure 3.9 Layout of the activity

The layout of the activity is displayed in the central pane, featuring the app's name prominently at the top The default empty activity includes a placeholder text, represented within the circle in the illustration above Additionally, a tab is located at the top left of the middle pane.

Clicking on the "Palette" tab within the rectangle displays a menu that allows users to incorporate various user interface objects and layout templates into their activity, as illustrated in Figure 3.10.

When the palette tab is clicked, two panes are opened: the Palette shown by the upper rectangle and the Component Tree pane inside the lower rectangle in Figure 3.10

The Palette in Android Studio features various groups such as Widgets, Text Fields, and Layouts, allowing users to easily drag and drop components into the interface In contrast, the Component Tree organizes these components hierarchically, which will be useful as we build more complex applications in future chapters For now, our focus is on displaying text on the screen, and as illustrated in Figure 3.10, Android Studio has already added a "Hello World" text in the top left corner of the view.

To center a TextView widget within a view, simply select the TextView and use the guiding lines to drag and drop it into the middle position.

Figure 3.11 Drag and drop operation on the TextView

After the drag and drop operation, the TextView will be kept selected

You can modify the TextView properties using the Properties pane located on the right side of the Layout view, as indicated in Figure 3.12 To access the basic editable properties of the TextView, simply click the arrow highlighted in the circle within the figure.

The editable properties of the TextView component, illustrated in Figure 3.13, allow for customization, such as adjusting the text size to 24sp and changing the style to bold for better presentation of the "Hello World" text.

The user interface is now fully set up, and for our initial app, we won't be writing any code since it doesn't require interactivity While future projects will involve significant coding, this particular stage does not necessitate any programming.

Building the Project and Running on an Emulator

Our first Android app is now ready for testing on an emulator, which can be easily done in Android Studio After setting up a Nexus 5 emulator in the previous chapter, the next steps involve building the project, selecting the emulator, and running the app on it.

Figure 3.13 The editable properties of the TextView

To build and run the project, click the “Run” button as shown in Figure 3.13 This action will bring up the emulator and device selection dialog illustrated in Figure 3.14, where you can choose the Nexus device we have previously created.

When using the emulator, it is automatically selected as indicated within the rectangle If a real Android device were connected via USB, it would appear in this dialog Currently, the absence of a connected device triggers a warning at the top of the dialog, as shown in the ellipse Click "Next" to boot the emulator, which will function like a real device The startup time may vary based on your computer's speed, typically taking around 20 seconds to fully load.

Upon launching the emulator, a Nexus 5 screen will appear, resembling a real device experience (excluding calling and SMS functionalities) Additionally, you can utilize the controls on the right sidebar to modify the emulator's general settings as needed.

Figure 3.14 Selecting the target for running our first app

The emulator has launched, but the app is not visible Don't worry! A warning in the main Android Studio window indicates the issue.

Android Studio prompts users to enable Instant Run, a feature introduced in version 2.0 that significantly accelerates the Code → Build → Run cycle By using Instant Run, developers can push code updates directly to the emulator without needing to create a new executable, allowing for quicker feedback on code changes To install this feature, simply click the "Install and Continue" button, as shown in Figure 3.16 Android Studio will quickly download the necessary files, after which users can follow the standard installation process Once the installation is complete, Android Studio will build the project, as indicated in Figure 3.17.

Congratulations on successfully creating your first Android app! After completing the building process, the emulator will display your app, as shown in Figure 3.18 If you see this screen, you have achieved a significant milestone in your app development journey.

To update our app, simply make the desired changes and click the “Re-Run” button, as shown in Figure 3.19 This action prompts the emulator to install the updated version of the app for testing.

As you can see from your very first project, Android Studio offers vast number of possibilities and a user–friendly interface for transforming your ideas into Android apps

Figure 3.17 Android Studio in the process of building our project

Figure 3.18 Emulator running our “Hello World” app

Figure 3.19 The “Re-Run” button in Android Studio

I updated the TextView properties by changing the text to "Hello Android!" and clicked the Re-Run button Android Studio rebuilt the project, and the updated app is now visible on the emulator screen.

Figure 3.20 The emulator running the updated app

To stop the emulator running your app, simply click the red square "Stop" button located next to the "Re-Run" button After stopping the app, the emulator will remain active and ready for the next run, without shutting down completely.

Running on a Real Device

It is also easy to try our app on a real Android device

1 Things to be done on the device: Before running/debugging apps on the real device, we have to enable the Developer Mode on the device For this, on your real device please navigate to Settings  About  Build number or Settings  About Software information  Build number Depending on your device and Android version, the place of the “Build number” may be different however I‟m sure you can find it easily in the Settings  About section Once you find the Build number, tap on it seven times and then your device will show a dialog box saying “You‟re now a developer.”

Once you enable Developer Mode on your device, a new section labeled "Developer options" will appear in the Settings menu Tap on it and activate "USB debugging" to allow debugging through the USB connection This enables you to install apps from Android Studio directly to your device using a standard USB connection.

2 Things to be done in Android Studio: First of all, please enable

“ADB Integration” from Tools  Android  ADB Integration as shown below:

Figure 3.21 Enabling ADB Integration in Android Studio

Now, we need to make our app “debuggable” For this, open the AndroidManifest.xml file by double-clicking on it and add the text android:debuggable="true"

42 inside the element as shown in Figure 3.22

Figure 3.22 Adding the “debuggable” property to our app

We are prepared to test our "Hello World" application on a physical device Upon clicking the "Run" button in Android Studio, a device selection window will be displayed.

Figure 3.23 Selecting the real device

To connect your Asus Zenfone 6, select it from the device selection window, which will vary if a different device is used After selecting your device, click the “OK” button, and the app screen should appear on your device If you see the “Hello World!” message, congratulations! You’ve successfully installed your app on a real Android device Running apps on actual hardware is crucial, as certain functions, such as sending SMS and making calls, can only be performed on real devices.

We successfully developed our test drive app, "Hello World," by mastering key skills such as creating an Android Studio project, utilizing user interfaces and widgets, setting up emulators, building the app, and running it both on the emulator and a real device.

Our app currently lacks interactivity, merely displaying text on the screen To create a functional app, we need to program it, and Java is the primary programming language for Android development In the next chapter, we will cover the basics of Java, equipping us to turn our ideas into operational Android applications Before diving into our Java lecture, let's take a coffee break—opt for a 3-in-1 coffee for an extra boost of glucose.

JAVA BASICS

What is Java?

We have successfully developed our first app, which currently displays text on the screen but lacks user interaction To create an engaging and interactive app, we must provide specific instructions on its functionality, which is achieved through programming languages.

Computers are often perceived as "stupid" because they require precise instructions to perform tasks For instance, after a long workday, while stuck in traffic on the M4 motorway near Oxford, you might think about dinner Remembering the frozen chicken korma in the fridge, you call your wife (using hands-free, of course) to ask her to prepare the meal.

You – Hi darling, hope you‟re OK

Your wife – Thanks, a bit tired You?

I’m feeling quite hungry and would appreciate it if you could prepare a frozen chicken korma for me I believe there’s some in the fridge, and I know you enjoy it as well.

Your partner – Yummy yummy I‟ll darling, it will be sizzling when you arrive See you in a while, bye (A caring wife!)

She retrieves the frozen korma from the fridge, unpacks it, pierces the film lid, and sets the timer to cook it in the microwave or oven She also prepares the included pilau rice without needing any prompts In contrast, if you had a robot wife with a computer brain, the interaction would be more like a simple greeting, "Hi darling, hope you’re OK."

Robot wife – Thanks You OK? (not in a romantic tone!)

You – Very tired And also very hungry Could you please cook a frozen chicken korma for me? There should be some in the fridge

The robot wife inquires about the frozen korma in the fridge and asks if she should also prepare pilau rice, offering options for normal or overcooked rice She further questions whether garlic bread is desired and seeks to know the preferred time for the meal to be ready.

You – Stop, stop please I‟ll drive to a restaurant

Robot wife – I don‟t understand, you are nonsense

Any programmable digital device functions similarly, requiring precise instructions through programming languages Numerous programming languages exist for software development across various platforms, with their popularity and rankings available on the TIOBE index website Choosing the right programming language can be challenging, as no single language is universally superior; each has its strengths and weaknesses.

According to the TIOBE index, Java has maintained its position as the most widely used programming language for several years due to its platform independence, extensive libraries, object-oriented nature, and strong security and robustness These attributes make Java the primary choice for developing Android applications, highlighting the importance of mastering Java fundamentals for anyone interested in Android app development.

47 programming language After learning Java, we‟ll use Android SDK libraries with Java and develop Android apps

For learning Java, you can utilize standalone Java compilers or Java-specific IDEs, but there's also a convenient method to run Java code within Android Studio Since Android Studio is already set up, we will leverage it for our Java coding practice.

Using Android Studio for Java Coding

To begin, launch Android Studio and create a new Android project, naming it as desired and selecting any Android version and screen layout Once the project loads, you will see the project files and folders displayed in the left pane of Android Studio.

Figure 4.1 Default file structure of a new Android Studio project

To experiment with Java code, create a new Java file by right-clicking on a Java folder, such as com.example.atomic.javabasics1, and selecting New → Java Class from the menu.

Figure 4.2 Creating a new Java Class

In Java, every program is structured around classes, so we begin by creating a new Java class It’s important to name this class without any spaces or special characters; for example, I chose the name "JavaBasics." After naming the class, simply click "OK" to proceed.

Figure 4.3 Creating a new Java file (Java class)

It is worth noting that the file kind is class as shown inside the ellipse in

Figure 4.3 After clicking “OK”, Android Studio will create the new Java file called JavaBasics.java and show it in the middle pane as shown in

Figure 4.4 The contents of the new Java file

The new Java file has the following default lines of code: package com.example.atomic.javabasics1; public class JavaBasics {

The first line defines a package that contains our new Java class Java classes are organized in packages Packages are like folders on your computer that hold several files inside

The second line is the main class definition All programs are classes in

In Java, every program must include a class definition for successful compilation It is essential that the class name corresponds exactly to the filename; for example, if the file is named JavaBasics.java, the class should also be named JavaBasics.

The program's contents are enclosed within curly brackets that appear immediately after the class name definition on the second line and are closed on the third line, as demonstrated in Code 4.1.

By default, a Java file contains only basic package and class definitions, resulting in an empty class body Consequently, when this Java program is compiled and executed, it performs no actions.

Java programs are written in source files with a java extension, which are compiled by the Java compiler into class files These class files are executed on a Java Virtual Machine (JVM), illustrating the essential flow of Java program execution.

Figure 4.5 Compilation and execution of a Java program

Anyway, let‟s see how we can make a “Hello World” program from our JavaBasics.java file In a Java source file, the following code line prints a text in the terminal window:

System out println("the text to be printed");

In Java, the System.out command is used to display output, while the println() method prints the text enclosed in double quotation marks By placing "Hello World" within this method, you can successfully print the message to the screen, as demonstrated in the following code example.

System out println("Hello World");

In a Java file, code must be positioned within the curly brackets of the class definition To create a basic "Hello World" program, we can incorporate Code 4.3 into Code 4.1, starting with the package declaration `package com.example.atomic.javabasics1;` followed by the class definition `public class JavaBasics {`.

System out println("Hello World");

To successfully compile and run a Java program, it must include a main method, which serves as the entry point for execution Without this method, the compiler will generate an error and prevent the program from running By incorporating the main function, we can create a valid "Hello World" program in Java, structured as follows: package com.example.atomic.javabasics1; public class JavaBasics { public static void main(String args[]) {

System out println("Hello World");

The main function is defined as public static void main(String args[]) and is typically not explained initially, with instructors advising students to accept it for now However, it's important to note the general structure of the main method.

This method has three keywords in the front: public , static and void Their meanings can be summarized as follows:

1 public : the main method will be accessible from anywhere,

2 static : the main method doesn‟t belong to a specific object and

3 void : the main method will not return a value

These will be clearer when we learn classes in the last subsection of this chapter

The main method accepts input arguments in the form of a String array, allowing it to process multiple text-based inputs This concept will be further clarified as we explore functions and their arguments in greater detail.

Don't be discouraged by the initial complexity of Java; while writing a simple "Hello World" program may seem time-consuming and confusing, this length is a strength of the language Java's structured and organized nature offers developers greater flexibility and reduces the likelihood of errors in coding.

After adding Code 4.5 to the JavaBasics.java file, you can execute your Java "Hello World" program Locate the JavaBasics.java file in your Android Studio file explorer, right-click on it, and choose the option to run 'JavaBasics.main()'.

Figure 4.6 Running our Java program in Android Studio

Android Studio compiles the JavaBasics.java file and executes it, a process that may take some time Once completed, the program's output is displayed in the Terminal window located at the bottom pane of Android Studio, as illustrated in Figure 4.7.

We have now written, compiled and run our first Java application in Android Studio without the need of using any other development

53 environment Let‟s continue with learning about variables used in Java in the next subsection

Figure 4.7 Terminal output of our Java program in Android Studio

Variables in Java

Variables are entities that store information, similar to boxes that hold data The process of creating a variable is known as variable declaration, while assigning a value to it during this process is referred to as variable initialization Values can be assigned to variables either at the time of declaration or later, based on specific conditions.

Just as real world boxes that can be used to hold different things like a sugar box, a match box or a component box, variables in programming languages also have different types

Java is a statically and strongly typed programming language, requiring variable types to be defined at creation and preventing any later changes It categorizes variable types into two distinct groups.

1 Primitive variable types: These variable types hold single data at a time In other words, primitive variables hold primitive values Primitive variables always have values Primitive variables exist from their creation to the end of a Java program

2 Reference variable types: These “non-primitive” types are dynamic variables; they can be created and erased before the program ends These variables store the addresses of objects they refer to Unlike primitive

54 types, reference types may have the value null, which means non- existence The null value means the absence of its value

These may seem confusing at first but please just try to remember that primitive types are used to store actual values but reference types store a handle to an object

The widely used variable types used in Java are shown in the following figure:

Figure 4.8 Variable types in Java

Let‟s explain the primitive data types first

1 Boolean variables: Boolean variables have the property of having only two distinct values: true or false We can think booleans as a yes–no question like “Is the screen background blue?” The answer can only be “yes” or “no” Instead of the words “yes” or “no”, Java uses true or false The following code defines a Boolean variable called myBoolean and assigns true as its value during the declaration: boolean myBoolean = true;

In this code snippet, the keyword "boolean" is used to define a boolean variable, with the variable name "myBoolean" following it The equal sign (=) assigns the value "true" to this newly created variable, as illustrated in Figure 4.9.

Figure 4.9 Assigning true to the variable myBoolean

In Java, statements must end with a semicolon (;) to avoid compilation errors This structure applies to various variable types, including Boolean variables, which are commonly used for decision-making in applications that involve complex logic.

2 Integer variables: Integer variables are widely used in Java An integer variable basically stores an integer value (a whole number that doesn‟t have fractional part) As it can be seen from Figure 4.8, integer variables have several forms: int , long , short , char and byte Let‟s see what these types are used for:

Int type variables are designed to hold integer values For instance, the following code snippet demonstrates how to declare an integer variable and assign it the value of 5 upon creation, effectively initializing the new int variable with this value.

In Java, integer variables are defined using the keyword "int." Once an int variable is declared and initialized, it can be used for mathematical operations The provided Java source code demonstrates the creation and initialization of an int variable, followed by the addition of another integer value, ultimately displaying the result on the terminal screen.

System out print("Sum = " + myInteger);

Let‟s analyse what happens in the above code:

 An int variable called myInteger is created and initialized to 5 on the fourth line

 In the fifth line, this variable is added to the number 7 and then the result is assigned back to myInteger by the line myInteger = myInteger + 7; as shown below:

 Finally, the sixth line System.out.print("Sum = " + myInteger); prints out the value of myInteger

Please note that, its value will be written next to the expression “Sum =

” in this code This Java program and its output are shown in Figure 4.11

More arithmetic and logic operations can be applied on integer variables as we‟ll learn in our Android projects in the upcoming chapters

Figure 4.11 int type definition and addition operation in Java

 int type variables can store numbers from –2 147 483 648 to +2

In programming, different integer types are used to store numerical values, each with specific limits Short type variables can hold numbers ranging from -32,768 to +32,767, making them suitable for smaller values For larger numerical requirements, such as in rocket science, long type variables are ideal, accommodating a vast range from -2^63 to 2^63 - 1 While the definition and assignment of int, short, and long types are consistent, the primary differences lie in the size of the numbers they can store and the corresponding memory they occupy.

 Another integer variable type is byte A byte can store numbers between –128 to 127 In computers, a byte represents 8 bits (binary digits) 8 bits can have the values between 8 zeros (00000000) to 8

In Java, the byte data type can hold values ranging from -128 to 127, encompassing a total of 256 distinct numbers For example, in the provided code snippet, a byte variable 'a' is initialized with the value 100 and printed to the terminal The code is structured within the package com.example.atomic.javabasics1 and defines a public class named JavaBasics3, with the main method serving as the entry point for execution.

If we try to assign a number which is not in the range of –128 and 127 to a byte , the compiler gives an error as shown in Figure 4.12

In this example, the variable 'a' is defined as a byte, which cannot hold the value of 300 When an incorrect statement is made, the Java compiler highlights the erroneous code with a red underline and displays a red bulb at the affected line(s) By clicking on these red bulbs, users can receive suggestions for correcting the expression.

 The last but not the least important integer variable type is char It stores value between 0 and 65535 which constitutes 16 bits (= 2

The `char` type in Java is utilized to represent individual characters, which can include letters, numbers, or symbols found on a keyboard In computing, these characters are typically mapped to integers using the ASCII (American Standard Code for Information Interchange) table Java's `char` type employs the Unicode system, which extends ASCII to accommodate a broader range of characters For instance, in the following code snippet, the character 'd' is assigned to a variable named `myChar` of the `char` type: ```javapackage com.example.atomic.javabasics1;public class JavaBasics3 { public static void main(String args[]) { char myChar = 'd'; }}```

In Java, characters assigned to char variables must be enclosed in single quotes to indicate their character type to the compiler The output generated by this code is displayed in the terminal below.

Figure 4.13 char definition in Java

Logical Decision Making Statements in Java

Decision making is a widely in programming as in daily life problems

We frequently make logical decisions in daily life such as:

- “If their coffee is tasty I‟ll get another one, else I‟ll grab a tea”

- “If it‟s rainy I‟ll take my umbrella, else I‟ll not”

In programming, decision-making statements determine whether a condition is satisfied, similar to real-life scenarios Java offers two primary decision-making constructs: the if-else statement and the switch-case block.

The if–else structure is a fundamental conditional statement in programming that executes specific code based on whether a condition is met When the condition is true, the code within the if block runs; if it is false, the code in the else block executes For instance, to illustrate a rainy versus not rainy scenario using an if–else block, the code would check if it is rainy and proceed accordingly.

I‟ll not take my umbrella

In Java, we can determine if two numbers are equal by utilizing an if-else statement For instance, within the main method of a class, we can declare two integer variables, 'a' and 'b', both assigned the value of 4 By employing the conditional check 'if (a == b)', we can evaluate their equality.

System out println("a and b are equal");

System out println("a and b are not equal"); }

Code 4.17 (cont‟d from the previous page)

 In this code, two integer type variables, a and b , are created and initialized to 4

 In the next line, the if statement checks if a and b are equal

 The comparison operator == is used to check the equality

If the comparison evaluates to true, the code within the if block executes, displaying the message "a and b are equal" on the terminal screen.

If the comparison yields a false result, the code within the if block executes, displaying the message "a and b are not equal" on the terminal screen.

Since we initialized both a and b to 4, they are equal and the Java compiler executes the code inside the if block as follows:

Figure 4.18 if –else example in Java

When we change one of the numbers to something other than 4, the code inside the else block is executed as shown in Figure 4.19

Figure 4.19 if–else statement in Java when the condition not satisfied

Nested if-else statements allow for multiple conditions to be evaluated sequentially, executing the corresponding code block when a condition is met If none of the specified conditions are true, the final else block is executed This structure ensures that the program checks each condition from top to bottom, providing a clear path for decision-making An example of nested if-else statements can be found in the provided code snippet, illustrating how these statements function in Java.

System out println("a and b are equal"); } else if(a > b) {

System out println("a is greater than b"); } else {

System out println("a is lower than b"); }

Code 4.18 (cont‟d from the previous page)

Figure 4.20 Nested if–else statements in Java

Nested if–else statements can become cumbersome and error-prone as the number of conditions increases To simplify the process of evaluating multiple conditions, switch–case statements are often utilized These statements function similarly to nested if–else statements but provide a more straightforward approach for checking various conditions For instance, a switch–case statement can be used to assess a student's grade, as illustrated in the provided code example.

System out println("Your grade is excellent."); break; case 'B':

System out println("Your grade is very good."); break; case 'C':

System out println("Your grade is good."); break; case 'D':

System out println("Your grade is low You have to take the course again."); break; case 'E':

System out println("Your grade is very low You have to take the course again."); break; default:

System out println("Not a valid grade");

Code 4.19 (cont‟d from the previous page)

In this example, the grade variable is of type char and is evaluated against the characters 'A', 'B', 'C', 'D', and 'E' Since the variable is initialized to 'B', the corresponding code block for case 'B' will execute The presence of break; statements in each case block is crucial, as they terminate the switch block once a case is matched Additionally, the default: block at the end of the program is important; it executes when none of the specified cases are met, handling any characters entered that are not 'A', 'B', 'C', 'D', or 'E'.

„C‟, „D‟ and „E‟, the program will print “Not a valid grade” on the terminal A default block is not mandatory in Java but useful as we‟ll see in Android app development chapters

Selecting if–else or switch–case: If the checked variable has a lot of discrete values, switch–case blocks are easier to use

We‟ll use decision making statements a lot in Android app development Let‟s now study another widely used concept: loops.

Loops in Java

Performing an operation in a repeated form is frequently needed in programming These repetitions are performed using loops Programming would be very difficult and long without loops For

70 example, let‟s try to find the sum of numbers from 1 to 50 Without loops, what we would do is as follows: int sum = 0 sum = sum + 1 sum = sum + 2 sum = sum + 3

(44 more lines of code here) sum = sum + 48 sum = sum + 49 sum = sum + 50

To achieve the desired outcome, an additional 44 lines of code are needed, as indicated by the ellipsis This straightforward task demands a total of 51 lines of code if loops are not utilized, making it susceptible to errors It is essential to strive for the shortest code possible in programming to minimize the risk of mistakes.

There are three types of loops in Java: for loop, while loop and do-while loop

1 for loop: We use for loops when we know how many times an operation will be performed The general structure of a for loop is as follows: for (type counter = initial value; counter check; counter increment/decrement statement) {

Code to be performed repeatedly

 The counter is an integer variable

 The counter variable is incremented or decremented according to the expression in ( counter increment/decrement statement ) after each cycle

 After each increment/decrement, the counter is checked if the ( counter check ) is still satisfied If it is satisfied, the loop continues; if not satisfied, the loop ends

In this article, we will demonstrate how to calculate the sum of numbers from 1 to 50 using a for loop in Java We will create a class named `JavaFor` within the package `com.helloworld.quantum.helloworld` Inside the `main` method, we initialize a variable `sum` to 0, and then use a for loop to iterate through numbers from 0 to 49, adding each number to the `sum` variable This example illustrates the basic structure and functionality of a for loop in Java programming.

System out println("Sum is " + sum);

This code initializes a variable named 'sum' to store the total and sets up a for loop with an integer variable 'counter' that iterates from 0 to 50 During each iteration, the 'counter' is incremented by 1 using the expression 'counter++', resulting in values ranging from 0 to 50.

The loop continues to cycle through values from 3 to 50 However, when the counter reaches 51, the loop condition of counter ≤ 50 is no longer satisfied, leading to the termination of the loop without executing any operations for counter = 51.

The variable sum starts at 0, and within a loop, the counter is incrementally added to it using the expression sum = sum + counter This process effectively totals the numbers from 0 to 50 Ultimately, the calculated sum of these numbers, which amounts to 1275, is displayed on the terminal screen as shown in Figure 4.21.

2 while loop: while loops can be used even when we don‟t know at which iteration the cycle will end The main difference of for and while loops is that the incrementing method of the loop variable is specified inside the loop therefore it provides a bit more flexibility The calculation of the sum of numbers from 0 to 50 using a while loop is shown in Code 4.23

In Java, a while loop can be used to calculate the sum of integers up to a specified limit In the provided example, the program initializes a sum and a counter to zero, then iteratively adds the counter to the sum while the counter remains less than a predefined value, P, incrementing the counter with each iteration This demonstrates a fundamental programming concept in Java, showcasing how loops can effectively manage repetitive tasks.

System out println("Sum is " + sum);

The loop variable "counter" is initialized prior to the while loop, which continues to execute as long as the condition "counter

Ngày đăng: 27/09/2021, 14:31

TỪ KHÓA LIÊN QUAN

w