Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Building Android Projects with Kotlin: Use Android SDK, Jetpack, Material Design, and JUnit to Build Android and JVM Apps That Are Secure and Modular (English Edition)
Building Android Projects with Kotlin: Use Android SDK, Jetpack, Material Design, and JUnit to Build Android and JVM Apps That Are Secure and Modular (English Edition)
Building Android Projects with Kotlin: Use Android SDK, Jetpack, Material Design, and JUnit to Build Android and JVM Apps That Are Secure and Modular (English Edition)
Ebook764 pages5 hours

Building Android Projects with Kotlin: Use Android SDK, Jetpack, Material Design, and JUnit to Build Android and JVM Apps That Are Secure and Modular (English Edition)

Rating: 0 out of 5 stars

()

Read preview

About this ebook

As an ambitious Kotlin programmer or Android developer, are you frequently baffled by the options available to do a specific task? Or why a single solution is superior to the others for doing this Android task?
And most importantly, how can you do Kotlin programming employing this superior alternative?

The book ‘Building Android Projects with Kotlin’ teaches you all you need to know to create an incredible Android application. It describes the fundamentals of Android, its components, and their purposes. This book also emphasizes the significance of clean code, modular code writing, and architectural patterns. It teaches the reader how to analyze the performance of a layout, how to select the best picture format and the fundamentals of multiscreen application development.

This book discusses the creation of chat applications, video-sharing applications, and video games. The book will discuss best practices, libraries, functional requirement collecting, and feature development while constructing and explaining the functionalities of these applications. A range of topics like Android fundamentals, layout and image optimization, practical development tools, writing clean code, multiscreen app development, creating chat apps, video sharing applications, and games will be learned throughout this book.
LanguageEnglish
PublisherBPB Online LLP
Release dateSep 8, 2022
ISBN9789355510921
Building Android Projects with Kotlin: Use Android SDK, Jetpack, Material Design, and JUnit to Build Android and JVM Apps That Are Secure and Modular (English Edition)
Author

PANKAJ KUMAR

Dr. Pankaj Kumar completed his master’s and doctorate degrees at the Gurukula Kangri Vishawavidyalaya, Haridwar, Uttarakhand (India). He has more than ten years of teaching and research experience. His research interest and expertise include the areas of rhizosphere microbiology, bacterial characterization and biofertilizers. He has published several research papers in national and international journals. He is also a co-editor of the book Rhizosphere Engineering (Elsever, 2022) with Prof. R. C. Dubey. He is also coauthor of An Objective Compendium on Food Science (Brillion publishing, 2022). He is life members of Association of Microbiology of India (AMI), New Delhi and Indian Science Congress, Kolkata, West Bengal and serving as reviewers and editorial board members of national and international journals. Currently, Dr. Pankaj is affiliated with the Department of Microbiology at the Dolphin (PG) Institute of Biomedical and Natural Science, Dehradun, Uttarakhand, India.

Related to Building Android Projects with Kotlin

Related ebooks

Programming For You

View More

Reviews for Building Android Projects with Kotlin

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Building Android Projects with Kotlin - PANKAJ KUMAR

    CHAPTER 1

    Creating Hello World Project

    Before going ahead, the recommendation is to do the setup of Android Studio on your development machine. Any latest version would work for each chapter in this book.

    In this chapter, we are going to create our first Hello World application for Android by creating a project using Android Studio Templates. We will see the project structure and know about each file added by default to the Hello World project.

    We will also read about Templates, Modules, the creation of the launcher icon, setting up emulator, and at last, we will know about some important tools that would be used while developing and debugging Android applications.

    Structure

    Creating a project from Android Studio Template

    Introducing templates

    Understanding files in the created project

    Creating a custom launcher icon

    Creating android virtual device (AVD)

    Running the Hello World application

    Important tools to develop, debug, and improve android applications

    Gradle

    Logcat

    Android lint

    Layout inspector

    Memory profiler

    Database inspector

    Objectives

    The objective of this chapter is to let you know how to create a new project using the Android Studio template, the basics about files that are part of the Android project, creating a launcher icon, and creating an emulator.

    You will also know about important tools which would help develop and debug Android applications.

    Creating a project from Android Studio Template

    To start the development of an Android Application, we need to create a project with the basic setup. Android Studio helps you do this. It provides you with the basic setup of the project with different types of commonly used projects. Those are known as templates. We need to choose the template depending on our requirement or whichever would be closer to our requirement. We will read more about the template later in this chapter.

    So first, we will create a project using Android Studio Template. To do that, perform the following steps to create a new project:

    Run Android Studio.

    Click on + Create New Project on the Welcome Window as shown in figure 1.1:

    Figure 1.1:Welcome window of Android Studio

    Create a New Project window, which will be shown in figure 1.2. Go to the Phone and Tablet tab, select Empty Activity template, and press Next:

    Figure 1.2:Choosing a template from the Project Template list

    On the Project Configuration window, you will require to add the following configurations, as shown in figure 1.3:

    Figure 1.3:Configuring the project

    Let us see these parameters in detail, which requires while creating the project, as shown in the preceding figure 1.3:

    Name: The name which you see on the phone for each application. Android will identify your application by this name. As of now, let us put "Hello World" in this field.

    Package Name: Best practice is to create a unique package name. To do that, you can put your company domain with the project name, like com.uniquecompany.app_name. Let us put com.bpb.android.helloworld for the Hello World project.

    Save location: Choose the physical location of the project where the project will be created. You can keep it default too.

    Language: There are two options, Java/Kotlin, and we are here to learn Kotlin; choose Kotlin as language.

    Minimum SDK: This option is a filter for the Play Store and Android system to allow your application to be installed on only those devices which are running on either the given min SDK version or newer.

    Android studio will show the percent of devices in the world that can use your world depending on the version you choose. So, for our Hello World project, let us choose API21.

    Click on Finish.

    Introducing templates

    Templates are a set of files for common uses and are added to your application automatically when you choose one of them. They follow design and development best practices to get you on the right track to create your awesome application.

    Android Studio gives you some commonly used templates, which can be added to your app in two ways:

    From create project wizard (starter templates): These templates can be chosen when you are creating a new project as shown in the preceding figure 1.2, for example, template for Login Screen, Screen with Tabs, and so on.

    Templates for the existing project: If you already have created a project and you need to add any template (let us say you want to add any screen), Android Studio gives you this ability too. From Tool Bar, click on File -> New -> and choose the category of template -> and choose a template, as shown in figure 1.4.

    For example, if you want to add a Login Screen to our Hello World Project, then it can be added by following these steps, File | New | Activity | Login Activity:

    Figure 1.4:Templates for existing project

    You should explore all templates and make practice using these templates in your application. There are benefits of using these, like you need to write less code and get prewritten code that follows the best practices of Android.

    Understanding files in the created project

    When Android Studio opens the project in the workspace, you will see a workspace similar to figure 1.5:

    Figure 1.5: Default Project structure

    Each file has an important role to play in our project. These files help us in creating a build, designing UI, and writing Kotlin code for our application. Some of these files help us to customize builds so we can create a different type of application from the same code base, like the paid and free versions of the application.

    AndroidManifest.xml

    This file contains information which is for the Android operating system, Android build tools, and the Google Play store. In general, this file has information about:

    Each Android component (activity/broadcast receiver/content provider or services).

    Which hardware or software feature is required to use your application? For example, Camera, NFC, and so on.

    Permissions that are required by your application. For security reasons, Android has a set of permissions that need to be requested from an application if doing any such task which needs permission.

    You will know more about this file in Chapter 4: Development of Chat Application, Chapter 6: Development of Video Sharing Application, and Chapter 8: Development of First Game.

    Java/

    This directory keeps Java/ Kotlin code for the application. Java/ is the default structure, and we can rename it too, like kotlin/. For the Hello world project, the code of MainActivity.kt is as follows:

    package com.bpb.android.helloworld

    import android.os.Bundle

    import androidx.appcompat.app.AppCompatActivity

    class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    }

    }

    res/

    This is the most interesting directory in an Android Project. You will know more about this directory in Chapter 4: Development of Chat Application, Chapter 6: Develop Video Sharing Application, Chapter 8: Development of First Game, and Chapter 9: Adding Support for Big Screens. Till then, just remember that this is the directory that keeps images (drawable), screen designs (layouts), texts used in the app, fonts, and so on. As the UI file is present in this directory, let us see what is inside a layout which shows Hello World text:

    1.0 encoding=utf-8?>

    xmlns:android=http://schemas.android.com/apk/res/android

    xmlns:app=http://schemas.android.com/apk/res-auto

    xmlns:tools=http://schemas.android.com/tools

    android:layout_width=match_parent

    android:layout_height=match_parent

    tools:context=.MainActivity>

    android:layout_width=wrap_content

    android:layout_height=wrap_content

    android:text=Hello World!

    android:textColor=@color/black

    app:layout_constraintBottom_toBottomOf=parent

    app:layout_constraintLeft_toLeftOf=parent

    app:layout_constraintRight_toRightOf=parent

    app:layout_constraintTop_toTopOf=parent />

    In this XML, you see ConstraintLayout, which is a type of ViewGroup that acts as a container of Views, and TextView in a View, which is used for showing texts in Android Applications. In our Hello World project, we are using this View to show the text Hello World.

    build.gradle

    You can see two different build.gradle files in preceding figure 1.5:

    The first file is for project-specific configurations. In general, configurations added to this file will be applied to each module used in the application. You can use allprojects {} or subprojects {} to define settings for all other modules, as follows:

    allprojects {

    repositories {

    google()

    jcenter()

    }

    }

    The second build.gradle file in the preceding figure 1.5 contains configuration/ dependencies for a module. Dependencies can be added using implementation with library identifier and the version available on Google, Jcenter, or Maven repositories. For our Hello World project, these dependencies can be written as follows:

    dependencies {

    implementation org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version

    implementation ‘androidx.core:core-ktx:1.3.2’

    implementation ‘androidx.appcompat:appcompat:1.2.0’

    implementation ‘com.google.android.material:material:1.2.1’

    implementation ‘androidx.constraintlayout:constraintlayout:2.0.4’

    testImplementation ‘junit:junit:4.+’

    androidTestImplementation ‘androidx.test.ext:junit:1.1.2’

    androidTestImplementation ‘androidx.test.espresso:espresso-core:3.3.0’

    }

    Here testImplementation and androidTestImplementation act the same as implementation, but these make libraries available only in the test and androidTest source set.

    NOTE: Modules are the concept of separation of concerns, where you divide application features into modules. Creating features as modules enables reusability of the feature into different applications and a few awesome features of Android like App Bundle and Instant Apps. Let us assume you are creating a messenger application that provides three different ways to communicate, call, message, and video call. In this case, call, message, and video features can be created as separate modules. One thing to remember is that each module can be debugged, build, and tested independently.

    In preceding figure 1.5, the app is the module. In later chapters, you would be learning to add configurations into Gradle files.

    gradle-wrapper.properties

    You can specify the Gradle version in this file. The following is the code of gradle/wrapper/gradle-wraper.properties file:

    distributionBase=GRADLE_USER_HOME

    distributionPath=wrapper/dists

    zipStoreBase=GRADLE_USER_HOME

    zipStorePath=wrapper/dists

    distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip

    The preceding code sets the Gradle version 6.5 by setting the value for distributionUrl. Note that this file will be created with default values when you create a new project. You only need to modify this file when you want to change the Gradle version.

    gradle.properties

    Project-wide Gradle settings, you will find in any Android project. The purpose of using this file is to provide start-up options for Gradle such as Gradle daemon’s maximum heap, use of AndroidX package structure, code style, and so on, as follows:

    # Project-wide Gradle settings.

    # IDE (e.g. Android Studio) users:

    # Gradle settings configured through the IDE *will override*

    # any settings specified in this file.

    # For more details on how to configure your build environment visit

    # http://www.gradle.org/docs/current/userguide/build_environment.html

    # Specifies the JVM arguments used for the daemon process.

    # The setting is particularly useful for tweaking memory settings.

    org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8

    # When configured, Gradle will run in incubating parallel mode.

    # This option should only be used with decoupled projects. More details, visit

    # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects

    # org.gradle.parallel=true

    # AndroidX package structure to make it clearer which packages are bundled with the

    # Android operating system, and which are packaged with your app"s APK

    # https://developer.android.com/topic/libraries/support-library/androidx-rn

    android.useAndroidX=true

    # Automatically convert third-party libraries to use AndroidX

    android.enableJetifier=true

    # Kotlin code style for this project: official or obsolete:

    kotlin.code.style=official

    The preceding codes are from our Hello World project, and these codes are added by default when you create the project. This file is optional, and these values can be overwritten by Gradle command-line arguments or a file located at USER_HOME/.gradle/gradle.properties.

    You can also set environment variables for the build in this file, where systemProps would be prefixed, as follows:

    systemProp.gradle.wrapperUser=myuser

    systemProp.gradle.wrapperPassword=mypassword

    proguard-rules.pro

    ProGuard is a tool to shrink, optimize, and obfuscate the code of the application. This file contains rules for the tool. You will read more details about this tool in Chapter 5, Publishing the Application.

    settings.gradle

    This file would be one file per project, so you will find only one copy of this file for a project, even if you are using more than one module in the project. The main role of settings.gradle is to define all submodules, as follows:

    include ‘:app’

    rootProject.name = Hello World

    In our Hello World project, we have only one module app, so you see only one entry of includes :app. In case you use more than one module for the project, there will be more than on include statements as follows:

    include ‘:app’

    include ‘:module1’

    include ‘:module2’

    local.properties

    This file is autogenerated and contains local environment properties for the build system, like the path of SDK/ NDK, and so on, as follows:

    sdk.dir=/Users/your_name/Library/Android/sdk

    You should not modify this file as this file is autogenerated and your changes will be erased. Most importantly, this file should not be added to your code repository.

    After reading the overview of each file in the project structure, let us change the launcher icon.

    Creating a custom launcher icon

    When you go to the application list on an Android device, it shows the application icon and name for all installed applications. That icon is known as the Launcher icon. While creating a new project, Android Studio adds the default launcher icon, which works well. But if you want to release your application, you must change it to the custom icon representing it.

    To create a launcher icon, go to File | New | Image Asset. You will see Configure Image Asset dialog, as shown in figure 1.6:

    Figure 1.6: Creating launcher icon

    At this screen, the icon type, which is the launcher icon is our case, name for the icon, three different types under asset type so you can choose any type to create an icon (as in preceding figure 1.6, Smiley has taken from Clip Art. Other settings can be changed, but these settings are as is, as these are recommended and follow standards.

    Now, click on Next. You will see the Confirm Icon Path screen and click Finish.

    Creating android virtual device (AVD)

    As shown in figure 1.7, if you see No Devices in Toolbar, you do not have an emulator or device connected:

    Figure 1.7: Running AVD from Toolbar

    So, you need to create AVD or connect the device. Let us see how you can create AVD (Emulator) using the following steps:

    Open the AVD Manager by clicking Tools | AVD Manager or by clicking on Icon from Tool Bar as shown in the preceding figure 1.7.

    Click on Create Virtual Device on AVD Manager Dialog.

    On the Select Hardware screen, select category as Phone and Hardware screen as Pixel 2 as of now, as shown in figure 1.8:

    Figure 1.8:Choosing hardware for emulator

    You can choose any hardware profile here, but profiles which include the Play Store are fully CTS compliant, and AVD will have play services features, including the Play Store application.

    Now click on Next.

    On the System Image screen, select the system image for a specific API level, and click on Next, as shown as figure 1.9:

    Figure 1.9:Choosing API level

    TIP: While choosing API level, you need to check the value of minSdkVersion from the manifest or Gradle file and make that value of minSdkVersion is either equal to or less than API level.

    You can see three Tabs in preceding figure 1.9, recommended tab shows you default recommendations. The other two tabs have the complete list of system images. So you can play with them and try to understand their uses.

    On Verify Configuration screen, you can change the name of AVD or more settings by clicking on Show Advance Settings, as shown in figure 1.10:

    Figure 1.10:Final steps to create an AVD

    And click on Finish.

    Congratulations, now you know how to create Android Virtual Device.

    Let us run our Hello World application.

    Running the Hello World application

    To run the application, click on Run | Run ‘app’ from Tool Bar or click on the run icon on Tool Bar.

    On first lunch, Android Studio will take some time to launch the application, as it will sync your application with Gradle files. After a successful build, you will see an amazing application running on the emulator, saying "Hello World!", as shown in figure 1.11:

    Figure 1.11: Output of Hello World app

    Now you know how to create a project using the template, how to create an emulator, and how to run the application.

    Important tools to develop, debug, and improve Android application

    Let us read more about a few important tools that help while developing and debugging the application and need to know before you start an awesome project. The following are those tools:

    Gradle

    Logcat

    Android Lint

    Layout Inspector and Layout Validator

    Memory Profiler

    Database Inspector

    Let us know more about these tools in the next section.

    Gradle

    Gradle is an open-source build automation tool that can be used to build almost any type of software. Keeping definition more simple, Gradle is software for building software.

    In terms of Android, Android Studio uses Gradle to create Android builds, and Gradle plugins add many features that are specific to building Android applications. It helps you to customize the build easily. For example, if you want to:

    Create free and paid versions of your application from the same project

    Create a country/region-specific application from the same source code

    Use different configurations like server URL for your debug application or release application

    Use any library in debug application, but you do not want to include that library in the release application.

    These all-custom configurations can be configured easily using Gradle. We will see how to do these configurations in a later chapter.

    While looking into a project structure, as shown in preceding figure 1.5, you saw a few files used for Gradle configurations, and you read a little bit about those files. In this section, we will learn more about the build.gradle file of app module in detail.

    So first of let us see the defaultConfig:

    android {

    defaultConfig {

    applicationId com.bpb.android.helloworld

    minSdkVersion 21

    targetSdkVersion 30

    versionCode 1

    versionName 1.0

    }

    }

    In the preceding code, we set the following:

    applicationId is the unique identification of the application. In a normal case, this id would be the same as the package name you set while creating a new project. But this can be changed, and it is not required to keep it the same as the package name. In the URL https://play.google.com/store/apps/details?id=com.ulektz.BPB, com.ulektz.BPB is the application id.

    minSdkVersion [see create project section for more information]

    targetSdkVersion refers to the API level on which you have tested your application, and the Android system used to not enable any forward-compatible behavior to run your application well on a newer version than targetSdkVersion.

    versionCode This positive integer number is used as the version number of your application, so different versions of the application can be identified, like which version is newer or older. And most importantly, by using version code, the Android system prevents downgrading of your application by disallowing the installation of applications that have a lower value of version code.

    versionName used to be a string that describes the application version .. like 1.0.1. The only purpose of it is to display the version to the user.

    Let us see buildTypes section of build.gradle:

    buildTypes {

    debug {

    debuggable true

    }

    release {

    minifyEnabled false

    proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’

    }

    }

    buildTypes contains configurations per build type. In the preceding code, you see debug and release build types with few configurations for each. You can add more build types like beta (we release the beta version to let the public test the app and then provide feedback to the developer). We will learn more about this file while explaining build flavors in Chapter 5: Publishing the Application.

    And at last, let us look into dependencies field:

    dependencies {

    // Dependency on local JARs

    implementation fileTree(dir: ‘libs’, include: [‘*.jar’])

    // Dependency on a local library module

    implementation project(‘:mylibrary’)

    // Dependency on a remote binary

    implementation ‘androidx.appcompat:appcompat:1.4.2’

    }

    In the preceding code, you set different types of dependencies, like if your module depends on a local jar file, you will add a dependency similar to Line 3. Line 5 can be used when your module depends on another local module myLibrary. And Line 7 is used to provide dependency to the module, which is online and placed on any online repository, like Maven.

    Logcat

    A tool, which shows your android device logs, including crash logs and the logs that you have written for your application. VERBOSE, DEBUG, INFO, WARNING, ERROR, or FATAL are logging levels that can be used to log errors, warnings, or some other text. As Logcat is a command-line tool, here are a few important commands which you can use to see logs on the command window. [Assuming you have added SDK path as an environment variable, or logcat can be found into platform-tools/ of Android SDK].

    To view log output, it will show the device log, including your application log:

    adb logcat

    To clear the device logs, you can use either of the following commands:

    adb logcat -c

    adb logcat --clear

    To filter logs with Log level. Given command will print logs with log level DEBUG and higher:

    adb logcat *:D

    To know about more commands and uses:

    adb logcat --help

    You should also read the official documentation https://developer.android.com/studio/command-line/logcat for logcat commands.

    Android Studio provides a logcat window, which is an easy way to view log messages, so we will not go into more details for logcat commands. Apart from the log view, this window gives a few other interesting features. Let us go back to Android Studio and open View | Tool Windows | Logcat or click on at the bottom toolbar. You see a Logcat Window, as shown in figure 1.12, where you can see logs for the Hello World application:

    Figure 1.12: The logcat window

    In the preceding figure 1.12, you can see a few options at the top, which are marked with numbers. These are filtering options to filter log messages. Let us see what these are as follows:

    This option shows you attached emulators and devices to ADB. You see log messages from the device which is selected in this option. You can switch to different devices by using the drop-down.

    This dropdown keeps all debug-able applications for the selected device. By choosing a different application from this drop-down, you can see logs of the chosen application.

    You can filter logs by Tag using this drop-down. In the preceding figure 1.12, Verbose is selected, which means you will see each type of log message that is Verbose, Debug, Info, Warning, and Error. Similarly, if you select Warning, then you will see the log messages, which are tagged with Warning or Error.

    The search box with regex gives you an option to filter log messages by some text. Logcat window will show only those messages which contain the text added into the search box.

    The last drop-down has options to show logs only for selected applications (Point 2) or complete device logs. It gives an option to create a custom filter too, where you can filter log messages by Process Id, Package Name, Log Tag, and more.

    There are some buttons(tools) on the Logcat Window, highlighted in the rectangular area in the preceding figure 1.12 and also shown in figure 1.13. These tools help us to perform some action on the logcat window, take a screenshot of a running application, take a video of the application, and so on. Let us look into these tools (as shown in figure 1.13) in more detail:

    Figure 1.13: Tools at Logcat window

    Clear Log: Choose to click this button when you want to clear the log messages on logcat Window.

    Scroll to the end: Clicking on a particular line stops scrolling and keeps that line visible.

    Up the stack trace and Down the stack trace: These buttons are useful when you get a crash in the Application. By using these two buttons,

    Enjoying the preview?
    Page 1 of 1