<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tien Tan on Medium]]></title>
        <description><![CDATA[Stories by Tien Tan on Medium]]></description>
        <link>https://medium.com/@ngotantien?source=rss-352e0ff5b8b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ft8_n3wYdpSvcYx9.</url>
            <title>Stories by Tien Tan on Medium</title>
            <link>https://medium.com/@ngotantien?source=rss-352e0ff5b8b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:50:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngotantien/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Testing Codelab]]></title>
            <link>https://medium.com/@ngotantien/android-testing-codelab-366bda9729e4?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/366bda9729e4</guid>
            <category><![CDATA[android-testing-codelab]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 09:25:17 GMT</pubDate>
            <atom:updated>2018-04-24T09:25:17.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5BEk6XBzLd9CK-QY.png" /></figure><p>In this codelab, you’ll learn how to get started with <strong>testing for Android</strong>. We’ll look at the testing integration in <strong>Android Studio</strong>, <strong>unit testing</strong>, <strong>hermetic testing</strong> and <strong>functional UI testing</strong>. Later we will also cover some more advanced topics from the <strong>Espresso testing framework</strong>.</p><h3>What you’ll learn</h3><ul><li>Lightweight application architecture design with the Model-View-Presenter pattern</li><li>Using Gradle and Android Studio to run Android tests</li><li>Writing unit tests for Android using JUnit4</li><li>Writing UI tests with Espresso and the Android Testing Support Library</li><li>Some advanced Espresso topics (Espresso-contrib, Espresso-intents and IdlingResources)</li><li>Generating Code Coverage reports</li></ul><h3>What you’ll need</h3><ul><li><a href="https://developer.android.com/sdk/installing/studio.html">Android Studio</a> version 2.1+</li><li>The sample code</li><li>A test device or emulator with at least Android 2.3.3 (API level 10), or later.</li><li>A USB cable for your device</li></ul><p>Read it through onlyRead it and complete the exercisesNoviceIntermediateExpert</p><p>You can either download all the sample code to your computer as a zip file or directly from github (see below).</p><p><a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">Download Zip</a></p><p>We have created snapshots for you for each step. If you get stuck you can just jump ahead to the next checkpoint and continue where you left off.</p><p>Each step builds on each other. Begin with ‘step-1–5’ and use the checkpoints if you want to start over for the next section.</p><p>The zip file contains a few folders and files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*4bKsAp4s9AGVcXo4.png" /></figure><ul><li><strong>step-1–5</strong> — The starting code that you’ll build upon in this codelab.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*SPUZkRv_wryXQ-ZV.png" /></figure><ul><li><strong>step-6</strong> — The starting code for section 6: “Unit Testing with JUnit4 and Mockito”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*rhfWyqO5qgHhhYX_.png" /></figure><ul><li><strong>step-7</strong> — The starting code for section 7: “Writing UI tests with Espresso”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*jByNxupB3XwNzGEh.png" /></figure><ul><li><strong>step-8</strong> — The starting code for section 8: “Espresso-Intents”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*QFqfVYhymDVHVKui.png" /></figure><ul><li><strong>step-9</strong> — The starting code for section 9: “Espresso-Contrib”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*gUTw8Sr1oPoJIeOp.png" /></figure><ul><li><strong>final</strong> — The complete code for the finished codelab.</li></ul><p>You can also checkout each snapshot directly from github, we set them up as separate branches.</p><p>The first snapshot is in the<strong> branch ‘step-1–5’</strong>:</p><pre>$ git clone <a href="https://github.com/googlecodelabs/android-testing">https://github.com/googlecodelabs/android-testing</a> -b step-1-5</pre><p>We will be getting back to the code in the next step, where we will import the project into Android Studio and run the app for the first time. For now, just download the sample code and save it to your computer.</p><p>If you run the app, you will notice that we are getting a blank screen with no notes or working buttons! We’ll implement the logic later.</p><h3>Notes — a simple note taking app</h3><p>In this codelab, you will be working with a simple note taking app called “Notes”. Don’t worry, we have prepared most of the code for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*N81dnbtDG1u3vCyl.png" /></figure><p>You can <em>view</em> notes, <em>open</em> them, <em>add</em> new ones or <em>attach</em> a photo. In the next few steps, we will hook up the final parts of the app, explore the ‘Model-View-Presenter’ architecture and — most importantly — add some tests.</p><p>Mobile applications run on devices that vary greatly in screen size and resolution, processing power, available memory or connectivity. Manually testing your application across all these different device configurations and external factors can be sheer impossible — that’s where automated testing can help.</p><p>The <a href="https://google.github.io/android-testing-support-library/"><strong>Android Testing Support library</strong></a> (ATSL) provides a great framework for testing your Android app. It has a <strong>JUnit 4-compatible test runner</strong> (<a href="https://developer.android.com/tools/testing-support-library/index.html#AndroidJUnitRunner"><strong>AndroidJUnitRunner</strong></a>) and <strong>functional UI testing</strong> through <a href="https://developer.android.com/tools/testing-support-library/index.html#Espresso"><strong>Espresso</strong></a> and <a href="https://developer.android.com/tools/testing-support-library/index.html#UIAutomator"><strong>UI Automator</strong></a>. You can run tests for these APIs directly in the Android Studio IDE or from the command line, which makes it very easy to integrate them into your development flow.</p><p>We’ll look at these in some more detail and explore how to write your own tests using these great tools!</p><p>There are many different ways to architect your Android app. Not all of them are testable and allow you to structure your code in a sane way, so that the app is easy to test.</p><p><strong>The key idea to a testable architecture is to separate parts of the application, making them easier to maintain and test individually. </strong>One common UI pattern is the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">Model-View-Presenter</a> architecture, or MVP for short.</p><h3>The Model-View-Presenter pattern</h3><p>In our app, we follow the MVP pattern, separating the internal data <em>model</em>, from a passive <em>view</em> through a <em>presenter </em>that handles the logic of our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/0*ATYNr5xih5Uu2e02.png" /></figure><h3>Model</h3><p>The <strong>model</strong> provides and stores the internal data. <br>In our note taking app, the notes are represented in the model. Each note has some data (a title, description and image) that is served through a data source and API endpoint.( <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/data/Note.java">Note</a>s are stored in a <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/data/NotesRepository.java">NotesRepository</a> that is backed by a <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/data/NotesServiceApi.java">NotesServiceApi</a>.)</p><h3>View</h3><p>The <strong>view </strong>(not to be confused with the Android class View) handles the display of data (ie. the model). User actions are forwarded to the presenter. <br>In our app, the view is represented by Fragments, but basically could be any Android View. We have three Views in our app:</p><h3>Presenter</h3><p>The <strong>presenter</strong> sits between the model and view: it coordinates the UI with the data, ensuring they are in sync. Specifically, it updates the view and acts upon user events that are forwarded by the view. The presenter also retrieves data from the model, prepares it for display (by the view) and updates the model as necessary.<br>We have three presenters in our app:</p><h3>Learn more</h3><p>Let’s see how MVP works in action and look at how the different parts of our app work together.</p><p><strong>Open the project in Android Studio.</strong></p><p>If you have downloaded the <a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">zip</a> file, extract it first then<strong> open the folder</strong> named step-1-5 in Android Studio. (Start Android Studio, then select <strong>File &gt; Open</strong> and select the step-1-5 directory. You may have to select the file settings.gradle.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*zNkeMqDUGm3SDHAf.png" /></figure><p>This is our first snapshot and contains our starting point for this codelab. (We also have snapshots for each subsequent step later in the codelab.)</p><p>If you run the app, you will notice that we are getting a blank screen with no notes or working buttons! We’ll implement the logic later, but for now we will explore the structure of our app and the MVP pattern.</p><h3>Notes app structure: Feature separation by packages</h3><p>Instead of using a <em>package by layer approach</em>, we have structured the application by <em>package per feature</em>. This greatly improves readability and modularizes the app in a way that parts of it can be changed independently from each other. Each key feature of the app is in its own Java package. Let’s take a quick look:</p><p><strong>Package: </strong>com.example.android.testing.notes</p><p>.addnote</p><p><strong>“Add note”: Adding a new note</strong></p><p>.data</p><p>Data: Storage of notes — this contains the <em>model layer</em></p><p>.notedetail</p><p><strong>“Note Detail”: Showing details for a single note</strong></p><p>.notes</p><p><strong>“Notes”: Showing a list of all stored notes</strong></p><p>.statistics</p><p>The statistics screen</p><p>.util</p><p>Utility classes used in various parts of the app, e.g. for handling file access</p><p>Each feature package (shown in bold above) contains a <strong>Contract</strong> interface - this defines the interface for the <strong>View</strong> and <strong>Presenter</strong> callbacks of each feature.</p><p>This makes it very clear which classes belong to the same feature and how they are interconnected.</p><h3>Explore the “Notes” Features: Showing a list of notes</h3><p>The first function we are exploring is the “show all notes” feature which is shown when the app is first started. The code for this feature lives in the package com.example.android.testing.notes.notes</p><p>We’ll be looking at these classes:</p><p>NotesActivity</p><p>The entry point into our app. Hosts the NotesFragment</p><p>NotesContract.View</p><p><strong>Defines the View layer</strong> for this feature</p><p>NotesContract.UserActionsListener</p><p>Defines the interaction between the <strong>View and Presenter layers</strong></p><p>NotesFragment</p><p>Concrete implementation of the<strong> View layer</strong></p><p>NotesPresenter</p><p>The <strong>Presenter layer</strong>, implements the NotesContract.UserActionsListener to listen for user actions. It has a reference to the <strong>View </strong>to update it when the model changes</p><h3>View Layer</h3><p>The NotesFragment class is the View for this feature - it implements the <strong>View interface</strong> defined in the NotesContract.View:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesFragment.java">NotesFragment.java</a></h3><pre>public class NotesFragment extends Fragment implements NotesContract.View { ...</pre><p>Take a look at the NotesContract.View interface. These are all functions that we expose from the View layer and make available to the Presentation Layer:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesContract.java">NotesContract.java</a></h3><pre>interface View { void setProgressIndicator(boolean active); void showNotes(List&lt;Note&gt; notes); void showAddNote(); void showNoteDetailUi(String noteId); }</pre><p>The View layer handles the user interface and these are the only functions that we expose to other layers.</p><h3>Presenter layer</h3><p>The NotesPresenter class is the Presenter layer for this feature - it implements the <strong>UserActionsListener interface</strong> defined in NotesContract.UserActionsListener:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter.java</a></h3><pre>public class NotesPresenter implements NotesContract.UserActionsListener {</pre><p>Take a look at the NotesContract.UserActionListener interface. It describes the actions that can be started from the View - for example opening or adding a note. The view should not handle user interaction directly where it affects the model. Instead, it should forward interactions to the presenter.</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesContract.java">NotesContract.java</a></h3><pre>interface UserActionsListener { void loadNotes(boolean forceUpdate); void addNewNote(); void openNoteDetails(@NonNull Note requestedNote); }</pre><h3>Connecting the View and Presenter layers</h3><p>Let’s see how the interaction between these two layers works in practice. We are not adding any new code in this step, we are only exploring how the application is structured.</p><p><strong>Open the NotesFragment</strong> (app/src/main/java/.../notes/NotesFragment.java).</p><p>Now temporarily comment out the mActionsListener field. This will show us where (and how) we make calls to the Presenter:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesFragment.java">NotesFragment.java</a></h3><pre>// private NotesContract.UserActionsListener mActionsListener;</pre><p>For example, we are making a call when a <em>click on the floating action button</em> occurs to trigger the “Add Note” UI through the Presenter (mActionsListener.addNewNote()):</p><pre>// Set up floating action button FloatingActionButton fab = ... fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mActionsListener.addNewNote(); } });</pre><p>Here we are asking the Presenter to display <em>a specific note when it is clicked</em>:</p><pre>NoteItemListener mItemListener = new NoteItemListener() { @Override public void onNoteClick(Note clickedNote) { mActionsListener.openNoteDetails(clickedNote); } };</pre><p>Now, add the mActionsListener back, we need it to run the app!</p><pre>private NotesContract.UserActionsListener mActionsListener;</pre><h3>Creating the NotesPresenter</h3><p>Let’s take a look at how exactly we are creating the NotesPresenter object in onCreate(...):</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesFragment.java">NotesFragment.java</a></h3><pre>@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mListAdapter = new NotesAdapter(new ArrayList&lt;Note&gt;(0), mItemListener); mActionsListener = new NotesPresenter(Injection.provideNotesRepository(), this); }</pre><p>We are using the Injection class to retrieve an instance of the notes repository. Using this class makes it easy to swap out the implementation during testing later on - we can simply inject a different service layer in our tests, perhaps one that only emulates parts of the functionality in a predefined way.</p><p><strong>Lightweight class injection using build flavors</strong></p><p>For testing it is often necessary to <em>inject</em> stub or mocked classes into other components to emulate and test certain functionality hermetically. For example, later in our tests we will override some functionality in the notes repository to emulate the saving and loading of notes. The class <strong>Injection</strong> returns an implementation of this repository.</p><p>We have two implementations in the source tree:</p><ul><li>In the <strong>prod</strong> build flavor the class returns an implementation that simulates network latency. (See <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/data/NotesServiceApiImpl.java">NotesServiceApiImpl.java</a>)</li><li>In the <strong>mock</strong> build flavor the class returns an implementation that stubs out the service layer completely and returns a fake dataset, which can even be configured in the test (See <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/mock/java/com/example/android/testing/notes/data/FakeNotesServiceApiImpl.java">FakeNotesServiceApiImpl.java</a>)</li></ul><p>These two build flavors are automatically recognised by gradle and are built directly as part of the usual debug build: <strong>prodDebug, </strong><strong>mockDebug</strong></p><p>More complicated setups can use Dependency Injection frameworks like <a href="http://google.github.io/dagger/">Dagger2</a>.</p><p><strong>We are now ready to run the app!</strong></p><p>Open the Build Variants window and choose the <strong>prodDebug</strong> variant for your app module. (The option to open the <strong>Build Variants</strong> screen is on the lower, left hand side in Android Studio.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*8-ie_JgzqsLyYZnP.png" /></figure><p>Connect your Android device (or start the emulator) and select<strong> ‘Run’ -&gt; ‘Run app’</strong> to start the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/0*ypoNLsS86Aif--Rh.png" /></figure><p>When prompted to choose a target device, select your device and check the box to use the same device for future launches, then press ok.</p><p>You should see an empty screen with a floating action button (that doesn’t do anything yet) and a navigation drawer:</p><p>Note that at this point the app is just a skeleton and most of the UI is non functional since we haven’t implemented any of the features yet!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*aPpHS5oWSdXr3acn.png" /></figure><p><strong>Continue with your existing Android Studio project for this section.</strong></p><p><strong>If you would like to start fresh for this section, continue from snapshot ‘step-6’:<br></strong>Open the directory named <strong>step-6</strong> from <a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">the zip file</a> in Android Studio or checkout the branch step-6 directly from github: <br>git clone https://github.com/googlecodelabs/android-testing.git -b step-6</p><p><strong>In this section we will get the project configured for testing, set up Android Studio to run our tests and explore how you can use unit tests to establish a contract between components.</strong></p><p>We will take a test-driven approach, this means that we will start by writing some tests that describe the functionality before adding their implementation. These tests will also aid us in defining the “contract” for the presenter which we introduced in previous steps. It helps you understand the responsibilities of your objects and how they communicate with each other, without implementing any details just yet. First we will look at implementing the <strong>notes list</strong>, that shows a list of all saved notes when the app is first started. We will write some tests that define the interaction between the <em>notes presenter</em> and the <em>notes repository</em>.</p><h3>Configure your project for Unit testing support</h3><p>Before you start writing tests, let’s go through a checklist and make sure our project is set up for local testing. <em>Local tests</em> are tests that run on your local machine, without needing access to the Android framework or an Android device. (Remember, we will first test the basic interaction needed between components.)</p><h3>Switch to the “Project” Perspective</h3><p>Tests are stored in the test and androidTest directories in your module&#39;s src folder. Good news - we have already set these up for you!</p><p>These folders are hidden in the default <strong>Android perspective</strong>, so you will need to switch to the <strong>Project perspective</strong> by using the drop down on the top-right of the project pane. (If you can’t see it, open the <strong>Project view</strong> first, it’s on the left — or you can enable it under <strong>View &gt; Tool Windows &gt; Project</strong>.)</p><p>If you start from a code snapshot along the way, make sure to switch to the <strong>project perspective</strong> again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GgOMUlbJGQFV48Y1.png" /></figure><p>Your final view hierarchy should now look like this: Note the new folders that have appeared in the src directory in our app module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*dymgXNuq7pa98j-S.png" /></figure><h3>Source sets define product flavors</h3><p>The directories in the src/ folder are called <em>source sets</em> that make up a <em>product flavor</em>. We have four different source sets defined that will be picked up by different parts of the build and test process. Our unit tests will go into the test/ directory.</p><p>A product flavor defines a customized version of the application built by the project. A single project can have different flavors which change the generated application.</p><p>This new concept is designed to help when some parts of the codebase need to be different for variations of the app. We’re going to use two flavors for this project: mock and prod. We&#39;ll use the mock flavor to substitute certain parts of the application to make hermetic testing easier.</p><p>The majority of the code will still exist in the main directory and only the files that need some variation will have a version in mock/ and another in prod/. The same also applies to Android tests (most tests live in androidTest/, but those that make use of the special implementation in mock/ are under androidTestMock/).</p><p>Files in the flavor-specific folders <em>do not</em> replace files in the main source set. Trying to do that will result in a duplicate class exception. This is a common misconception because it’s how resources are merged.</p><p>If you check the list of gradle tasks you’ll find new tasks like installMockDebug or installProdDebug. Every operation now requires you to specify what <em>variant</em> of the app you want to use. In Android Studio that&#39;s chosen from the Build Variants window.</p><p><strong>Source Set (directory)</strong></p><p><strong>Explanation</strong></p><p>androidTest</p><p>Location of Android tests (tests that are run on a device or emulator)</p><p>androidTestMock</p><p>Location for Android tests for the mock flavor of the application. <br>Contains tests that should only run against the mock flavor of the app. This is particularly useful if you want some tests to only run in an hermetic environment.</p><p>main</p><p>The main source set, default location for all source code</p><p>mock</p><p>Custom app flavor (mock) that is used for tests. <br>Within it, the class Injection provides dummy implementations of dependencies that use fake data for an isolated execution, not hitting the network or external storage (mock = <a href="https://en.wikipedia.org/wiki/Mock_object">mocked dependency</a> that simulates the behavior of a complex, real object)</p><p>prod</p><p>Opposite to the mock flavor, here the class Injection provides dependencies for a real-world context . (prod = production implementation)</p><p>test</p><p>Location of local tests</p><h3>Adding Gradle dependencies for JUnit 4</h3><p>The first test we will be adding is a JUnit test. We have already added the necessary dependencies to our build.gradle file in the <strong>app</strong> module. We will also be using Mockito and Hamcrest matchers in this step - more about this later. For now, this is what our dependencies look like:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/build.gradle#L54">app/build.gradle</a></h3><pre>// Dependencies for local unit tests testCompile &quot;junit:junit:$rootProject.ext.junitVersion&quot; testCompile &quot;org.mockito:mockito-all:$rootProject.ext.mockitoVersion&quot; testCompile &quot;org.hamcrest:hamcrest-all:$rootProject.ext.hamcrestVersion&quot; testCompile &quot;org.powermock:powermock-module-junit4:$rootProject.ext.powerMockito&quot; testCompile &quot;org.powermock:powermock-api-mockito:$rootProject.ext.powerMockito&quot;</pre><p><strong>Gradle pro-tip: Use variables to define version numbers.</strong></p><p>Note how we have written $rootProject.ext.junitVersion instead of a version number. We are defining these variables in the gradle build file in our root project (in the file <a href="https://github.com/googlecodelabs/android-testing/blob/master/build.gradle#L24">build.gradle</a>). Instead of having to update every gradle file in our project with new version numbers, we can simply update the variable once for all modules.</p><p>We’ll be using this syntax for all other dependencies in our build configuration.</p><h3>Optionally sync your project</h3><p>Sometimes changing the test artifact can result in errors, synchronizing your project again with Android Studio will in most cases resolve these issues!</p><p>Click the <strong>gradle sync</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/22/0*JSFX85q2jWcIeiSi.png" /></figure><p>button in the toolbar. Any missing dependencies will now be downloaded.</p><p>You might need an Internet connection to download the JUnit dependency when syncing your Gradle configuration.</p><h3>Create your first Unit Tests: Notes Presenter</h3><p>Now that everything is set up, it’s time to start writing your first test. A unit test exercises a small component of your application, usually a class or method. Remember, we will be writing our unit test first and implement the logic afterwards.</p><p>Let’s implement a few tests for the NotesPresenter. <br>The notes presenter sits between the data model and the view. It toggles the state of the view (show a loading indicator, display a list of notes, display an empty indicator), based on callbacks received. It also handles the display of different views when options are selected on the screen, such as showing note details or the &quot;add note&quot; UIs.</p><h3>Mocking dependencies with Mockito</h3><p>The first tests we are writing focuses purely on the NotesPresenter. However, the NotesPresenter class does not stand in isolation - it also requires a view that updates the UI (NotesContract.View) and a repository where our notes are stored. We don&#39;t care about the concrete implementation of the View and repository at this point, we only want to make sure that the presenter behaves as expected.</p><p>Instead of relying on actual implementations of these <em>dependencies</em>, we can use <strong>mock objects </strong>to test our class under test in isolation. A mock object is a dummy class for which you can define the output and behavior of its method calls based on their input.</p><p>This is perfect for our test — we don’t know how the View might display a progress indicator, but we do know that the presenter <strong>must </strong>call a method on the View to tell it to display the progress indicator. The tests we will be writing next will focus on this interaction — we test if the presenter has made the calls on the view that we expect it to make when we call its methods.</p><p>One popular framework for mocking on Android is <a href="http://mockito.org/">Mockito</a>. You’ll see some of its syntax in the next section.</p><p>Another advantage of using a mocking framework like Mockito is the option to test against arguments of calls. This means that you can write tests that capture the parameters supplied to a method and test against them. (In Mockito this functionality is implemented through an <a href="https://github.com/mockito/mockito/blob/master/src/main/java/org/mockito/ArgumentCaptor.java">ArgumentCaptor</a>.)</p><h3>Unit Test 1: Opening the ‘Add Notes’ screen</h3><p>Unit tests live in the test/ source set.</p><p><strong>Open the file </strong>app/src/<strong>test</strong>/java/.../<strong>notes/NotesPresenterTest.java</strong> and comment in the code as you work through this section:</p><p>If you can’t see this file, make sure you have switched to the <strong>Project perspective</strong>!</p><p>Our first test verifies that asking the Presenter to ‘Add a new note’ results in a request to be made for the View to show the new add-note screen. Let’s implement the clickOnFab_ShowsAddsNoteUi()test.<br>First, remove the fail(...) line, because we are now implementing this test!<br>Next, add a call to the presenter&#39;s addNewNote() method, after which we verify that the showAddNote() method has been called on the View.</p><p>This is our final implementation:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/test/java/com/example/android/testing/notes/notes/NotesPresenterTest.java">test/…/NotesPresenterTest.java</a></h3><pre>@Test public void clickOnFab_ShowsAddsNoteUi() { // When adding a new note mNotesPresenter.addNewNote(); // Then add note UI is shown verify(mNotesView).showAddNote(); }</pre><p>We can call verify(...) directly because we have added it as a static import: import static org.mockito.Mockito.verify;</p><h3>Running your Unit Tests</h3><p>Now it’s finally time to run your test!</p><p>Right click on the NotesPresenterTest class we have just worked on and select <strong>Run &gt; NotesPresenterTest</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_b9gY6kBtE14ZeDG.png" /></figure><p>You can also run the test from the command line, by issuing the following command in your project’s directory:</p><pre>./gradlew testMockDebugUnitTest --tests *NotesPresenterTest</pre><p>You might have noticed that Android Studio never asked you to connect a device or launch an emulator to run the tests on. That’s because tests residing in the src/tests folder are local unit tests that run on the Java VM on your computer. This enables a really fast iteration flow where you write your tests, implement the functionality which will make the test pass and then add some more tests… This is called Test Driven Development (TDD for short).</p><p><strong>Congratulations! </strong>You have just written your first unit test! <strong>(The test should fail for now.)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pef7G0i4jMwDhSkz.png" /></figure><p>(You may have to switch to the “<strong>Run</strong>” view to see the status of your Unit Test runs.)</p><p>For now the test is failing, because we haven’t implemented the relevant logic in the presenter yet.</p><h3>Implement NotesPresenter#addNewNote</h3><p><strong>Open the file </strong>app/src/main/java/.../notes/NotesPresenter.java and implement the method addNewNote().</p><p>Based on our Unit test we expect this method to call the View’s showAddNote() to trigger the UI update.</p><p>This will be our implementation:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter.java</a></h3><pre>@Override public void addNewNote() { mNotesView.showAddNote(); }</pre><p>Run the test again — it should now complete successfully! (Right click on NotesPresenterTest and select <strong>Run &gt; NotesPresenterTest</strong>)</p><p>The test will no longer be included in the “Run” View, because it only displays tests that have failed.</p><p>You can also toggle view to display all passed tests using the button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/27/0*nQV5m_l25ZxBnupj.png" /></figure><p>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*tGw-3JPzoc4wNHpw.png" /></figure><h3>Bonus — Unit Test 2: Loading notes from presenter</h3><p>Our next test validates that the presenter correctly displays a list of notes — this includes retrieving the notes from the repository and updating the view (displaying a progress indicator and finally displaying the notes).</p><p>The flow we will be testing is this:</p><ul><li>When calling the presenter to load notes from the repository the presenter calls the repository to load data (and expect the result back via a callback)</li><li>The callback returns with a list of notes</li><li>The presenter then tells the view to disable the progress indicator and to display the notes.</li></ul><p>Let’s go back to the file app/src/test/java/.../notes/NotesPresenterTest.java and comment in the lines in this step as you follow along.</p><p>We are implementing the test loadNotesFromRepositoryAndLoadIntoView. Remove the call to fail(...) first:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/test/java/com/example/android/testing/notes/notes/NotesPresenterTest.java">test/…/NotesPresenterTest.java</a></h3><pre>@Test public void loadNotesFromRepositoryAndLoadIntoView() { ... }</pre><p>First we are telling the NotesPresenter to load notes:</p><pre>// Given an initialized NotesPresenter with empty notes // When loading of Notes is requested mNotesPresenter.loadNotes(true);</pre><p>Next we will use Mockito’s verify(...) to check that the getNotes(...) method has been called by the presenter, while capturing the parameter supplied to the call. The parameter is actually a callback that would be called by the repository when the data has been loaded (See <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/data/NotesRepository.java">NotesRepository.LoadNotesCallback</a>)</p><p>Our repository here is only a mock object (and doesn’t have any actual functionality), we need to fake the callback on the listener ourselves. (The callback would have been set up by the presenter — which is what we are trying to test here.)</p><p>First we capture the callback in the captor, then we call it with a list of notes:</p><pre>// Callback is captured and invoked with stubbed notes verify(mNotesRepository).getNotes(mLoadNotesCallbackCaptor.capture()); mLoadNotesCallbackCaptor.getValue().onNotesLoaded(NOTES);</pre><p>In the last step we verify that the presenter has asked the view to hide the progress indicator and display the list of notes:</p><pre>// Then progress indicator is hidden and notes are shown in UI verify(mNotesView).setProgressIndicator(false); verify(mNotesView).showNotes(NOTES);</pre><p>Our final test should now look like this:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/test/java/com/example/android/testing/notes/notes/NotesPresenterTest.java">test/…/NotesPresenterTest.java</a></h3><pre>@Test public void loadNotesFromRepositoryAndLoadIntoView() { // Given an initialized NotesPresenter with initialized notes // When loading of Notes is requested mNotesPresenter.loadNotes(true); // Callback is captured and invoked with stubbed notes verify(mNotesRepository).getNotes(mLoadNotesCallbackCaptor.capture()); mLoadNotesCallbackCaptor.getValue().onNotesLoaded(NOTES); // Then progress indicator is hidden and notes are shown in UI verify(mNotesView).setProgressIndicator(false); verify(mNotesView).showNotes(NOTES); }</pre><p><strong>Advanced Topic — ArgumentCaptor</strong></p><p>We have already set up the NotesPresenterTest with a mocked notes repository and view.</p><p>We have defined an ArgumentCaptor that captures parameters - we are using it to capture the callback for the NotesRepository when data is loaded by the presenter, so we can call it ourselves to simulate that the notes have been loaded already.</p><p>Run the test. (Right click on NotesPresenterTest and select <strong>Run &gt; NotesPresenterTest</strong>).</p><p>The test will fail, but we have a helpful error message that tells us exactly what we need to do:</p><pre>Wanted but not invoked: mNotesRepository.getNotes( &lt;Capturing argument&gt; );</pre><p>This means that we expected mNotesRepository.getNotes(...)to be called, but the call was never made by the NotesPresenter!</p><p>We haven’t implemented the logic in the NotesPresenter yet - let&#39;s do that next to get our test to pass.</p><h3>Implement NotesPresenter#loadNotes</h3><p><strong>Open the file </strong>app/src/main/java/.../notes/NotesPresenter.java and comment in the lines as you work through this step.</p><p>Go to the method loadNotes:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter.java</a></h3><pre>@Override public void loadNotes(boolean forceUpdate) { ... }</pre><p>Remember the flow we need to implement:</p><ul><li>Display a progress indicator</li><li>Refresh the data from the repository if an update is forced (method parameter is true)</li><li>Load the notes from the repository</li><li>When the notes have been loaded, hide the progress indicator and display them</li></ul><p>This is our final implementation:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter.java</a></h3><pre>@Override public void loadNotes(boolean forceUpdate) { mNotesView.setProgressIndicator(true); if (forceUpdate) { mNotesRepository.refreshData(); } // The network request might be handled in a different thread so make sure Espresso knows // that the app is busy until the response is handled. EspressoIdlingResource.increment(); // App is busy until further notice mNotesRepository.getNotes(new NotesRepository.LoadNotesCallback() { @Override public void onNotesLoaded(List&lt;Note&gt; notes) { EspressoIdlingResource.decrement(); // Set app as idle. mNotesView.setProgressIndicator(false); mNotesView.showNotes(notes); } }); }</pre><p>We are using an IdlingResource to track the asynchronous request. Don&#39;t worry, we are covering this in a later step in the codelab.</p><p>Run your test again — it should now pass.</p><p>(Right click on NotesPresenterTest and select <strong>Run &gt; NotesPresenterTest</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*hhINn0VtMfZxHxYZ.png" /></figure><h3>Test driven development and contracts</h3><p>The calls we have made from the presenter to the view are effectively a <em>contract</em>. The view must implement these calls to handle calls from the presenter. At this point we haven’t looked at the UI yet, we only know how it should behave based on the logic we have implemented (through tests) in the presenter.</p><p>This kind of approach to development can be very useful to establish a contract between different components of your app, without getting distracted by platform implementation details.</p><p>In this codelab we have already defined these contracts (for example <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesContract.java">NotesContract.View</a> that we have used in our tests).</p><h3>Unit testing with Android dependencies</h3><p>Gradle provides you with an android.jar in the classpath containing Android framework classes. Note that these are not fully functional (for example, you shouldn’t just call methods of Activity and expect them to work.) You should use a mocking framework like Mockito to mock Android method calls that you need to use.</p><p>By default, all calls to the provided Android.jar throw exceptions, this allows you to write tests that do not depend on any Android platform behavior.</p><p>However, if you want to write a test that depends on particular behavior of the framework, you can override the default behavior of the provided android.jar. The key to this is that all final modifiers have been stripped off, which enables you to extend the behavior that would otherwise not be possible.</p><p>Doing this by yourself can be quite tedious — that’s where mocking frameworks such as Mockito come in.</p><p>You might also want to consider to keep classes which contain a lot of logic free from any Android code and test them in a separate java-only module or just run these as an <a href="https://github.com/googlesamples/android-testing/tree/master/unit/BasicUnitAndroidTest">unit Android test</a> on your device.</p><h3>Explore another Unit test: NoteDetailPresenterTest</h3><p>Open the file app/src/test/java/.../notes/notedetail/NotesDetailPresenterTest.java. It defines another set of Unit tests for the NotesDetailPresenter class that handles the display of a single note on screen.</p><p>We’ll be implementing its matching UI test at the end of the next section, so take a look at the callbacks the View and Presenters expect:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/test/java/com/example/android/testing/notes/notedetail/NotesDetailPresenterTest.java">test/…/NotesDetailPresenterTest.java</a></h3><pre>@Test public void getNoteFromRepositoryAndLoadIntoView() { ... verify(mNoteDetailView).setProgressIndicator(true); ... verify(mNoteDetailView).setProgressIndicator(false); verify(mNoteDetailView).showTitle(TITLE_TEST); verify(mNoteDetailView).showDescription(DESCRIPTION_TEST); }</pre><p><strong>Did you know that unit tests should make up to 70% of your tests? Learn more on the </strong><a href="http://googletesting.blogspot.co.uk/2015/04/just-say-no-to-more-end-to-end-tests.html"><strong>Google Testing Blog</strong></a>.</p><p><strong>Congratulations! </strong>You have just learned how to write unit tests for your Android app! Unit tests are a great way to ensure that the individual components of your app are correct. But what about testing the interaction between those units? This is where integration tests come into play, which we will cover in the next step.</p><p><strong>Continue with your existing Android Studio project for this section.</strong></p><p><strong>If you would like to start fresh for this section, continue from snapshot ‘step-7’:<br></strong>Open the directory named <strong>step-7</strong> from <a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">the zip file</a> in Android Studio or checkout the branch step-7 directly from github: <br>git clone https://github.com/googlecodelabs/android-testing.git -b step-7</p><p>Next, let’s implement the user interface. We’ll be following a similar approach as before. First we’ll define the tests that verify how we expect the UI to behave, then the implementation follows from there.</p><h3>UI Testing on Android with Espresso</h3><p>The Android Testing Support Library contains the Espresso testing framework that provides APIs to simulate user interactions. Espresso has a very nice fluent, concise and readable Api to write functional UI tests and was built to make UI testing as frictionless as possible. This means that you can focus on writing tests without having to deal with unreliable and flaky tests.</p><p>Although there is support for running instrumentation tests in the Android framework, current development efforts are focused around the new AndroidJUnitRunner which is released as part of the Android Testing Support Library.</p><h3>Set up Espresso and AndroidJUnitRunner</h3><p><strong>We have already set up the build dependencies for you</strong>, so there is no need to update our build configuration<strong>.<br></strong>If you are adding Espresso to your own project you need to add the AndroidJUnitRunner and Espresso framework from the Android Testing Support Library to your build.gradle:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/build.gradle#L54">app/build.gradle</a></h3><pre>// Android Testing Support Library&#39;s runner and rules androidTestCompile &quot;com.android.support.test:runner:$rootProject.ext.runnerVersion&quot; androidTestCompile &quot;com.android.support.test:rules:$rootProject.ext.rulesVersion&quot; // Espresso UI Testing dependencies. androidTestCompile &quot;com.android.support.test.espresso:espresso-core:$rootProject.ext.espressoVersion&quot; androidTestCompile &quot;com.android.support.test.espresso:espresso-contrib:$rootProject.ext.espressoVersion&quot;</pre><h3>Set up Android Studio for Android instrumentation tests</h3><p>Unlike local unit tests, instrumentation tests must be placed in the androidTest source set (app/src/androidTest/java/...). Don&#39;t worry - we have already created the directory and files up for you.</p><p>Just to recap our project structure, we have three <em>build variants</em> for our app:</p><p>mockDebug</p><p>Uses the mock <em>source set </em>to inject a mock data repository where notes are stored</p><p>prodDebug</p><p>Debug build that uses the prod <em>source set</em> to inject the ‘real&#39; production data repository</p><p>prodRelease</p><p>Signed Release build that uses a ‘real&#39; data repository</p><p>The first test we are writing is using the <strong>prodDebug</strong> variant - make sure to select it for our test artifact before continuing. (Different tests and directories are activated based on the variant you have selected!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*mJneuTvEWIVl-ofE.png" /></figure><h3>Set up your device for Espresso tests</h3><p>For this section of the codelab you will need a physical device or Android emulator, because we will be implementing the user interface.</p><p>You need to <strong>turn off animations</strong> on your test device (or emulator), otherwise Espresso may not work as expected and your tests may fail. Turn off animations from <em>Settings</em> by opening <em>Developer Options</em> and turning all the following options under “<em>Drawing</em>” off:</p><ul><li>Window animation scale</li><li>Transition animation scale</li><li>Animator duration scale</li></ul><h3>Espresso Test 1: Opening the ‘Add Note’ screen</h3><p>Espresso can also perform user interactions (<a href="http://developer.android.com/reference/android/support/test/espresso/action/ViewActions.html">ViewActions</a>) on a view, for example clicks and touches.</p><p>One of the key interactions in the app is <strong>clicking the floating action button to open the “add note” screen</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*u5rhve0jEGfEpJU5.png" /></figure><p>We will implement a test that opens the app, clicks that button and verifies that the correct screen is being displayed.</p><p><strong>Edit the file </strong>app/src/androidTest/java/.../notes/NotesScreenTest.java and comment in the method clickAddNoteButton_opensAddNoteUi() as you work through this section:</p><p>First, we need to find the floating action button in the view hierarchy (which we can identify by its ID R.id.fab_notes) and click it. Then we check that the &quot;add note&quot; screen has been shown, we can easily do this by checking that the title of the screen (identified by its ID R.id.add_note_title) is being displayed:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/NotesScreenTest.java">androidTest/…/NotesScreenTest.java</a></h3><pre>@Test public void clickAddNoteButton_opensAddNoteUi() throws Exception { // Click on the add note button onView(withId(R.id.fab_add_notes)).perform(click()); // Check if the add note screen is displayed onView(withId(R.id.add_note_title)).check(matches(isDisplayed())); }</pre><p>Note that we do not have to wait for the add note screen to be displayed. This is the power of Espresso — it automatically waits for the UI thread to be idle before running any further check. There is no need to implement these waits and delays yourself.</p><h3>Running Espresso tests</h3><p>Now that we have written our first test, it’s time to run it!</p><p>See the <strong>Troubleshooting section</strong> at the end if you have trouble running this test. (You may need to uninstall the previous build first — run the uninstallAll gradle task.)</p><p><strong>Right click</strong> on the class that where we have just implemented our test (androidTest/java/.../notes/NotesScreenTest.java) then select &quot;<strong>Run NotesScreenTest ...</strong>&quot;. If you are not seeing this option, make sure you have switched to the <strong>Android Instrumentation Tests</strong> Build Variant (see above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xBPWegvgrkDekNcX.png" /></figure><p>This approach works well if you are working on just a single test class, but doesn’t scale if you want to run many different tests at the same time.</p><p>Let’s set up a <em>build configuration</em> that will run all of our unit tests together</p><p>Fortunately, Android Studio makes this very easy! Just <strong>right click</strong> on the package name under <strong>androidTest</strong>/java/com.example.android.testing.notes and select &quot;<strong>Create ‘Tests in com.exampl...&#39;&quot;</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iaIR0w684ZxBoUvj.png" /></figure><p>In the next dialog we can configure our new build configuration (such as excluding tests or selecting a target device), but for now the <strong>default options</strong> are just fine.</p><p>Select our new run configuration from the run configuration menu, then select <strong>run</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*oBH9ivamV4WlZAGC.png" /></figure><p><strong>Keep an eye on your device — you can see Espresso execute our tests!</strong></p><p>We will have a few failing tests for now — that’s what we will be implementing in the rest of the codelab!</p><p>Their status is displayed in the <strong>Run</strong> Panel that opened at the bottom of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*T-yb35a8I5pydw45.png" /></figure><h3>ActivityTestRule: Functional testing for Android Activities</h3><p>The Android Testing Support Library <a href="https://google.github.io/android-testing-support-library/docs/rules/index.html">includes two JUnit Rules</a> that make it easy to write functional tests for <strong>Android Activities and Services</strong>.</p><p>If you have used Android TestCases (like ActivityInstrumentationTestCase2 or ServiceTestCase) in the past, these have been deprecated. Instead you should switch to the new ActivityTestRule and ServiceTestRule.</p><p><a href="http://junit.org/junit4/javadoc/latest/org/junit/rules/TestRule.html">JUnit test rules</a> allow the alteration of test methods. It is run before any test is executed and can be shared between projects and classes.</p><p>The ActivityTestRule is a rule that provides functional testing of a single Activity. The annotated Activity will be launched before each annotated @Test and before any annotated @Before methods. The Activity is automatically terminated after the test is completed and all @After methods are finished.</p><h3>View Matching and Assertions with Espresso</h3><p>Espresso tests are written based on what a user might do while interacting with your app. The key concepts are locating and interacting with UI elements. The first step is to find a View you are interested in, then check its state or interact with it.</p><p><a href="http://developer.android.com/reference/android/support/test/espresso/matcher/ViewMatchers.html">ViewMatcher</a>s select Views in the current view hierarchy. The most common ones are withId(...) (that finds Views with a specific ID) and withText(...) (that finds Views with a specific text), but there are many others, including matchers for state (selected, focused, enabled), content description and hierarchy (root and children), <a href="http://developer.android.com/reference/android/support/test/espresso/matcher/ViewMatchers.html">among others</a>.</p><p><a href="http://developer.android.com/reference/android/support/test/espresso/action/ViewActions.html">ViewAction</a>s are actions that can be performed on a View (for example click).</p><p><a href="http://developer.android.com/reference/android/support/test/espresso/assertion/ViewAssertions.html">ViewAssertion</a>s are passed to the check(...) ViewAction to verify its state.</p><h3>Espresso Test 2: Adding a note</h3><p><strong>Continue editing the file </strong>app/src/androidTest/java/.../notes/NotesScreenTest.java and comment in the code as you work through this section:</p><p>Let’s go ahead and implement our first Espresso test from scratch: addNoteToNotesList().</p><p>This test will open the ‘Add Note’ screen, enter some text, click the save button and verify that the text has been displayed.</p><p>First, make sure that the test has been set up, remove the fail(...) call and add some test data we will be checking:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/NotesScreenTest.java">androidTest/…/NotesScreenTest.java</a></h3><pre>@Test public void addNoteToNotesList() throws Exception { String newNoteTitle = &quot;Espresso&quot;; String newNoteDescription = &quot;UI testing for Android&quot;; ... }</pre><p>Similar to the previous Espresso test we looked at, we will first <strong>find the floating action button </strong>(R.id.fab_add_notes) and <strong>click</strong> it:</p><pre>// Click on the add note button onView(withId(R.id.fab_add_notes)).perform(click());</pre><p>Next (once the “add note screen” is open) we will <strong>enter our note text </strong>and <strong>save the note</strong>. (We don’t need to wait for the new screen to open — Espresso will do this automatically for us. It waits until a View with the id R.id.add_note_title can be found.)</p><pre>// Add note title and description onView(withId(R.id.add_note_title)).perform(typeText(newNoteTitle), closeSoftKeyboard()); // Type new note title onView(withId(R.id.add_note_description)).perform(typeText(newNoteDescription), closeSoftKeyboard()); // Type new note description and close the keyboard // Save the note onView(withId(R.id.fab_add_notes)).perform(click());</pre><p>Next we are back on the “Notes list screen”. We will ask Espresso to scroll the RecyclerView until it can find a note in the list that contains our description and verify that it is in fact displayed on the screen:</p><p>Espresso has out-of-the-box support for most support and design support library features! This makes it very convenient for you to use Espresso with APIs like RecyclerView and makes for a great UI testing experience! We will cover some of those APIs later in the <strong>Espresso-Contrib</strong> section of this codelab.</p><pre>// Scroll notes list to added note, by finding its description onView(withId(R.id.notes_list)).perform( scrollTo(hasDescendant(withText(newNoteDescription)))); // Verify note is displayed on screen onView(withItemText(newNoteDescription)).check(matches(isDisplayed()));</pre><p>This is our final implementation of the addNoteToNotesList() test:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/NotesScreenTest.java">androidTest/…/NotesScreenTest.java</a></h3><pre>@Test public void addNoteToNotesList() throws Exception { String newNoteTitle = &quot;Espresso&quot;; String newNoteDescription = &quot;UI testing for Android&quot;; // Click on the add note button onView(withId(R.id.fab_add_notes)).perform(click()); // Add note title and description // Type new note title onView(withId(R.id.add_note_title)).perform(typeText(newNoteTitle), closeSoftKeyboard()); onView(withId(R.id.add_note_description)).perform(typeText(newNoteDescription), closeSoftKeyboard()); // Type new note description and close the keyboard // Save the note onView(withId(R.id.fab_add_notes)).perform(click()); // Scroll notes list to added note, by finding its description onView(withId(R.id.notes_list)).perform( scrollTo(hasDescendant(withText(newNoteDescription)))); // Verify note is displayed on screen onView(withItemText(newNoteDescription)).check(matches(isDisplayed())); }</pre><p><strong>Run all Espresso tests again.</strong></p><p>Our test NotesScreenTest#addNoteToNotesList() is now no longer listed as failing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*YQ7xA5AtOTWNdsop.png" /></figure><p>You can also toggle view to display all passed tests using the button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/27/0*S_bJIRpZoux4g68h.png" /></figure><p>.</p><h3>Espresso test 3: Clicking a note</h3><p>In the previous step we implemented a test for the notes Presenter that verified that calling the ‘open a note’ call told the View to display note details. Now we will implement an end-to-end UI test that verifies that clicking a note will display the correct note on screen.</p><p>We will start again by implementing the test and then implementing the UI in the View.</p><p><strong>What happens in the app when you click a note? Let’s recap:</strong></p><p>The presenter receives a callback to openNoteDetails(...) with a note. This is triggered from a callback from the RecyclerView that displays the grid of notes.</p><p>The presenter then calls showNoteDetailUI on the View with the ID of the note.</p><h3>Switch build variant to mockDebug</h3><p>The test we are implementing now uses the mock source set to simulate a notes repository with a fake implementation. You need to switch your build variant to mockDebug to activate the correct tests. Our tests for the mockDebug variant live in app/src/andoidTestMock/....</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*fZPQ8TJY0tzpNwqi.png" /></figure><h3>Launch NoteDetailActivity with an Intent extra parameter</h3><p><strong>Edit the file </strong>app/src/<strong>androidTestMock</strong>/java/.../notedetail/<strong>NoteDetailScreenTest.java</strong> and comment in the method as you work through this section:</p><p>Our test is for the <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notedetail/NoteDetailActivity.java">NoteDetailActivity</a>,<strong> we have already defined </strong>an <a href="http://developer.android.com/reference/android/support/test/rule/ActivityTestRule.html">ActivityTestRule</a> for that Activity. The additional parameters specify the touch mode and if the Activity should be automatically launched before each @Test. We&#39;ll need to supply an extra parameter to the Activity via a custom Intent, so we will handle the launch ourselves.</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTestMock/java/com/example/android/testing/notes/notedetail/NoteDetailScreenTest.java">androidTestMock/…/NoteDetailScreenTest.java</a></h3><pre>@Rule public ActivityTestRule&lt;NoteDetailActivity&gt; mNoteDetailActivityTestRule = new ActivityTestRule&lt;&gt;(NoteDetailActivity.class, true /* Initial touch mode */, false /* Lazily launch activity */);</pre><p>Next, we will set up a method annotated with @Before that accesses this rule to create the intent (with a supplied note ID that we wish to display) that will start the Activity. The ActivityTestRule handles the creation and the lifecycle of the Activity during the test. This set up is essentially similar to the call to NoteDetailActivity.newInstance(...) with a Note ID.</p><p>We are using the <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/mock/java/com/example/android/testing/notes/data/FakeNotesServiceApiImpl.java">FakeNotesServiceApiImpl</a> to store our notes and we have added one single note to our repository. Comment in the set up steps in intentWithStubbedNoteId():</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTestMock/java/com/example/android/testing/notes/notedetail/NoteDetailScreenTest.java">androidTestMock/…/NoteDetailScreenTest.java</a></h3><pre>@Before public void intentWithStubbedNoteId() { // Add a note stub to the fake service api layer. FakeNotesServiceApiImpl.addNotes(NOTE); // Lazily start the Activity from the ActivityTestRule this time to inject the start Intent Intent startIntent = new Intent(); startIntent.putExtra(NoteDetailActivity.EXTRA_NOTE_ID, NOTE.getId()); mNoteDetailActivityTestRule.launchActivity(startIntent); registerIdlingResource(); }</pre><h3>Implement the test NoteDetailScreenTest#noteDetails_DisplayedInUI</h3><p>Implement the test noteDetails_DisplayedInUi() that verifies that the title, description and image match what we have just added. (Remember, the @Before method starts the NoteDetailActivity to the note we have just added.)</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTestMock/java/com/example/android/testing/notes/notedetail/NoteDetailScreenTest.java">androidTestMock/…/NoteDetailScreenTest.java</a></h3><pre>@Test public void noteDetails_DisplayedInUi() throws Exception { // Check that the note title, description and image are displayed onView(withId(R.id.note_detail_title)).check(matches(withText(NOTE_TITLE))); onView(withId(R.id.note_detail_description)).check(matches(withText(NOTE_DESCRIPTION))); onView(withId(R.id.note_detail_image)).check(matches(allOf( hasDrawable(), isDisplayed()))); }</pre><h3>Run the UI Test and Implement the logic</h3><p>Next, run this test! Right click on the class NoteDetailScreenTest and select <strong>Run</strong> &gt; <strong>Run &quot;NoteDetailScreenTest&quot;</strong> or use the build configuration we have set up before.</p><p>The test will fail because we haven’t implemented the logic in our View yet.</p><p>Switch to the <strong>Run</strong> view in Android Studio to see which test failed (and why it failed).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cw5aNEbyHNX3q6t3.png" /></figure><p>You may see the following error when running this test:</p><p>Process finished with exit code 1</p><p>Class not found: &quot;com.example.android.testing.notes.notedetail.NoteDetailScreenTest&quot;Empty test suite.</p><p>If that happens you’re very likely using the wrong test run configuration. Here is what the context menu should look like to create and run a instrumentation test run configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*V0lKiuSy3xQMmDqT.png" /></figure><p>Try to run all tests in the package <strong>com.example.android.testing.notes</strong>: Right click on the package name under app &gt; src &gt; androidTestMock &gt; java and select &quot;Run tests in ‘com.example...&#39;&quot; and you should see the instrumentation test run configuration from the first screenshot.</p><p>See the <strong>Troubleshooting section</strong> at the end if you have trouble running this test. (You may need to uninstall the previous build first — run the uninstallAll gradle task.)</p><p>The test will fail with an error similar to this:</p><pre>android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: &#39;with text: is &quot;ATSL&quot;&#39; doesn&#39;t match the selected view. Expected: with text: is &quot;ATSL&quot; Got: &quot;AppCompatTextView{id=2131492979, res-name=note_detail_title, visibility=VISIBLE, width=0, height=103, has-focus=false, has-focusable=fals &lt;... stacktrace ...&gt;</pre><p>This error tells us that the title TextView does not contain the expected text we have set on it.</p><p>We haven’t implemented the hooks for the NoteDetailContract.View yet which handles the display of note details.</p><p><strong>Edit the file </strong>app/src/main/java/.../noteDetail/NoteDetailFragment.java<strong> to add the missing logic</strong>:</p><p>Implement the methods: setProgressIndicator, hideDescription, hideTitle, showDescription and showTitle:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notedetail/NoteDetailFragment.java">NoteDetailFragment.java</a></h3><pre>@Override public void setProgressIndicator(boolean active) { if (active) { mDetailTitle.setText(&quot;&quot;); mDetailDescription.setText(getString(R.string.loading)); } } @Override public void hideDescription() { mDetailDescription.setVisibility(View.GONE); } @Override public void hideTitle() { mDetailTitle.setVisibility(View.GONE); } @Override public void showDescription(String description) { mDetailDescription.setVisibility(View.VISIBLE); mDetailDescription.setText(description); } @Override public void showTitle(String title) { mDetailTitle.setVisibility(View.VISIBLE); mDetailTitle.setText(title); }</pre><p>Run the test again (NoteDetailScreenTest) - the test noteDetails_DisplayedInUi now passes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*KL2PkSMPbcUPF-w6.png" /></figure><h3>Troubleshooting</h3><p>A common error while running your tests in this codelab setup is:</p><p>INSTALL_FAILED_UPDATE_INCOMPATIBLE</p><p>If you run into this error uninstall all artifacts from your test device using Android studio. Open the <strong>Gradle view</strong> on the right hand side of Android studio. Open <strong>:app </strong>&gt; <strong>Tasks &gt; install</strong> and run the <strong>uninstallAll</strong> task by double clicking it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*RoAE_iwQlLHtAm_a.png" /></figure><p><strong>Continue with your existing Android Studio project for this section.</strong></p><p><strong>If you would like to start fresh for this section, continue from snapshot ‘step-8’:<br></strong>Open the directory named <strong>step-8</strong> from <a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">the zip file</a> in Android Studio or checkout the branch step-8 directly from github: <br>git clone https://github.com/googlecodelabs/android-testing.git -b step-8</p><p><a href="https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html">Espresso-Intents</a> is an extension to Espresso that focuses on the validation and mocking of Intents. It has a similar API to Mockito (that we have explored earlier for mocking Java code), but for stubbing Intents.</p><p>If your app takes advantage of the full power of the Android platform by <em>intenting</em> out to other applications or the platform, you can focus on your own functionality and rely on the platform and other apps to function as expected. With Espresso-Intents you can validate your Intents or even stub out Intents by responding with your own results.</p><h3>Intent Matching</h3><p>Espresso-Intents adds the functionality to intercept Intents based on some matching criteria. These matchers are defined via <a href="https://code.google.com/p/hamcrest/">Hamcrest Matchers</a> (that we briefly explored earlier in the mocking section), but usually the <a href="http://developer.android.com/reference/android/support/test/espresso/intent/matcher/IntentMatchers.html">basic built-in matchers</a> provide sufficient functionality: you can match based on action, data, extras and categories or any combination thereof.</p><h3>Intent Stubbing</h3><p>Espresso-Intents also adds functionality to provide stub implementations to matching intents, by intercepting Intents and providing a response for Activities that are started with startActivityForResult(...)</p><p>Clicking on the “Add image” button on the “Add Note” screen sends an Intent to the camera application on the device to take a photo. The image is then returned back to the app.</p><p>We will write a test that verifies that after a photo is taken from that screen, its thumbnail is displayed in our app.</p><h3>Switch to the mockDebug Build Variant</h3><p>Make sure to select the the <strong>mockDebug</strong> build variant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*jE6D5_BNGlK_jDRo.png" /></figure><h3>Implement AddNoteScreenTest#addImageToNote_ShowsThumbnailInUi with Espresso-Intents</h3><p>Edit the file app/src/androidTestMock/java/.../addnote/AddNoteScreenTest.java and comment in the following lines as you work through this section:</p><p>First we have already set up an IntentsTestRule. It is an extension of ActivityTestRule that we have used earlier and specifically built for using the Espresso-Intents API in functional UI tests. It initialises Espresso-Intents before each @Test and releases it after each run.</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTestMock/java/com/example/android/testing/notes/addnote/AddNoteScreenTest.java">androidTestMock/…/AddNoteScreenTest.java</a></h3><pre>@Rule public IntentsTestRule&lt;AddNoteActivity&gt; mAddNoteIntentsTestRule = new IntentsTestRule&lt;&gt;(AddNoteActivity.class);</pre><p>Next, we will implement the test addImageToNote_ShowsThumbnailUi(). <br>Remove the call to fail(...).</p><pre>@Test public void addImageToNote_ShowsThumbnailInUi() { ... }</pre><p>We will stub out all Intents that match the MediaStore.ACTION_IMAGE_CAPTURE action and always respond with a valid (RESULT_OK) ActivityResult (provided by a call to createImageCaptureActivityResultStub() ).</p><p>First we will create the result object:</p><pre>ActivityResult result = createImageCaptureActivityResultStub();</pre><p>Next we instruct Espresso to respond to all intents that have the MediaStore.ACTION_IMAGE_CAPTURE action with the result object we have just created:</p><pre>intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result);</pre><p>Next we verify that no thumbnail image is being shown as a sanity check — no image has been taken yet.</p><pre>// Check thumbnail view is not displayed onView(withId(R.id.add_note_image_thumbnail)).check(matches(not(isDisplayed()))); selectTakeImageFromMenu();</pre><p>We select the “Add image” option in the menu using a short helper method:</p><pre>selectTakeImageFromMenu();</pre><p>selectTakeImageFromMenu() clicks the &quot;Add image&quot; button that fires off a MediaStore.ACTION_IMAGE_CAPTURE Intent. (If you are curious, we are using a convenience method called openActionBarOverflowOrOptionsMenu(...) from Espresso to open the menu.)</p><p>If the Intent was set up correctly, it will be captured by our test and a valid result will be returned. If the Intent does not match our expected value, it will not be matched and an assertion exception would be thrown.</p><p>Finally we check that the thumbnail is now being displayed:</p><pre>onView(withId(R.id.add_note_image_thumbnail)) .check(matches(allOf( hasDrawable(), isDisplayed())));</pre><p>This is our final addImageToNote_ShowsThumbnailInUi() test:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTestMock/java/com/example/android/testing/notes/addnote/AddNoteScreenTest.java">androidTestMock/…/AddNoteScreenTest.java</a></h3><pre>@Test public void addImageToNote_ShowsThumbnailInUi() { // Create an Activity Result which can be used to stub the camera Intent ActivityResult result = createImageCaptureActivityResultStub(); // If there is an Intent with ACTION_IMAGE_CAPTURE, intercept the Intent and respond with // a stubbed result. intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE)).respondWith(result); // Check thumbnail view is not displayed onView(withId(R.id.add_note_image_thumbnail)).check(matches(not(isDisplayed()))); selectTakeImageFromMenu(); // Check that the stubbed thumbnail is displayed in the UI onView(withId(R.id.add_note_image_thumbnail)) .perform(scrollTo()) // Scroll to thumbnail .check(matches(allOf( hasDrawable(), // Check ImageView has a drawable set with a custom matcher isDisplayed()))); }</pre><p><strong>Run the test!</strong></p><p>It should pass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*_eFSjmgvcYxfoDei.png" /></figure><p>By using the full power of the Android platform (and being a good app citizen), you can write tests that focus on your own functionality, without having to worry about functionality of the platform.</p><p><strong>Continue with your existing Android Studio project for this section.</strong></p><p><strong>If you would like to start fresh for this section, continue from snapshot ‘step-9’:<br></strong>Open the directory named <strong>step-9</strong> from <a href="https://github.com/googlecodelabs/android-testing/raw/master/android-testing-checkpoints.zip">the zip file</a> in Android Studio or checkout the branch step-9 directly from github: <br>git clone https://github.com/googlecodelabs/android-testing.git -b step-9</p><p>Espresso-contrib is an extension to the Espresso framework that contains a few additional, useful features that will help you write great tests with Espresso. Part of this component is support for RecyclerView that enables you to write ViewMatchers for items or perform specific <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/RecyclerViewActions.PositionableRecyclerViewAction.html">RecyclerViewAction</a>s (such as scrolling to a specific item). It also contains explicit support for the navigation drawer through <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerActions.html">DrawerActions</a> and <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerMatchers.html">DrawerMatchers</a>.</p><h3>Implement Espresso tests for the Navigation Drawer</h3><p>Let’s use some of these features of Espresso-contrib to write a test that verifies that opening the navigation drawer and selecting the ‘Statistics’ option opens that screen and hides the drawer when selected.</p><h3>Switch to the prodDebug build variant</h3><p>This test is using the main implementation and does not rely on the mock target. Switch the build variant to <strong>prodDebug</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*x_FDWyGwv1_ClJ7o.png" /></figure><h3>Implement AppNavigationTest#clickOnAndroidHomeIcon_OpensNavigation</h3><p>Edit the file app/src/androidTest/java/.../notes/AppNavigationTest.java and comment in the following lines as you work through this section:</p><p>Let’s add a new test called AppNavigationTest.</p><p>Make sure it is setup to run with the JUnit4 runner and is defined as a large test:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/AppNavigationTest.java">androidTest/…/AppNavigationTest.java</a></h3><pre>@RunWith(AndroidJUnit4.class) @LargeTest public class AppNavigationTest { ... }</pre><p><strong>Test Qualifiers</strong></p><p>Android test size annotations let you classify how long a test should take to run, and consequently, how frequently you can run the test. The annotations are defined in the android.test.suitebuilder.annotation package.</p><ul><li>@SmallTest: <em>&lt; 100ms execution time</em>, should be run very frequently, only uses local dependencies, no resource access</li><li>@MediumTest: <em>&lt; 2s execution time</em>, focus on limited subset of app components, no external resource access, mocking external dependencies</li><li>@LargeTest: <em>&gt; 2s execution time</em>, makes use of all platform resources, including external communications</li></ul><p>Well organized tests suites using test size annotations can improve your efficiency and productivity and establish a common understanding within your team on when to use the right test annotation for the job.</p><p>You can find out more in <a href="https://plus.google.com/+AndroidDevelopers/posts/TPy1EeSaSg8">this excellent #Protip on +Android Developers</a>.</p><h3>Espresso-Intents Test 1: Clicking “Navigate up” opens the Navigation Drawer</h3><p>Let’s write a small test that verifies that clicking the ‘Home’ icon on the start screen opens the navigation drawer.</p><p>Implement AppNavigationTest#clickOnAndroidHomeIcon_OpensNavigation(), which:</p><ul><li>Finds the navigation drawer layout and checks that it is closed (using the special <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerMatchers.html#isClosed(int)">isClosed()</a> matcher)</li><li>Clicks the “navigate up” button (we can find it by matching its content description — it is “Navigate up”.)</li><li>Verifies that the drawer is now open by using the <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerMatchers.html#isOpen(int)">isOpen(...)</a> matcher.</li></ul><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/AppNavigationTest.java">androidTest/…/AppNavigationTest.java</a></h3><pre>@Test public void clickOnAndroidHomeIcon_OpensNavigation() { // Check that left drawer is closed at startup onView(withId(R.id.drawer_layout)) .check(matches(isClosed(Gravity.LEFT))); // Left Drawer should be closed. // Open Drawer onView(withContentDescription(&quot;Navigate up&quot;)).perform(click()); // Check if drawer is open onView(withId(R.id.drawer_layout)) .check(matches(isOpen(Gravity.LEFT))); // Left drawer is open open. }</pre><p><strong>Run the test — clickOnAndroidHomeIcon_OpensNavigation should complete successfully:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*9_KTk-swQgGyJq9N.png" /></figure><h3>Espresso-Intents Test 2: Clicking the statistics option in navigation drawer opens the statistics screen</h3><p>Next, implement our test called clickOnStatisticsNavigationItem_ShowsStatisticsScreen() in the file using the drawer support from Espresso-contrib.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*IFYpO6WwfZcJ94Uo.png" /></figure><p>Edit the file app/src/androidTest/java/.../notes/AppNavigationTest.java and comment in the following lines as you work through this section:</p><p>We will be using a ViewAction from the espresso-contrib library: <a href="https://developer.android.com/reference/android/support/test/espresso/contrib/NavigationViewActions.html">NavigationViewActions.navigateTo(...)</a>. It provides an easy interface to match MenuItems in a NavigationView. Here we will be using it for the navigation drawer to find a specific item that we want to select.</p><ul><li>Find the navigation drawer layout, check that it is closed (using the special <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerMatchers.html#isClosed(int)">isClosed()</a> matcher) and trigger its <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/DrawerActions.html#open(int)">open(...)</a> action to open the drawer.</li><li>Now that the drawer is open we need to find the “statistics” item in the drawer and select it. We are using our own navigateTo(...) matcher on the DrawerLayout to find the statistics item by its ID.</li><li>Lastly, we verify that the correct text message “No statistics” is displayed. We are doing this by loading the text resource from the app itself (by getting the Android Context from the <a href="http://developer.android.com/reference/android/support/test/InstrumentationRegistry.html">InstrumentationRegistry</a>) and checking that the shown TextView displays the correct text.</li></ul><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/androidTest/java/com/example/android/testing/notes/notes/AppNavigationTest.java">androidTest/…/AppNavigationTest.java</a></h3><pre>@Test public void clickOnStatisticsNavigationItem_ShowsStatisticsScreen() { // Open Drawer to click on navigation. onView(withId(R.id.drawer_layout)) .check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be closed. .perform(open()); // Open Drawer // Start statistics screen. onView(withId(R.id.nav_view)) .perform(navigateTo(R.id.statistics_navigation_menu_item)); // Check that statistics Activity was opened. String expectedNoStatisticsText = InstrumentationRegistry.getTargetContext() .getString(R.string.no_statistics_available); onView(withId(R.id.no_statistics)).check(matches(withText(expectedNoStatisticsText))); }</pre><p>One of the key parts of Espresso is its ability to synchronize all test actions. Espresso waits until the UI is idle before it moves to the next operation. Likewise, it waits for AsyncTask background operations to complete. In general, this should address the majority of test synchronizations in your application. If you have written UI tests before, you will appreciate this feature — there’s no need to add waits or synchronization points to your app!</p><p>However, sometimes it is not possible to rely on automatic synchronisation, for instance when your app does background operations via non-standard means (managing threads directly or using custom Services). If you have run into a situation where you cannot rely on Espresso to automatically handle the synchronization for you, you can use <strong>idling resources</strong> and still rely on Espresso for synchronization.</p><p>As you use a resource that needs to be synchronized, register it with Espresso using <a href="https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/core/src/main/java/android/support/test/espresso/Espresso.java">Espresso.registerIdlingResource</a> in your test set up (usually in your @Before method), and implement the <a href="https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/idling-resource/src/main/java/android/support/test/espresso/IdlingResource.java">IdlingResource</a> interface to track their use.</p><h3>Idling Resources in Practice</h3><p>In our app we have wrapped the calls to <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/util/SimpleCountingIdlingResource.java">SimpleCountingIdlingResource</a> (which is a simple implementation of the IdlingResource interface) in the class EspressoIdlingResource that is used across the entire application. This makes it easy to use the idling resources across the entire app.</p><p>In case you don’t want to write your own, Espresso got you covered. Have a look at <a href="http://developer.android.com/reference/android/support/test/espresso/contrib/CountingIdlingResource.html">CountingIdlingResource</a> an IdlingResource provided by Espresso and maintains an internal counter that is exposed via increment() and decrement() calls.</p><p>You can see it in action in the <a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter</a>, where we increment the counter just before we make an asynchronous call to access the notes api to load in a list of notes. This signals to Espresso that the app is busy and holds all further execution of Espresso commands until the app is marked as idle again after the callback returns:</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/src/main/java/com/example/android/testing/notes/notes/NotesPresenter.java">NotesPresenter.java</a></h3><pre>@Override public void loadNotes(boolean forceUpdate) { mNotesView.setProgressIndicator(true); if (forceUpdate) { mNotesRepository.refreshData(); } // The network request might be handled in a different thread so make sure Espresso knows // that the app is busy until the response is handled. EspressoIdlingResource.increment(); // App is busy until further notice mNotesRepository.getNotes(new NotesRepository.LoadNotesCallback() { @Override public void onNotesLoaded(List&lt;Note&gt; notes) { EspressoIdlingResource.decrement(); // Set app as idle. mNotesView.setProgressIndicator(false); if (notes.isEmpty()) { mNotesView.showNotesEmptyPlaceholder(); } else { mNotesView.showNotes(notes); } } }); }</pre><p><a href="https://en.wikipedia.org/wiki/Code_coverage">Code coverage</a> describes how well your application is covered by tests. This can be useful to find areas of your app that aren’t tested well enough (and could contain potential bugs).</p><h3>Code Coverage for Unit Tests</h3><p>Android studio has built-in support to generate code coverage reports from unit tests. We’ll look at instrumentation tests in the next section. Note that these reports are independent of each other and are not merged.</p><p>Create a run configuration for the unit tests. In the test source set, under java, select the package name: <strong>com.example.android.testing.notes</strong>. Right click on the package name and select “<strong>Create tests in com.example.android.testing.notes</strong>”. (If you have previously created a test configuration, enable it by clicking on “Select tests in com.example…” In the next step, you need to edit the existing test configuration: Run &gt; Edit configurations )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*UPaNW_7kyHNHRYOp.png" /></figure><p>On the next dialog(Run &gt; Edit configurations), select the <strong>&quot;Code Coverage</strong>&quot; tab.</p><p>Select the “IntelliJ IDEA” coverage runner. Accept the (empty) default setting for the “packages and classes to record coverage data”. (You could go ahead and exclude the platform generated files (R.java and BuildConfig.java) by specifying the packages in the app, but that’s not required.)</p><p>Click OK to create the build configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XAHPWiRzt0sPwZYj.png" /></figure><p>Next, run the code coverage report. In the build configuration, select the new build configuration we have just created, and click the code coverage button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/25/0*-e56MudvIWkbZICZ.png" /></figure><p>to generate the report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*dqZhNDLbQbpoTKIM.png" /></figure><p>When the task finishes, the code coverage report will be displayed in a panel in the right hand side. (You may have to expand the panel by dragging on its side):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*2SshEw4nsQjdNEge.png" /></figure><p>On this panel you can navigate through each feature (which is contained in its own package) and you can even drill down all the way to exact methods. For example, navigate to the notedetail package (com &gt; example &gt; android &gt; testing &gt; notes) to see code coverage for the notes detail feature. Clicking on a class opens the editor for that file - code coverage is displayed in red and green bars on the left hand side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*_fOI4MFCGl7V1LO4.png" /></figure><h3>Code Coverage for Instrumentation Tests</h3><p>There is no support for showing code coverage reports for instrumentation tests in Android Studio.</p><p>First we need to update our gradle build configuration to enable code coverage reports for debug builds.</p><p>Open the file app/build.gradle and comment in the following line within the android section.</p><h3><a href="https://github.com/googlecodelabs/android-testing/blob/master/app/build.gradle">app/build.gradle</a></h3><pre>buildTypes { debug { // Run code coverage reports by default on debug builds. testCoverageEnabled = true } }</pre><p>This enables a new gradle task that will generate a code coverage report for debug builds.</p><p>In Android Studio, sync your gradle configuration with your project (</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/22/0*AlhrVTtYGqobsLGl.png" /></figure><p>in the toolbar) to see the new *CoverageReport gradle tasks.</p><p>Next, run the gradle task <strong>createMockDebugAndroidTestCoverageReport</strong> to generate the coverage report. You can run it from the <strong>Gradle Tasks</strong> perspective (on the right hand side of the screen in Android Studio) double click on <strong>verification</strong> &gt; <strong>createMockDebugAndroidTestCoverageReport</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*FZrXdNHxFq_ISjVP.png" /></figure><p>Or you can run it directly from the commandline:</p><pre>./gradlew createMockDebugAndroidTestCoverageReport</pre><p>Once the task is complete, you can find the coverage report in app/build/reports/coverage/mock/debug.</p><p>Open the file index.html in your web browser. (In Android Studio right click on the file index.html and select <strong>Open in Browser</strong> &gt; Chrome).</p><p>The report will look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*44-Djvekf9Je5skw.png" /></figure><p>You can explore the coverage of individual packages and files by navigating through the elements.</p><p>Go to the NotePresenter class (under com.example.android.testing.notes.addnote &gt; AddNotePresenter):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1NQDuqad2N8hM9_n.png" /></figure><p>Click on a method to see a graphical representation of the parts of the code that are covered by our instrumentation tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*q-CO5zZiXxl6ispm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tb_L0bItQSqUUpb.png" /></figure><p><strong>Congratulations!</strong></p><p>You have now learned the basics of app architecture design using the MVP (Model-View-Presenter) pattern and explored the world of testing on Android!</p><p>In this codelab we have covered testing from a few different angles — from functional unit tests (with the help of Mockito to handle Android dependencies) to instrumental UI tests with Espresso. Developing an application from a test-driven point of view like we did here can help you define a clean architecture and establish clear communication between different components of your application.</p><h3>What we’ve covered</h3><ul><li>Model-View-Presenter architecture</li><li>Unit Testing on Android: JUnit4</li><li>UI Testing on Android with Espresso</li><li>Mocking dependencies with Mockito</li><li>Advanced Espresso topics: Espresso-contrib and Espresso-intents</li><li>Code coverage reports</li></ul><h3>Next Steps</h3><ul><li>Add some tests to your own app!</li><li>For your next application, consider following a similar test-driven approach for development and design.</li></ul><h3>Learn More</h3><p><a href="https://docs.google.com/a/google.com/forms/d/1jhSvKLZSpgguVyc03FdjSMuyLsBwe2upKggte8nAhSs/viewform?entry.340009906=Android-testing">Tell us how we did</a></p><p><em>Originally published at </em><a href="https://codelabs.developers.google.com/codelabs/android-testing/index.html"><em>codelabs.developers.google.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366bda9729e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What you need to know about Android app memory leaks]]></title>
            <link>https://medium.com/@ngotantien/what-you-need-to-know-about-android-app-memory-leaks-bd54ccd86acf?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd54ccd86acf</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 02:30:26 GMT</pubDate>
            <atom:updated>2018-04-24T02:30:26.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an Android app is easy, but making a super-high-quality, memory-efficient Android app is not. Early on as an Android developer, I was mainly inclined to work on features that had a visual impact rather than on things that no one would notice at first glance. I formed a habit of avoiding or giving a lower priority to app optimization — including fixing memory leaks.</p><p>This naturally led to an accumulation of <a href="https://techbeacon.com/get-grip-technical-debt">technical debt</a>, which started affecting the performance and quality of my apps in the long run. Thank goodness I made the slow but deliberate effort to become more “performance-focused.”</p><p>I know the concept of memory leaks is quite daunting for a lot of developers. They find it difficult, time-consuming, boring, and unnecessary. But none of that is true. Once you start getting into it, you may even start to enjoy fixing memory leaks.</p><p>Here’s how even newbie developers can start building high-performance Android apps right from the start of their career.</p><p>Gartner Magic Quadrant for Software Test Automation</p><h3>Why doesn’t Java prevent memory leaks?</h3><p>In Android, you rarely write code in languages such as C or C++, where you have to manage the entire memory allocation and de-allocation yourself. Java is the primary language for Android, and thankfully, Java knows how to clean up after itself.</p><p>When I first read about memory leaks in Java, I wondered why I even had to worry about this when Java already has a dedicated <a href="https://techbeacon.com/14-languages-help-you-block-entire-classes-bugs">memory management</a> system.<em> </em>Is the Java garbage collector faulty?</p><p>No, it certainly is not. The garbage collector (GC) is one of the finest achievements of Java, and it deserves its due respect. The GC works just as it should, but it is our own programming mistakes that sometimes inhibit the GC from releasing unnecessary chunks of memory when it should.</p><h3>A brief look at how Java GC works</h3><p>Before going any further, you need to know a bit about how the garbage collector works. The concept is pretty simple, but what goes on under the hood is quite complicated sometimes.</p><p>A memory tree diagram.</p><p>Every Android (or Java) application has a starting point, from where objects get instantiated and methods get called. We can consider this starting point as the “root” of the memory tree. Some objects keep a reference to the root directly, and other objects are instantiated from them, keeping a reference to these objects, and so on.</p><p>Thus, a chain of references is formed, which creates the memory tree. So the garbage collector starts from the GC roots and traverses the objects directly or indirectly linked to the roots. At the end of this process, some objects have never been visited by the GC.</p><p>These objects are your garbage (or dead objects), and they are eligible to be collected by our beloved garbage collector.</p><p><strong>Bonus</strong>: <em>If you want to learn more about garbage collectors, I recommend you have a look </em><a href="https://www.youtube.com/watch?v=UnaNQgzw4zY"><em>here</em></a><em> and </em><a href="http://www.cubrid.org/blog/dev-platform/understanding-java-garbage-collection/"><em>here</em></a><em>.</em></p><h3>What is a memory leak? Should I care if I have one?</h3><p>Put simply, memory leaks happen when you hold on to an object long after its purpose has been served. The concept is as simple as that.</p><p>Every object has got its own lifetime, after which it needs to say goodbye and leave the memory. But if some other object(s) is holding onto this object (directly or indirectly), then the garbage collector will not be able to collect it. And this, my friend, is what we call a memory leak.</p><p>The good news is that you don’t need to worry too much about every single memory leak happening in your app. Not all memory leaks will hurt your app.</p><p>Some leaks are really minor (leaking a few kilobytes of memory), and some in the Android framework itself (yes, you read that right) you don’t need to fix. These will generally have a minimum impact on your app’s performance and can be safely ignored.</p><p>But there are others that can make your app lag badly or crash. These are the ones that you need to take care of.</p><h3>What happens during a bad memory leak?</h3><p>As the app is being used and the heap memory keeps on increasing, a short GC will kick off and try to clear up immediate dead objects. Now, these short GCs run concurrently (on a separate thread), and they don’t slow down your app significantly (2ms to 5ms pause). But remember, the less the garbage collector has to run, the better your app’s performance will be.</p><p>If your app has some serious memory leaks hidden under the hood, these short GCs will not be able to reclaim the memory, and the heap will keep on increasing, which will force a larger GC to kick off. This larger GC, called a <a href="https://plumbr.eu/blog/garbage-collection/minor-gc-vs-major-gc-vs-full-gc">“stop-the-world” GC</a>, pauses the entire application main thread for around 50ms to 100ms. At this point, your app seriously lags and becomes almost unusable.</p><p>If this doesn’t fix the problem, then the heap memory of your app will constantly increase until it reaches a point of death where no more memory can be allocated to your app, leading to the dreaded <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryError</a>, which crashes your app.</p><p>When you know the impact memory leaks can have on your app, you understand why you need to address them immediately.</p><h3>Detecting memory leaks</h3><p>Now that you know that you need to fix memory leaks hidden inside your app, how will you actually detect them?</p><p>The good thing is that Android Studio has a very useful and powerful tool for this, the monitors. There are monitors not only for memory usage, but for network, CPU, and GPU usage as well (more info <a href="https://developer.android.com/studio/profile/android-monitor.html">here</a>).</p><p>Memory, CPU, and network graphs in Android Studio</p><p>While using and debugging your app, keep a close eye on this memory monitor. The first symptom of a memory leak is when the memory usage graph constantly increases as you use the app and never goes down, even when you put the app in the background.</p><p>Use the <a href="https://developer.android.com/studio/profile/am-allocation.html"><strong>Allocation Tracker</strong></a> to check the percentage of memory allocated to different types of objects in your app. This gives you a clear idea of which objects occupy the most memory and need to be addressed specifically.</p><p>But this by itself is not enough. You also need to use the Dump Java Heap<strong> </strong>option to create a <a href="https://developer.android.com/studio/profile/am-hprof.html">heap dump</a> that actually represents a snapshot of the memory at a given point in time. Seems like a lot of boring and repetitive work, right? Yes, it truly is.</p><p>LeakCanary showing the stack trace of a memory leak</p><p>Engineers tend to be lazy, and this is exactly where <a href="https://github.com/square/leakcanary">LeakCanary</a> comes to the rescue. This library runs along with your app, dumps memory when needed, looks for potential memory leaks, and gives you a notification with a clean and useful stack trace to find the root cause of the leak.</p><p>(LeakCanary makes it super easy for developers to detect leaks in their apps. I can’t thank <a href="https://twitter.com/piwai">Py</a> from <a href="https://github.com/square">Square</a> enough for making such an amazing and lifesaving library. Kudos!)</p><p><strong>Bonus</strong>: <em>If you want get the most of this library, check out </em><a href="https://realm.io/news/droidcon-ricau-memory-leaks-leakcanary/"><em>this post</em></a><em>.</em></p><h3>Common memory leak scenarios and how to fix them</h3><p>In my experience, these are some of the most common scenarios that can lead to memory leaks.</p><h4>Unregistered listeners</h4><p>There are many situations where you register a listener in your Activity (or Fragment) but forget to unregister it. This can easily lead to a huge memory leak. Generally, these listeners balance off each other, so if you register one somewhere you also need to unregister it right there.</p><p>Suppose you want to receive location updates in your app. All you need to do is to get the <a href="https://developer.android.com/reference/android/location/LocationManager.html">LocationManager</a> system service and register a listener for location updates.</p><p>private void registerLocationUpdates(){mManager = (LocationManager) getSystemService(LOCATION_SERVICE);mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TimeUnit.MINUTES.toMillis(1), 100, this);</p><p>}</p><p>You have implemented the listener interface in your Activity itself, and thus the LocationManager keeps a reference to it. Now when it’s time for your Activity to die, the Android framework will call onDestroy() on it, but the garbage collector will not be able to remove the instance from memory because the LocationManager is still holding a strong reference to it.</p><p>The solution is very simple. Just unregister the listener in the onDestroy() method and you are good to go. This is what most of us forget or don’t even know.</p><p>@Overridepublic void onDestroy() { super.onDestroy(); if (mManager != null) { mManager.removeUpdates(this); }</p><p>}</p><h4>Inner classes</h4><p>Inner classes are very common in Java and are used by many Android developers for various tasks because of their simplicity. But with improper usage, these inner classes can also lead to potential memory leaks.</p><p>Here’s a look at another simple code example:</p><p>public class BadActivity extends Activity { private TextView mMessageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_bad_activity); mMessageView = (TextView) findViewById(R.id.messageView); new LongRunningTask().execute(); } private class LongRunningTask extends AsyncTask&lt;Void, Void, String&gt; { @Override protected String doInBackground(Void... params) { return &quot;Am finally done!&quot;; } @Override protected void onPostExecute(String result) { mMessageView.setText(result); } }</p><p>}</p><p>This is a very simple Activity, which starts a long-running task in a background thread (maybe a complex database query or a slow network call). After the task is finished, the result is shown in a TextView. Sound good?</p><p>No, certainly not. The problem here is that the non-static inner class holds an implicit reference to the outer enclosing class (that is, the Activity itself). Now if we rotate the screen or if this long-running task lives longer than the lifetime of the Activity, then it will not let the garbage collector collect the entire Activity instance from memory — a simple mistake leading to a <em>huge</em> memory leak.</p><p>But the solution, again, is very simple. Just have a look at it and you will understand.</p><p>public class GoodActivity extends Activity { private AsyncTask mLongRunningTask; private TextView mMessageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_good_activity); mMessageView = (TextView) findViewById(R.id.messageView); mLongRunningTask = new LongRunningTask(mMessageView).execute(); } @Override protected void onDestroy() { super.onDestroy(); mLongRunningTask.cancel(true); } private static class LongRunningTask extends AsyncTask&lt;Void, Void, String&gt; { private final WeakReference&lt;TextView&gt; messageViewReference; public LongRunningTask(TextView messageView) { this.messageViewReference = new WeakReference&lt;&gt;(messageView); } @Override protected String doInBackground(Void... params) { String message = null; if (!isCancelled()) { message = &quot;I am finally done!&quot;; } return message; } @Override protected void onPostExecute(String result) { TextView view = messageViewReference.get(); if (view != null) { view.setText(result); } } }</p><p>}</p><p>As you can see, we have transformed the non-static inner class to a static inner class because static inner classes don’t hold any implicit reference to its enclosing outer class. But now we can’t access the non-static variables (like the TextView) of the outer class from a static context, so we have to pass our required object references to the inner class through its constructor.</p><p>It is highly recommended that you wrap these object references in a WeakReference to prevent further memory leaks. <a href="http://javarevisited.blogspot.in/2014/03/difference-between-weakreference-vs-softreference-phantom-strong-reference-java.html">Make sure that you understand</a> the various types of references available in Java and how you can use them to avoid memory leaks.</p><h4>Anonymous classes</h4><p>Anonymous classes are a favorite tool among developers because the way they are defined makes it really easy write concise code. But from my experience, these anonymous classes have been the most common reason for memory leaks.</p><p>Anonymous classes are nothing but non-static inner classes, which means they can cause potential memory leaks for the same reasons I mentioned in the last section.</p><p>Here’s an example:</p><p>public class MoviesActivity extends Activity { private TextView mNoOfMoviesThisWeek; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_movies_activity); mNoOfMoviesThisWeek = (TextView) findViewById(R.id.no_of_movies_text_view); MoviesRepository repository = ((MoviesApp) getApplication()).getRepository(); repository.getMoviesThisWeek() .enqueue(new Callback&lt;List&lt;Movie&gt;&gt;() { @Override public void onResponse(Call&lt;List&lt;Movie&gt;&gt; call, Response&lt;List&lt;Movie&gt;&gt; response) { int numberOfMovies = response.body().size(); mNoOfMoviesThisWeek.setText(&quot;No of movies this week: &quot; + String.valueOf(numberOfMovies)); } @Override public void onFailure(Call&lt;List&lt;Movie&gt;&gt; call, Throwable t) { // Oops. } }); }</p><p>}</p><p>Here, we are using a very popular library called <a href="https://github.com/square/retrofit">Retrofit</a>, which is used for making a network call and displaying the result in a TextView. It is quite evident that the Callable object keeps a reference to the enclosing Activity class.</p><p>Now if this network call runs on a very slow connection and the Activity is rotated or destroyed somehow before the call ends, then the entire Activity instance will be leaked.</p><p>It is always advisable to use static inner classes instead of anonymous classes whenever possible. It’s not that you must stop using anonymous classes completely, but you have to understand and judge when it is safe to use them and when it is not.</p><h4>Bitmaps</h4><p>Every image that you see in your app is nothing but <a href="https://developer.android.com/reference/android/graphics/Bitmap.html">bitmap</a> objects, which contain the entire pixel data of an image.</p><p>These bitmap objects are generally quite heavy, and if they are dealt with improperly, they can lead to significant memory leaks that eventually crash your app due to <a href="https://developer.android.com/reference/java/lang/OutOfMemoryError.html">OutOfMemoryError</a>. The bitmap memory related to image resources that you use in your app is automatically managed by the framework, but if you are dealing with bitmaps manually, be sure to <a href="https://developer.android.com/reference/android/graphics/Bitmap.html#recycle%28%29">recycle()</a> them after use.</p><p>You should load large bitmaps by scaling them down, and use bitmap caching and pooling whenever possible to reduce memory usage. <a href="https://developer.android.com/training/displaying-bitmaps/manage-memory.html">Here</a> is a good resource to understand bitmap handling in depth.</p><h4>Contexts</h4><p>If you want to get things done in Android, the Context object is your go-to guy.</p><p>Another common reason for memory leaks is the misuse of the Context instances. The <a href="https://developer.android.com/reference/android/content/Context.html">Context</a> is simply an abstract class. There are many classes (like <a href="https://developer.android.com/reference/android/app/Activity.html">Activity</a>, <a href="https://developer.android.com/reference/android/app/Application.html">Application</a>, <a href="https://developer.android.com/reference/android/app/Service.html">Service</a>, etc.) that extend Context instances to provide their own functionalities.</p><p>But there is a difference between these Contexts. It is very important to understand the difference between the activity-level Context and the application-level Context and which one should be used under what circumstances.</p><p>Using the activity Context in the wrong place can keep a reference to the entire activity and cause a potential memory leak. <a href="https://medium.com/@ali.muzaffar/which-context-should-i-use-in-android-e3133d00772c#.mruk222z2">Here</a> is an excellent article for you to find out exactly which Context to use.</p><h3>Time to fix your apps</h3><p>Now that you know how garbage collection in Java works, what memory leaks are, and how they can have a significant impact on your app, it’s time to start looking for leaks in your code. I showed you some of the best tools and resources for learning how to detect and fix these, so there are no more excuses.</p><p>Let’s start building good-quality, high-performance Android apps from now on. Detecting and fixing memory leaks will not only make your app’s user experience better, but it will slowly turn you into a better developer as well.</p><p><em>Image credit: </em><a href="https://flic.kr/p/ekRWCx"><em>Flickr</em></a></p><p>Testing in the Agile Era: Top Tools and Processes</p><p><em>Originally published at </em><a href="https://techbeacon.com/what-you-need-know-about-android-app-memory-leaks"><em>techbeacon.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd54ccd86acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal way to write to external SD card on Android]]></title>
            <link>https://medium.com/@ngotantien/universal-way-to-write-to-external-sd-card-on-android-516905bbc066?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/516905bbc066</guid>
            <category><![CDATA[external-storage]]></category>
            <category><![CDATA[permission]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 04:26:14 GMT</pubDate>
            <atom:updated>2018-03-29T04:26:14.526Z</atom:updated>
            <content:encoded><![CDATA[<p>In addition to all other nice answers, I could add a bit more to this question so it can give wider coverage for readers. In my answer here, I would use 2 countable resources to present External Storage.</p><p>The first resource is from <strong>Android Programming, The Big Nerd Ranch Guide 2nd edition</strong>, chapter 16, page 294.</p><p>The book describes the basic and external file and directory methods. I will try to make a resume of what could be relevant to your question.</p><p>The following part from the book:</p><p><strong>External Storage</strong></p><p>Your photo needs more than a place on the screen. Full-size pictures are too large to stick inside a SQLite database, much less an Intent. They will need a place to live on your device’s filesystem. Normally, you would put them in your private storage. Recall that you used your private storage to save your SQLite database. With methods like Context.getFileStreamPath(String) and Context.getFilesDir(), you can do the same thing with regular files, too (which will live in a subfolder adjacent to the databases subfolder your SQLite database lives in)</p><p>Basic file and directory methods in <strong>Context</strong></p><pre>| Method | |---------------------------------------------------------------------------------------| |File etFilesDir() | | - Returns a handle to the directory for private application files. | | | |FileInputStream openFileInput(String name) | | - Opens an existing file for input (relative to the files directory). | | | |FileOutputStream openFileOutput(String name, int mode) | | - Opens a file for output, possibly creating it (relative to the files directory). | | | |File getDir(String name, int mode) | | - Gets (and possibly creates) a subdirectory within the files directory. | | | |String[] fileList() | | - Gets a list of file names in the main files directory, such as for use with | | openFileInput(String). | | | |File getCacheDir() | | - Returns a handle to a directory you can use specifically for storing cache files. | | You should take care to keep this directory tidy and use as little space as possible|</pre><p>If you are storing files that only your current application needs to use, these methods are exactly what you need.</p><p>On the other hand, if you need another application to write to those files, you are out of luck: while there is a Context.MODE_WORLD_READABLE flag you can pass in to openFileOutput(String, int), it is deprecated, and not completely reliable in its effects on newer devices. If you are storing files to share with other apps or receiving files from other apps (files like stored pictures), you need to store them on external storage instead.</p><p>There are two kinds of external storage: primary, and everything else. All Android devices have at least one location for external storage: the primary location, which is located in the folder returned by Environment.getExternalStorageDirectory(). This may be an SD card, but nowadays it is more commonly integrated into the device itself. Some devices may have additional external storage. That would fall under “everything else.”</p><p>Context provides quite a few methods for getting at external storage, too. These methods provide easy ways to get at your primary external storage, and kinda-sorta-easy ways to get at everything else. All of these methods store files in publicly available places, too, so be careful with them.</p><p>External file and directory methods in <strong>Context</strong></p><pre>| Method | | --------------------------------------------------------------------------------------| |File getExternalCacheDir() | | - Returns a handle to a cache folder in primary external storage. Treat it like you do| | getCacheDir(), except a little more carefully. Android is even less likely to clean | | up this folder than the private storage one. | | | |File[] getExternalCacheDirs() | | - Returns cache folders for multiple external storage locations. | | | |File getExternalFilesDir(String) | | - Returns a handle to a folder on primary external storage in which to store regular | | files. If you pass in a type String, you can access a specific subfolder dedicated | | to a particular type of content. Type constants are defined in Environment, where | | they are prefixed with DIRECTORY_. | | For example, pictures go in Environment.DIRECTORY_PICTURES. | | | |File[] getExternalFilesDirs(String) | | - Same as getExternalFilesDir(String), but returns all possible file folders for the | | given type. | | | |File[] getExternalMediaDirs() | | - Returns handles to all the external folders Android makes available for storing | | media – pictures, movies, and music. What makes this different from calling | | getExternalFilesDir(Environment.DIRECTORY_PICTURES) is that the media scanner | | automatically scans this folder. The media scanner makes files available to | | applications that play music, or browse movies and photos, so anything that you | | put in a folder returned by getExternalMediaDirs() will automatically appear in | | those apps. |</pre><p>Technically, the external folders provided above may not be available, since some devices use a removable SD card for external storage. In practice this is rarely an issue, because almost all modern devices have nonremovable internal storage for their “external” storage. So it is not worth going to extreme lengths to account for it. But we do recommended including simple code to guard against the possibility, which you will do in a moment.</p><p><strong>External storage permission</strong></p><p>In general, you need a permission to write or read from external storage. Permissions are well-known string values you put in your manifest using the &lt;uses-permission&gt; tag. They tell Android that you want to do something that Android wants you to ask permission for.</p><p>Here, Android expects you to ask permission because it wants to enforce some accountability. You tell Android that you need to access external storage, and Android will then tell the user that this is one of the things your application does when they try to install it. That way, nobody is surprised when you start saving things to their SD card.</p><p>In Android 4.4, KitKat, they loosened this restriction. Since Context.getExternalFilesDir(String) returns a folder that is specific to your app, it makes sense that you would want to be able to read and write files that live there. So on Android 4.4 (API 19) and up, you do not need this permission for this folder. (But you still need it for other kinds of external storage.)</p><p>Add a line to your manifest that requests the permission to read external storage, but only up to API Listing 16.5 Requesting external storage permission (AndroidManifest.xml)</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.bignerdranch.android.criminalintent&quot; &gt; &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; android:maxSdkVersion=&quot;18&quot; /&gt;</pre><p>The maxSdkVersion attribute makes it so that your app only asks for this permission on versions of Android that are older than API 19, Android KitKat. Note that you are only asking to read external storage. There is also a WRITE_EXTERNAL_STORAGE permission, but you do not need it. You will not be writing anything to external storage: The camera app will do that for you</p><p>The second resource is this <a href="https://developer.android.com/guide/topics/data/data-storage.html">link</a> read all of it, but you can also jump to <strong>Using the External Storage</strong> section.</p><p><strong>Reference:</strong></p><p><strong>More reading stuff:</strong></p><blockquote><strong><em>Disclaimer:</em></strong><em> This information was taken from Android Programming: The Big Nerd Ranch Guide with permission from the authors. For more information on this book or to purchase a copy, please visit bignerdranch.com.</em></blockquote><p><em>Originally published at </em><a href="https://stackoverflow.com/questions/40068984/universal-way-to-write-to-external-sd-card-on-android"><em>stackoverflow.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516905bbc066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SD Card on Android 5.0 and Later]]></title>
            <link>https://medium.com/@ngotantien/sd-card-on-android-5-0-and-later-8af3f342082?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af3f342082</guid>
            <category><![CDATA[mirco-sd-write-permission]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 04:16:51 GMT</pubDate>
            <atom:updated>2018-03-29T04:16:51.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Android version 4.4 (KitKat) drastically limits how user installed apps can access the external SD card. You can read more about the problem <a href="https://metactrl.com/docs/sdcard-on-kitkat/">in this article</a>. Practically the only workaround is to root the device and modify a system config file. It’s only one-line change but admitedly rooting is not something normal users would want to do.</p><p>Fortunately in Android 5.0 and later there is a new official way for apps to write to the external SD card. Apps must ask the user to grant write access to a folder on the SD card. They open a system folder chooser dialog. The user need to navigate into that specific folder and select it.</p><p>In our sync apps there is a new item in the app settings: “SD Card Write Access”. Selecting it opens a screen showing the current write access status. If write access is not possible, you can enable it by tapping “Enable Write Access” button. A system folder chooser dialog is displayed. For most users its initial state is completely empty!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*NDTWx6aKJ0VKhE5H.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*o7ppWevqN8HMiUQ_.png" /></figure><p>You need to go to the menu and tell the system to show the SD card</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*W3yezxQETQFnywIN.png" /></figure><p>Tap on the SD card from the list on the left side to display its folder structure. In this screenshot you see both “Internal storage” and the SD card. The SD card can be displayed under a different name then what you see here, for example “Kingston”. It’s the so called “disk label” of the card. The disk label is a short text the user uses to name the card. If there is no disk label, the system folder chooser uses a generic name “SD card”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*xKDgA32SWnjn0khW.png" /></figure><p>Then select the card. Don’t navigate down into any subfolder. You must select the top-level root folder of the SD card. This is important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*qD05WwJ_uUkVOqTv.png" /></figure><p>After tapping the “Select SD card” button you should be back in the app. The app double checks if it now indeed can write to the SD card. You should see a message about the check result in the app.</p><p>If you replace the SD card in your device, you need to go through this procedure again. The write permission is granted individually for each app and each physical SD card.</p><h3>App Crash</h3><p>Some devices running Android 5, at least NVIDIA SHIELD and HTC One M8, suffer <a href="https://code.google.com/p/android/issues/detail?id=103249">a known bug</a> The system folder chooser dialog crashes and brings the whole app down with it after users press the “Select SD card” button.</p><p>The crash happens if the SD card doesn’t have a name (aka disk label). To avoid the crash you need to give a name to the card, for example, by following these steps</p><ul><li>Take the SD card out of the device</li><li>Find an adapter, USB card reader or something so you can plug the card to your computer.</li><li>On your computer give the card a name. How to do it depends on which operating system you use on your computer. Usually right click on the card icon on the computer desktop or file explorer, then choose “Rename” from the context menu would do it.</li></ul><p>This is a system bug. Apps can’t workaround it by themselves.</p><p><em>Originally published at </em><a href="https://metactrl.com/docs/sdcard-on-lollipop/"><em>metactrl.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af3f342082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Apache Tomcat 9 (on Windows, Mac OS X, Ubuntu) and Get Started with Java Servlet…]]></title>
            <link>https://medium.com/@ngotantien/how-to-install-apache-tomcat-9-on-windows-mac-os-x-ubuntu-and-get-started-with-java-servlet-45f959d7ee0a?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f959d7ee0a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java-servlet-programming]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Sat, 24 Feb 2018 17:24:47 GMT</pubDate>
            <atom:updated>2018-02-24T17:24:48.619Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Install Apache Tomcat 9 (on Windows, Mac OS X, Ubuntu) and Get Started with Java Servlet Programming</h3><p>This practical can be completed in a 3-hour session.</p><p>This installation and configuration guide is applicable to Tomcat 9, and possibly the earlier versions.</p><p>Take note that Tomcat 9 requires JDK 1.8 and later. You can check your JDK version via command “javac -version&quot;.</p><h3>Introduction</h3><h4>Web Application (Webapp)</h4><p>A <em>web application</em> (or webapp), unlike standalone application, runs over the Internet. Examples of webapps are google, amazon, ebay, facebook and twitter.</p><p>A webapp is typically a <em>3-tier</em> (or <em>multi-tier</em>) <em>client-server database application</em> run over the Internet as illustrated in the diagram below. It comprises five components:</p><ol><li>HTTP Server: E.g., Apache HTTP Server, Apache Tomcat Server, Microsoft Internet Information Server (IIS), nginx, Google Web Server (GWS), and others.</li><li>HTTP Client (or Web Browser): E.g., Internet Explorer (MSIE), FireFox, Chrome, Safari, and others.</li><li>Database: E.g., Open-source MySQL, Apache Derby, mSQL, SQLite, PostgreSQL, OpenOffice’s Base; Commercial Oracle, IBM DB2, SAP SyBase, MS SQL Server, MS Access; and others.</li><li>Client-Side Programs: could be written in HTML Form, JavaScript, VBScript, Flash, and others.</li><li>Server-Side Programs: could be written in Java Servlet/JSP, ASP, PHP, Perl, Python, CGI, and others.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/0*81qSAChtTliKJk5n.png" /></figure><p>The typical use-case is:</p><ol><li>A user, via a web browser (HTTP client), issues a URL request to an HTTP server to start a webapp.</li><li>The HTTP server returns an HTML form (client-side program), which is loaded into the client’s browser.</li><li>The user fills up the query criteria inside the form and submits the form.</li><li>The client-side program sends the query parameters to a server-side program.</li><li>The server-side program receives the query parameters, queries the database based on these parameters, and returns the query result to the client-side program.</li><li>The client-side program displays the query result on the browser.</li><li>The process repeats for the next request.</li></ol><h4>Hypertext Transfer Protocol (HTTP)</h4><ul><li>HTTP is an <em>application layer</em> protocol runs over TCP/IP. The IP provides support for routing and addressing (via an unique IP address for machines on the Internet); while TCP supports multiplexing via 64K ports from port number 0 to 65535. The default port number assigned to HTTP is TCP port 80.</li><li>HTTP is an <em>asynchronous request-response application-layer protocol</em>. A client sends a request message to the server. The server then returns a response message to the client. In other words, HTTP is a <em>pull</em> protocol, a client pulls a page from the server (instead of server pushes pages to the clients).</li><li>The syntax of the message is defined in the <a href="http://www.w3.org/standards/webdesign/htmlcss">HTTP specification</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*D7Gnzk7KAx2DYNle.png" /></figure><h4>Apache Tomcat HTTP Server</h4><p><em>Apache Tomcat</em> is a Java-capable HTTP server, which could execute special Java programs known as “Java Servlet” and “Java Server Pages (JSP)”. Tomcat is an <em>open-source</em> project, under the “Apache Software Foundation” (which also provides the most use, open-source, industrial-strength Apache HTTP Server). The mother site for Tomcat is <a href="http://tomcat.apache.org/">http://tomcat.apache.org</a>. Alternatively, you can find tomcat via the Apache mother site @ <a href="http://www.apache.org/">http://www.apache.org</a>.</p><p>Tomcat was originally written by James Duncan Davison (then working in Sun), in 1998, based on an earlier Sun’s server called Java Web Server (JWS). It began at version 3.0 after JSWDK 2.1 it replaced. Sun subsequently made Tomcat open-source and gave it to Apache.</p><p>The various Tomcat releases are:</p><ol><li>Tomcat 3.x (1999): RI for Servlet 2.2 and JSP 1.1.</li><li>Tomcat 4.x (2001): RI for Servlet 2.3 and JSP 1.2.</li><li>Tomcat 5.x (2002): RI for Servlet 2.4 and JSP 2.0.</li><li>Tomcat 6.x (2006): RI for Servlet 2.5 and JSP 2.1.</li><li>Tomcat 7.x (2010): RI for Servlet 3.0, JSP 2.2 and EL 2.2.</li><li>Tomcat 8.x (2013): RI for Servlet 3.1, JSP 2.3, EL 3.0 and WebSocket 1.0.</li><li>Tomcat 9.x (2018): RI for Servlet 4.0, JSP 2.3, EL 3.0, WebSocket 1.0, JASPIC 1.1.</li></ol><p>Tomcat is an HTTP application runs over TCP/IP. In other words, the Tomcat server runs on a specific TCP port from a specific IP address. The default TCP port number for HTTP protocol is 80, which is used for the <em>production</em> HTTP server. For <em>test</em> HTTP server, you can choose any unused port number between 1024 and 65535.</p><h3>How to Install Tomcat 9 and Get Started with Java Servlet Programming</h3><h4>STEP 0: Create a Directory to Keep all your Works</h4><p>I shall assume that you have created a directory called “c:\myWebProject&quot; (for Windows) or &quot;~\myWebProject&quot; (for Mac OS X) in your earlier exercises. Do it otherwise.</p><p>This step is important; otherwise, you will be out-of-sync with this article and will not be able to find your files later.</p><h4>STEP 1: Download and Install Tomcat</h4><p>For academic learning, I recommend “zip&quot; (or &quot;tar.gz&quot;) version, as you could simply delete the entire directory when Tomcat is no longer needed (without running any un-installer). You are free to move or rename the Tomcat&#39;s installed directory. You can install (unzip) multiple copies of Tomcat in the same machine. For production, it is easier to use the installer to properly configure the Tomcat.</p><p>Tomcat’s Directories</p><p>Take a quick look at the Tomcat installed directory. It contains the these sub-directories:</p><ul><li>bin: contains the binaries; and startup script (startup.bat for Windows and startup.sh for Unixes and Mac OS), shutdown script (shutdown.bat for Windows and shutdown.sh for Unix and Mac OS), and other binaries and scripts.</li><li>conf: contains the system-wide configuration files, such as server.xml, web.xml, and context.xml.</li><li>webapps: contains the webapps to be deployed. You can also place the WAR (Webapp Archive) file for deployment here.</li><li>lib: contains the Tomcat’s system-wide JAR files, accessible by all webapps. You could also place external JAR file (such as MySQL JDBC Driver) here.</li><li>logs: contains Tomcat’s log files. You may need to check for error messages here.</li><li>work: Tomcat’s working directory used by JSP, for JSP-to-Servlet conversion.</li></ul><h4>STEP 2: Create an Environment Variable JAVA_HOME</h4><h4>STEP 3: Configure Tomcat Server</h4><p>The Tomcat configuration files are located in the “conf&quot; sub-directory of your Tomcat installed directory, e.g. &quot;c:\myWebProject\tomcat\conf&quot; (for Windows) or &quot;~/myWebProject/tomcat/conf&quot; (for Mac OS X). There are 4 configuration XML files:</p><ol><li>server.xml</li><li>web.xml</li><li>context.xml</li></ol><p>Make a BACKUP of the configuration files before you proceed!!!</p><p>Step 3(a) “conf\server.xml” — <strong>Set the TCP Port Number</strong></p><p>Use a programming text editor (e.g., NotePad++, TextPad, Sublime, Atom for Windows; or gEdit, jEdit, Sublime, Atom for Mac OS) to open the configuration file “server.xml&quot;, under the &quot;conf&quot; sub-directory of Tomcat installed directory.</p><p>The default TCP port number configured in Tomcat is 8080, you may choose any number between 1024 and 65535, which is not used by an existing application. We shall choose 9999 in this article. (For production server, you should use port 80, which is pre-assigned to HTTP server as the default port number.)</p><p>Locate the following lines (around Line 69) that define the HTTP connector, and change port=&quot;8080&quot; to port=&quot;9999&quot;.</p><pre>&lt;Connector port=&quot;9999&quot; protocol=&quot;HTTP/1.1&quot; connectionTimeout=&quot;20000&quot; redirectPort=&quot;8443&quot; /&gt;</pre><p>Step 3(b) “conf\web.xml” — <strong>Enabling Directory Listing</strong></p><p>Again, use a programming text editor to open the configuration file “web.xml&quot;, under the &quot;conf&quot; sub-directory of Tomcat installed directory.</p><p>We shall enable directory listing by changing “listings&quot; from &quot;false&quot; to &quot;true&quot; for the &quot;default&quot; servlet. This is handy for test system, but not for production system for security reasons.</p><p>Locate the following lines (around Line 108) that define the “default” servlet; and change the “listings” from “false&quot; to &quot;true&quot;.</p><pre>&lt;servlet&gt; &lt;servlet-name&gt;<strong>default</strong>&lt;/servlet-name&gt; &lt;servlet-class&gt;org.apache.catalina.servlets.DefaultServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;debug&lt;/param-name&gt; &lt;param-value&gt;0&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;<strong>listings</strong>&lt;/param-name&gt; &lt;param-value&gt;<strong>true</strong>&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt;</pre><p>Step 3(c) “conf\context.xml” — <strong>Enabling Automatic Reload</strong></p><p>We shall add the attribute reloadable=&quot;true&quot; to the &lt;Context&gt; element to enable automatic reload after code changes. Again, this is handy for test system but not for production, due to the overhead of detecting changes.</p><p>Locate the &lt;Context&gt; start element (around Line 19), and change it to &lt;Context reloadable=&quot;true&quot;&gt;.</p><pre>&lt;Context <strong>reloadable=&quot;true&quot;</strong>&gt; ...... ...... &lt;/Context&gt;</pre><h4>STEP 4: Start Tomcat Server</h4><p>The Tomcat’s executable programs and scripts are kept in the “bin&quot; sub-directory of the Tomcat installed directory.</p><p>Step 4(a) Start Server</p><p>A <em>new</em> Tomcat console window appears. Study the messages on the console. Look out for the Tomcat’s port number (double check that Tomcat is running on port 9999). Future error messages will be send to this console. System.out.println() issued by your Java servlets will also be sent to this console.</p><pre>...... xxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [&quot;http-nio-9999&quot;] xxxxx INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler [&quot;ajp-nio-8009&quot;] xxxxx INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 1325 ms</pre><p>(Skip Unless …) Cannot Start Tomcat: Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html#TomcatDebug">How to Debug</a>”.</p><p>Step 4(b) Start a Client to Access the Server</p><p>Start a browser (Firefox, Chrome) as an HTTP client. Issue URL “http://localhost:9999&quot; to access the Tomcat server&#39;s welcome page. The hostname &quot;localhost&quot; (with IP address of 127.0.0.1) is meant for local loop-back testing inside the same machine. For users on the other machines over the net, they have to use the server&#39;s IP address or DNS domain name or hostname in the format of &quot;http://<em>serverHostnameOrIPAddress</em>:9999&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*iK0B79I8C-F_HYpA.png" /></figure><p>Try issuing URL http://localhost:9999/examples to view the servlet and JSP examples. Try running some of the servlet examples.</p><p>Step 4(c) Shutdown Server</p><p>WARNING: You MUST properly shutdown the Tomcat. DO NOT kill the cat by pushing the window’s “CLOSE” button.</p><h4>STEP 5: Develop and Deploy a WebApp</h4><p>Step 5(a) Create the Directory Structure for your WebApp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*DEjf5OYeoXI86F2R.png" /></figure><p>Let’s call our first webapp “hello&quot;. Goto Tomcat&#39;s &quot;webapps&quot; sub-directory and create the following directory structure for your webapp &quot;hello&quot; (as illustrated):</p><ol><li>Under Tomcat’s “webapps&quot;, create your webapp&#39;s <em>root</em> directory &quot;hello&quot; (i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello&quot;).</li><li>Under “hello&quot;, create a sub-directory &quot;WEB-INF&quot; (case sensitive, a &quot;dash&quot; not an underscore) (i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello\WEB-INF&quot;).</li><li>Under “WEB-INF&quot;, create a sub-sub-directory &quot;classes&quot; (case sensitive, plural) (i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello\WEB-INF\classes&quot;).</li></ol><p>You need to keep your web resources (e.g., HTMLs, CSSs, images, scripts, servlets, JSPs) in the proper directories:</p><ul><li>“hello&quot;: The is called the <em>context root</em> (or <em>document base directory</em>) of your webapp. You should keep all your HTML files and resources visible to the web users (e.g., HTMLs, CSSs, images, scripts, JSPs) under this <em>context root</em>.</li><li>“hello/WEB-INF&quot;: This directory, although under the context root, is <em>not visible</em> to the web users. This is where you keep your application&#39;s web descriptor file &quot;web.xml&quot;.</li><li>“hello/WEB-INF/classes&quot;: This is where you keep all the Java classes such as servlet class-files.</li></ul><p>You should RE-START your Tomcat server to pick up the hello webapp. Check the Tomcat&#39;s console to confirm that &quot;hello&quot; application has been properly deployed:</p><pre>...... xxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [xxx\webapps\hello] xxxxx INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [xxx\webapps\hello] has finished in [38] ms ......</pre><p>You can issue the following URL to access the web application “hello&quot;:</p><pre><a href="http://localhost:9999/hello">http://localhost:9999<strong>/hello</strong></a></pre><p>You should see the directory listing of the directory “&lt;TOMCAT_HOME&gt;\webapps\hello&quot;, which shall be empty at this point of time. (Take note that we have earlier enabled directory listing in &quot;web.xml&quot;. Otherwise, you will get an error &quot;404 Not Found&quot;).</p><p>Step 5(b) Write a Welcome Page</p><p>Create the following HTML page and save as “HelloHome.html&quot; in your application&#39;s root directory &quot;hello&quot;.</p><pre>1 2 3 4 5 6</pre><pre>&lt;html&gt; &lt;head&gt;&lt;title&gt;My Home Page&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;My Name is so and so. This is my HOME.&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt;</pre><p>You can browse this page by issuing this URL:</p><pre><a href="http://localhost:9999/hello/HelloHome.html">http://localhost:9999/hello/<strong>HelloHome.html</strong></a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*2N8jv32UDCVC0Q0B.png" /></figure><p>Alternatively, you can issue an URL to your web application root “hello&quot;:</p><pre><a href="http://localhost:9999/hello">http://localhost:9999/hello</a></pre><p>The server will return the directory listing of your base directory. You can then click on “HelloHome.html&quot;.</p><p>Rename “HelloHome.html&quot; to &quot;index.html&quot;, and issue a directory request again:</p><pre><a href="http://localhost:9999/hello">http://localhost:9999/hello</a></pre><p>Now, the server will redirect the directory request to “index.html&quot;, if the root directory contains an &quot;index.html&quot;, instead of serving the directory listing.</p><p>You can check out the home page of your peers by issuing:</p><pre><a href="http://yourpeerhostnameoripaddress:9999/hello">http://<em>YourPeerHostnameOrIPAddress</em>:9999/hello</a> <a href="http://yourpeerhostnameoripaddress:9999/hello/HelloHome.html">http://<em>YourPeerHostnameOrIPAddress</em>:9999/hello/HelloHome.html</a> <a href="http://yourpeerhostnameoripaddress:9999/hello/index.html">http://<em>YourPeerHostnameOrIPAddress</em>:9999/hello/index.html</a></pre><p>with a valid “<em>YourPeerHostnameOrIPAddress</em>&quot;, provided that your peer has started his tomcat server and his firewall does not block your access. You can use command such as &quot;ipconfig&quot; (Windows), &quot;ifconfig&quot; (Mac OS and Unix) to find your IP address.</p><p>(Skip Unless…) The likely errors are “Unable to Connect”, “Internet Explorer cannot display the web page”, and “404 File Not Found”. Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html#TomcatDebug">How to Debug</a>” section.</p><h4>STEP 6: Write a “Hello-world” Java Servlet</h4><p>A <em>servlet</em> is Java program that runs inside a Java-capable HTTP Server, such as Apache Tomcat. A web user invokes a servlet by issuing an appropriate URL from a web browser (HTTP client).</p><p>Before you proceed, I shall assume that you are familiar with Java Programming and have installed the followings:</p><p>Step 6(a) Write a “Hello-world” Java Servlet</p><p>A Java servlet is a Java program that runs inside a HTTP server. A web user invokes a servlet by issuing a URL from a browser (or HTTP client).</p><p>In this example, we are going to write a Java servlet called HelloServlet, which says &quot;Hello, world!&quot;. We shall configure such that web users can invoke this servlet by issuing URL http://<em>hostname</em>:<em>port</em>/hello/sayhello from their browser, as illustrated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*bz2zsHfd0OeW9V0Y.png" /></figure><p>Write the following source codes called “HelloServlet.java&quot; and save it under your application &quot;classes&quot; directory (i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello\<strong>WEB-INF\classes</strong>\HelloServlet.java&quot;). This servlet says &quot;Hello&quot;, echoes some request information, and prints a random number upon each request.</p><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34</pre><pre>import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class <strong>HelloServlet</strong> extends HttpServlet { @Override public void <strong>doGet</strong>(HttpServletRequest <strong>request</strong>, HttpServletResponse <strong>response</strong>) throws IOException, ServletException { <strong>response.setContentType(&quot;text/html&quot;);</strong> <strong>PrintWriter out = response.getWriter();</strong> try { out.println(&quot;&lt;html&gt;&quot;); out.println(&quot;&lt;head&gt;&lt;title&gt;Hello, World&lt;/title&gt;&lt;/head&gt;&quot;); out.println(&quot;&lt;body&gt;&quot;); out.println(&quot;&lt;h1&gt;Hello, world!&lt;/h1&gt;&quot;); out.println(&quot;&lt;p&gt;Request URI: &quot; + <strong>request.getRequestURI()</strong> + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;Protocol: &quot; + <strong>request.getProtocol()</strong> + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;PathInfo: &quot; + <strong>request.getPathInfo()</strong> + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;Remote Address: &quot; + <strong>request.getRemoteAddr()</strong> + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;A Random Number: &lt;strong&gt;&quot; + <strong>Math.random()</strong> + &quot;&lt;/strong&gt;&lt;/p&gt;&quot;); out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;); } finally { out.close(); } } }</pre><p>Step 6(b) Compiling the Servlet (DIFFICULT)</p><p>We need the Servlet API to compile the servlet. Servlet API is NOT part of JDK. Nonetheless, Tomcat provides a copy in &lt;TOMCAT_HOME&gt;/lib/servlet-api.jar. We need to include this JAR file in the compilation via the -cp (classpath) option.</p><p>The output of the compilation is “HelloServlet.class&quot;. Browse the &quot;classes&quot; folder to make sure that it is created.</p><p>(Skip Unless…) Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/ErrorMessages.html#ServletErrors">Common Errors in Compiling Java Servlet</a>”.</p><p>Step 6(c) Configure Servlet’s Request URL in “webapps\hello\WEB-INF\web.xml”</p><p>A web user invokes a servlet, which is kept in the web server, by issuing <em>a request URL</em> from the browser. We need to configure this request URL for our HelloServlet.</p><p>Create the following configuration file called “<strong>web.xml</strong>&quot;, and save it under &quot;<strong>webapps\hello\WEB-INF</strong>&quot; (i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello\WEB-INF\web.xml&quot;).</p><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21</pre><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;web-app version=&quot;3.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;&gt; &lt;servlet&gt; &lt;servlet-name&gt;<strong>HelloWorld</strong>&lt;/servlet-name&gt; &lt;servlet-class&gt;<strong>HelloServlet</strong>&lt;/servlet-class&gt; &lt;/servlet&gt;  &lt;servlet-mapping&gt; &lt;servlet-name&gt;<strong>HelloWorld</strong>&lt;/servlet-name&gt; &lt;url-pattern&gt;<strong>/sayhello</strong>&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt;</pre><p>In the above configuration, a servlet having a class file “HelloServlet.class&quot; is mapped to request URL &quot;/sayhello&quot; (via an <em>arbitrary</em> servlet-name &quot;HelloWorld&quot;), under this web application &quot;hello&quot;. In other words, the complete request URL for this servlet is &quot;http://<em>hostname</em>:<em>port</em><strong>/hello/sayhello</strong>&quot;.</p><p>This configuration file, saved under your webapp “hello&quot;, is applicable only to this particular webapp &quot;hello&quot;.</p><p>RESTART your Tomcat server to refresh the “web.xml&quot; file.</p><p>IMPORTANT: For EACH servlet, you need to write a pair of &lt;servlet&gt; and &lt;servlet-mapping&gt; elements with a common but arbitrary &lt;servlet-name&gt;. Take note that all the &lt;servlet&gt; elements MUST be grouped together and placed IN FRONT of the &lt;servlet-mapping&gt; elements.</p><p>Step 6(d) Invoke the Servlet</p><p>To run this servlet, start a browser, and issue the request URL configured earlier:</p><pre><a href="http://localhost:9999/hello/sayhello">http://localhost:9999/<strong>hello/sayhello</strong></a></pre><p>You shall see the output of the servlet displayed in your web browser.</p><p>Refresh the browser, you shall see a new random number upon each refresh. In other word, the doGet() method of the servlet runs once per request.</p><p>View Page Source</p><p>(For Firefox and Chrome) Right-click the page ⇒ “View Page Source” to look at the output received by the web browser (returned by the server). Take note that the web browser receives only the output of the servlet (generated via the out.println() statements). The client has no access to the servlet source codes (which may contain confidential information).</p><p>(For Mac OS’s Safari browser) You need to enable “Developer Menu” under the “Preferences” to enable the “View Source” menu.</p><pre>&lt;html&gt; &lt;head&gt;&lt;title&gt;Hello, World&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello, world!&lt;/h1&gt; &lt;p&gt;Request URI: /hello/sayhello&lt;/p&gt; &lt;p&gt;Protocol: HTTP/1.1&lt;/p&gt; &lt;p&gt;PathInfo: null&lt;/p&gt; &lt;p&gt;Remote Address: 127.0.0.1&lt;/p&gt; &lt;p&gt;A Random Number: &lt;strong&gt;0.3523682325749493&lt;/strong&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</pre><p>(Skip Unless…) The likely errors are “404 File Not Found” and “500 Internal Server Error”. Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html#TomcatDebug">How to debug</a>” Section.</p><p>(Optional) Inspecting HTTP Request and Response Messages</p><p>When you enter a URL (e.g., http://localhost:9999/hello/sayhello) on a web browser, an HTTP GET <em>request message</em> is sent to the server; and the server returns a <em>response message</em> for display on the web browser. You can inspect the request and response messages via Web browser&#39;s Developer Tool.</p><p>For <strong>Firefox</strong>, press F12 to enable “web console”. Choose “Console” pane. Enter URL http://localhost:9999/hello/sayhello (or refresh). Enable &quot;Net&quot; (not in Gray). Expand the link http://localhost:9999/hello/sayhello. A HTTP message consists of a header and a body. Inspect the request header and body; as well as the response header and body.</p><p>For <strong>Chrome</strong>, press F12 to enable “developer tool”. Choose “Network” pane. Enter URL http://localhost:9999/hello/sayhello (or refresh). Select the link http://localhost:9999/hello/sayhello.Inspect the request header and body; as well as the response header and body.</p><p>The request message <em>header</em> is as follows:</p><pre>GET <a href="http://localhost:9999/hello/sayhello">http://localhost:9999/hello/sayhello</a> HTTP/1.1 Host: localhost:9999 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 Cache-Control:max-age=0 Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0</pre><p>For this request, there is no request message body.</p><p>The response message <em>header </em>is as follows:</p><pre>HTTP/1.1 200 OK Date: Wed, 22 Mar 2017 09:30:23 GMT Content-Length: 286 Content-Type: text/html;charset=ISO-8859-1</pre><p>The response message <em>body</em> is as follows:</p><pre>&lt;html&gt; &lt;head&gt;&lt;title&gt;Hello, World&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello, world!&lt;/h1&gt; &lt;p&gt;Request URI: /hello/sayhello&lt;/p&gt; &lt;p&gt;Protocol: HTTP/1.1&lt;/p&gt; &lt;p&gt;PathInfo: null&lt;/p&gt; &lt;p&gt;Remote Address: 0:0:0:0:0:0:0:1&lt;/p&gt; &lt;p&gt;A Random Number: &lt;strong&gt;0.4480280769255568&lt;/strong&gt;&lt;/p&gt; &lt;/body&gt;&lt;/html&gt;</pre><h4>STEP 7: Write a Database Servlet</h4><p>This section assumes that you are familiar with “Java database programming” and “MySQL database server”. Otherwise, read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/java/JDBC_Basic.html">Java Database Program</a>” and “<a href="https://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html">How to Install MySQL and Get Started</a>”.</p><p>Step 7(a) Setup a Database on MySQL (Already done in the MySQL exercises)</p><p>Start your MySQL server. Take note of the server’s port number. I shall assume that the MySQL server is running on port 3306 (whereas the Tomcat is running on port 9999).</p><pre><strong>c: cd \myWebProject\mysql\bin mysqld --console</strong></pre><p>Start a MySQL client. I shall assume that there is a user called “myuser&quot; with password &quot;xxxx&quot;.</p><pre><strong>c: cd \myWebProject\mysql\bin mysql -u myuser -p</strong> <strong>cd /usr/local/mysql/bin</strong> <strong>./mysql -u myuser -p</strong></pre><p>Run the following SQL statements to create a database called “ebookshop&quot;, with a table called &quot;books&quot; with 5 columns: id, title, author, price, qty.</p><pre>create database if not exists <strong>ebookshop</strong>; use ebookshop; drop table if exists books; create table <strong>books</strong> ( <strong>id</strong> int, <strong>title</strong> varchar(50), <strong>author</strong> varchar(50), <strong>price</strong> float, <strong>qty</strong> int, primary key (id)); insert into books values (1001, &#39;Java for dummies&#39;, &#39;Tan Ah Teck&#39;, 11.11, 11); insert into books values (1002, &#39;More Java for dummies&#39;, &#39;Tan Ah Teck&#39;, 22.22, 22); insert into books values (1003, &#39;More Java for more dummies&#39;, &#39;Mohammad Ali&#39;, 33.33, 33); insert into books values (1004, &#39;A Cup of Java&#39;, &#39;Kumar&#39;, 55.55, 55); insert into books values (1005, &#39;A Teaspoon of Java&#39;, &#39;Kevin Jones&#39;, 66.66, 66); select * from books;</pre><p>Step 7(b) Install MySQL JDBC Driver (Already done in the previous JDBC exercises)</p><p>You need to download MySQL JDBC driver if you have not done so. Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/java/JDBC_Basic.html#MySQLJDBCDriverInstall">Installing the MySQL JDBC Driver</a>”.</p><p>Step 7(c) Copy the MySQL JDBC Drive to Tomcat’s “lib” (IMPORTANT!!!)</p><p>Copy the MySQL JDBC Driver JAR file “mysql-connector-java-5.1.{xx}-bin.jar&quot; into Tomcat&#39;s lib directory, i.e., &quot;c:\myWebProject\tomcat\lib&quot; (for Windows) or &quot;~\myWebProject\tomcat\lib&quot;.</p><p>Step 7(d) Write a Client-side HTML Form</p><p>Let’s write an HTML script to create a <em>query form</em> with 3 checkboxes and a submit button, as illustrated below. Save the HTML file as “querybook.html” in your application root directory “&lt;TOMCAT_HOME&gt;\webapps\hello”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*C7fOe_Mt53YSMPJ-.png" /></figure><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15</pre><pre>&lt;html&gt; &lt;head&gt; &lt;title&gt;Yet Another Bookshop&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Yet Another Bookshop&lt;/h2&gt; &lt;form method=&quot;get&quot; <strong>action=&quot;http://localhost:9999/hello/query&quot;</strong>&gt; &lt;b&gt;Choose an author:&lt;/b&gt; &lt;input type=&quot;checkbox&quot; <strong>name=&quot;author&quot; value=&quot;Tan Ah Teck&quot;</strong>&gt;Ah Teck &lt;input type=&quot;checkbox&quot; <strong>name=&quot;author&quot; value=&quot;Mohammad Ali&quot;</strong>&gt;Ali &lt;input type=&quot;checkbox&quot; <strong>name=&quot;author&quot; value=&quot;Kumar&quot;</strong>&gt;Kumar &lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</pre><p>You can browse the HTML page by issuing the following URL:</p><pre><a href="http://localhost:9999/hello/querybook.html">http://localhost:9999/<strong>hello/querybook.html</strong></a></pre><p>Check a box (e.g., “Tan Ah Teck”) and click the “Search” button. An HTTP GET request will be issued to the URL specified in the &lt;form&gt;&#39;s &quot;action&quot; attribute. Observe the URL of the HTTP GET request:</p><pre><a href="http://localhost:9999/hello/queryauthor=Tan+Ah+Teck">http://localhost:9999/hello/query<strong>author=Tan+Ah+Teck</strong></a></pre><p>The request consists of two part: a URL corresponding to the “action&quot; attribute of the &lt;form&gt; tag, and the &quot;name=value&quot; pair extracted from the &lt;input&gt; tag, separated by a &#39;?&#39;. Take note that blanks are replaced by &#39;+&#39; (or %20), because blanks are not allowed in the URL.</p><p>If you check two boxes (e.g., “Tan Ah Teck” and “Mohammad Ali”), you will get this URL, which has two “name=value” pairs separated by an &#39;&amp;&#39;.</p><pre><a href="http://localhost:9999/hello/queryauthor=Tan+Ah+Teckauthor=Mohammad+Ali">http://localhost:9999/hello/query<strong>author=Tan+Ah+Teckauthor=Mohammad+Ali</strong></a></pre><p>You are expected to get an error “404 File Not Found”, as you have yet to write the server-side program.</p><p>Step 7(e) Write the Server-side Database Query Servlet</p><p>The next step is to write a Java servlet, which responses to the client’s request by querying the database and returns the query results.</p><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67</pre><pre>import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class <strong>QueryServlet</strong> extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); Connection conn = null; Statement stmt = null; try { Class.forName(&quot;com.mysql.jdbc.Driver&quot;); <strong>conn = DriverManager.getConnection( &quot;jdbc:mysql://localhost:3306/ebookshop?useSSL=false&quot;, &quot;myuser&quot;, &quot;xxxx&quot;);</strong> <strong>stmt = conn.createStatement();</strong> <strong>String sqlStr = &quot;select * from books where author = &quot; + &quot;&#39;&quot; + request.getParameter(&quot;author&quot;) + &quot;&#39;&quot; + &quot; and qty &gt; 0 order by price desc&quot;;</strong> out.println(&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Query Response&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&quot;); out.println(&quot;&lt;h3&gt;Thank you for your query.&lt;/h3&gt;&quot;); out.println(&quot;&lt;p&gt;You query is: &quot; + sqlStr + &quot;&lt;/p&gt;&quot;); <strong>ResultSet rset = stmt.executeQuery(sqlStr);</strong> int count = 0; while(<strong>rset.next()</strong>) { out.println(&quot;&lt;p&gt;&quot; + <strong>rset.getString(&quot;author&quot;)</strong> + &quot;, &quot; + <strong>rset.getString(&quot;title&quot;)</strong> + &quot;, $&quot; + <strong>rset.getDouble(&quot;price&quot;)</strong> + &quot;&lt;/p&gt;&quot;); count++; } out.println(&quot;&lt;p&gt;==== &quot; + count + &quot; records found =====&lt;/p&gt;&quot;); out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;); } catch (SQLException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace();</pre><pre>} finally { out.close(); try { if (stmt != null) <strong>stmt.close()</strong>; if (conn != null) <strong>conn.close()</strong>; } catch (SQLException ex) { ex.printStackTrace(); } } } }</pre><p>Compile “QueryServlet.java&quot; as follows:</p><pre><strong>c:</strong> <strong>cd \myWebProject\tomcat\webapps\hello\WEB-INF\classes</strong> <strong>javac -cp .;&quot;c:\myWebProject\tomcat\lib\servlet-api.jar&quot; QueryServlet.java</strong> <strong>cd ~/myWebProject/tomcat/webapps/hello/WEB-INF/classes</strong> <strong>javac -cp .:&quot;$HOME/myWebProject/tomcat/lib/servlet-api.jar&quot; QueryServlet.java</strong></pre><p>Verify that “QueryServlet.class&quot; generated in the &quot;classes&quot; directory.</p><p>Step 7(f) Configure the Request URL for the Servlet</p><p>Open the configuration file “web.xml&quot; of your application &quot;hello&quot; that you have created earlier for the HelloServlet, i.e., &quot;&lt;TOMCAT_HOME&gt;\webapps\hello\WEB-INF\web.xml&quot;. Add the lines that are shown in red at the LOCATIONS INDICATED.</p><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31</pre><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt; &lt;web-app version=&quot;3.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;&gt; &lt;servlet&gt; &lt;servlet-name&gt;HelloWorld&lt;/servlet-name&gt; &lt;servlet-class&gt;HelloServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;<strong>UserQuery</strong>&lt;/servlet-name&gt; &lt;servlet-class&gt;<strong>QueryServlet</strong>&lt;/servlet-class&gt; &lt;/servlet&gt;  &lt;servlet-mapping&gt; &lt;servlet-name&gt;HelloWorld&lt;/servlet-name&gt; &lt;url-pattern&gt;/sayhello&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;<strong>UserQuery</strong>&lt;/servlet-name&gt; &lt;url-pattern&gt;<strong>/query</strong>&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt;</pre><p>The above lines configure the following URL to invoke QueryServlet:</p><pre><a href="http://localhost:9999/hello/query">http://localhost:9999/hello<strong>/query</strong></a></pre><p>Step 7(g) Invoke the Servlet from the Client-Side Form</p><p>Issue the following URL to browse the HMTL form “querybook.html&quot; that you have created earlier:</p><pre><a href="http://localhost:9999/hello/querybook.html">http://localhost:9999/hello/<strong>querybook.html</strong></a></pre><p>Select an author (e.g., “Tan Ah Teck”) and click the submit button, which activates the following URL coded in the &lt;form&gt;&#39;s &quot;action&quot; attribute, together with the name=value pair:</p><pre><a href="http://localhost:9999/hello/query?author=Tan+Ah+Teck">http://localhost:9999/hello/<strong>query?author=Tan+Ah+Teck</strong></a></pre><p>This URL “/query&quot; triggers QueryServlet. The QueryServlet retrieves the name=value pair of &quot;author=Tan+Ah+Teck&quot;. Inside the QueryServlet, the method request.getParameter(&quot;author&quot;) returns &quot;Tan Ah Teck&quot;, which is inserted into the SQL SELECT command to query the database. The processed query result is then written to the client as an HTML document.</p><p>(Skip Unless…) The likely errors are “404 File Not Found” and “500 Internal Server Error”. Read “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html#TomcatDebug">How to debug</a>” Section.</p><h4>(Advanced) Deploying Servlet using @WebServlet (Servlet 3.0 on Tomcat 7)</h4><p>Servlet 3.0, which is supported by Tomcat 7, introduces the @WebServlet annotation, which greatly simplifies the deployment of servlets. You no longer need to write the deployment descriptor in &quot;web.xml&quot;. Instead, you can use the @WebServlet annotation to specify the URL mapping.</p><p>For example, let us write a new servlet called AnotherHelloServlet.java, by modifying the HelloServlet.java written earlier, with URL mapping of &quot;sayhi&quot;.</p><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36</pre><pre>import java.io.*; import javax.servlet.*; import javax.servlet.http.*; <strong>import javax.servlet.annotation.*;</strong> @WebServlet(&quot;/sayhi&quot;) public class AnotherHelloServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/html;charset=UTF-8&quot;); PrintWriter out = response.getWriter(); try { out.println(&quot;&lt;html&gt;&quot;); out.println(&quot;&lt;head&gt;&lt;title&gt;Hello, World&lt;/title&gt;&lt;/head&gt;&quot;); out.println(&quot;&lt;body&gt;&quot;); out.println(&quot;&lt;h1&gt;Hello world, again!&lt;/h1&gt;&quot;); out.println(&quot;&lt;p&gt;Request URI: &quot; + request.getRequestURI() + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;Protocol: &quot; + request.getProtocol() + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;PathInfo: &quot; + request.getPathInfo() + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;Remote Address: &quot; + request.getRemoteAddr() + &quot;&lt;/p&gt;&quot;); out.println(&quot;&lt;p&gt;A Random Number: &lt;strong&gt;&quot; + Math.random() + &quot;&lt;/strong&gt;&lt;/p&gt;&quot;); out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;); } finally { out.close(); } } }</pre><p>In Line 7, the annotation @WebServlet(&quot;/sayhi&quot;) is used to declare the URL mapping for this servlet, i.e., http://localhost:9999/hello/sayhi. There is no need to provide any more configuration in &quot;web.xml&quot;!</p><p>Notes: In Tomcat 9, you might need to remove (or rename) “web.xml&quot; for this to work?!</p><h3>How to Debug?</h3><p>“Everything that can possibly go wrong will go wrong.” The most important thing to do is to find the <strong>ERROR MESSAGE</strong>!!!</p><p>Always…</p><ol><li>Refresh your browser using <strong>Cntl-F5</strong> (instead of refresh button or simply F5) to get a fresh copy, instead of from the cache.</li><li>You may re-start your Tomcat server. You may also re-start your browser to clear the cache.</li><li>Check your spelling! Always assume that all programs are case-sensitive. Don’t type, copy and paste if possible!</li><li>and MOST IMPORTANTLY — Find the <strong>ERROR MESSAGE</strong>!!!</li><li>Check the Error Messages on Tomcat’s Console. Most of the error messages have a few screens of lines. You need to scroll up slowly from the last line to <strong>look for the FIRST LINE of the error messages</strong>.</li><li>Check the Tomcat’s log files, located at “&lt;TOMCAT_HOME&gt;\logs&quot;. The &quot;catalina.yyyy-mm-dd.log&quot; shows the Tomcat&#39;s startup messages. Also check the &quot;localhost.yyyy-mm-dd.log&quot;.</li><li>If things were running fine until the lightning strikes, ask yourself “What have I changed?”</li></ol><p>Cannot Start Tomcat — Tomcat’s Console Flashes and Disappears</p><ol><li>Try running the script “configtest.bat&quot; (for Windows) or &quot;./configtest.sh&quot; (for Mac OS/Linux) to check your configuration files.</li><li>Check the Tomcat’s log files for error messages. The log files are located at “&lt;TOMCAT_HOME&gt;\logs&quot;. The &quot;catalina.{yyyy-mm-dd}.log&quot; shows the Tomcat&#39;s startup messages. Also check the &quot;localhost.{yyyy-mm-dd}.log&quot;.</li><li>If the error messages indicate that another Tomcat instance is running (java.net.BindException: Address already in use: JVM_Bind), kill the Tomcat process (see below); or try running the &quot;shutdown&quot; script at Tomcat&#39;s bin (For Windows, simply double-click the &quot;shutdown.bat&quot; or issue &quot;shutdown&quot; from CMD. For Mac OS, issue &quot;./shutdown.sh&quot; from Terminal.)</li><li>If the error messages indicate that another application is running on the Tomcat’s port numbers, then you need to change the Tomcat’s port number in server.xml. You can issue command &quot;netstat -an&quot; to check the status of all the ports.</li><li>Start the tomcat in the debugging mode by running “catalina debug&quot; (or ./catalina.sh debug) and type &quot;run&quot; in the &quot;jdb&quot; prompt. Look for the error messages.</li></ol><p>Locating/Killing Tomcat’s Process</p><ul><li>In windows, start “Task Manager”, Tomcat run as a “process” named “java.exe&quot;. You may need to kill the process.</li><li>In Mac OS, start “Activity Monitor”. Select “All Processes” and look for “java.exe&quot;.</li><li>In Linux/Mac OS, you may issue “ps aux | grep tomcat&quot; to locate the Tomcat process. Note down the process ID (pid). You can kill the Tomcat process via &quot;kill -9 <em>pid</em>&quot;.</li></ul><p>(Firefox) Unable to Connect (IE) Internet Explorer cannot display the webpage (Chrome) Oops! Google Chrome could not connect to …</p><p>(Safari) Safari can’t connect to the server</p><p>Cause: You are simply not connecting to your Tomcat.</p><p>Solution:</p><ol><li>Check if your Tomcat server has been started?</li><li>Check the hostname and port number, separated by a colon &#39;:&#39;, of your URL (http://localhost:9999/...).</li></ol><p>Error 404 File Not Found</p><p>Cause: You have connected to your Tomcat. But Tomcat server cannot find the HTML file or Servlet that your requested.</p><p>Solution:</p><ol><li>Check your spelling! The path is case-sensitive!</li><li>For HTML file with URL <a href="http://localhost:9999/xxxx/filename.html:">http://localhost:9999/</a><a href="http://localhost:9999/xxxx/filename.html:"><em>xxxx</em></a><a href="http://localhost:9999/xxxx/filename.html:">/</a><a href="http://localhost:9999/xxxx/filename.html:"><em>filename</em></a><a href="http://localhost:9999/xxxx/filename.html:">.html:</a></li><li>Open Tomcat’s “webapps&quot; directory, check if sub-directory &quot;<em>xxxx</em>&quot; exists. It is case-sensitive.</li><li>Open the “<em>xxxx</em>&quot; directory, check if &quot;<em>filename</em>.html&quot; exists.</li><li>For Servlet with URL <a href="http://localhost:9999/xxxx/servletURL:">http://localhost:9999/</a><a href="http://localhost:9999/xxxx/servletURL:"><em>xxxx</em></a><a href="http://localhost:9999/xxxx/servletURL:">/</a><a href="http://localhost:9999/xxxx/servletURL:"><em>servletURL</em>:</a></li><li>Check the Tomcat’s console for error message. Your application cannot be deployed if you make a mistake in editing “web.xml&quot;, which triggered many error messages.</li><li>Check the Tomcat console to make sure that your application has been deployed.</li><li>Open Tomcat’s “webapps&quot; directory, check if sub-directory &quot;<em>xxxx</em>&quot; exists.</li><li>Open the “<em>xxxx</em>&quot; directory, check if sub-sub-directory &quot;WEB-INF&quot; (uppercase with a dash) exists.</li><li>Open the “WEB-INF&quot;, check if sub-sub-sub directory &quot;classes&quot; (lowercase, plural) exists.</li><li>Open the configuration file “WEB-INF\web.xml&quot;:</li><li>Check that <em>servletURL</em> is defined in a &lt;servlet-mapping&gt; tag. Take note of the <em>name</em> in &lt;servlet-name&gt; tag.</li><li>Based on the <em>name</em> noted, look for the matching &lt;servlet-class&gt; tag. Take note of the <em>ServletClassname</em>.</li><li>Open “WEB-INF\classes&quot;, check if &quot;<em>ServletClassname</em>.class&quot; that you noted exists (Note: It is &quot;.class&quot;, and NOT &quot;.java&quot;. You need to compile the &quot;.java&quot; to get the &quot;.class&quot;.)</li></ol><p>Error 500 Internal Server Error</p><p>Error 500 should have triggered many error message in the Tomcat’s console. Go to the Tomcat’s console, find the error message. The error message spans tens of lines. You need to scroll up slowly to look for the <em>first line</em> of the error message. The error message should tell you the cause of this error, e.g. SQL syntax error, wrong user/password, etc.</p><p>For database servlet, you may check the error messages at “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/ErrorMessages.html#JDBCErrors">Common Errors in JDBC Programming</a>”.</p><ul><li>For “No suitable driver found” (Windows) or NullPointerException (Mac OS and Linux): Read Step 7(b) again, again, and again.</li></ul><p>More Errors</p><p>Try searching “<a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/ErrorMessages.html">Common Error Messages</a>”.</p><p>REFERENCES &amp; RESOURCES</p><p>Latest version tested: Tomcat 9.0.4, MySQL 5.7.21, JDK 9.0.4, Windows 10, Mac OS 10.13, Ubuntu 16.04LTS<br> Last modified: February, 2018</p><p><em>Originally published at </em><a href="https://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html"><em>www.ntu.edu.sg</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f959d7ee0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Java “pass-by-reference” or “pass-by-value”?]]></title>
            <link>https://medium.com/@ngotantien/is-java-pass-by-reference-or-pass-by-value-4a11697eb24d?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a11697eb24d</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Tue, 31 Oct 2017 09:00:00 GMT</pubDate>
            <atom:updated>2017-10-31T09:00:00.756Z</atom:updated>
            <content:encoded><![CDATA[<p>I thought I’d contribute this answer to add more details from the Specifications.</p><p>First, <a href="https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value">What’s the difference between passing by reference vs. passing by value?</a></p><blockquote><em>Passing by reference means the called functions’ parameter will be the same as the callers’ passed argument (not the value, but the identity — the variable itself).</em></blockquote><blockquote><em>Pass by value means the called functions’ parameter will be a copy of the callers’ passed argument.</em></blockquote><p>Or from wikipedia, <a href="http://en.wikipedia.org/wiki/Call_by_reference#Call_by_reference">on the subject of pass-by-reference</a></p><blockquote><em>In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument — something that will be seen by its caller.</em></blockquote><p>And <a href="http://en.wikipedia.org/wiki/Call_by_value#Call_by_value">on the subject of pass-by-value</a></p><blockquote><em>In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function […]. If the function or procedure is able to assign values to its parameters, only its local copy is assigned […].</em></blockquote><p>Second, we need to know what Java uses in its method invocations. The <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1">Java Language Specification</a> states</p><blockquote><em>When the method or constructor is invoked (§15.12), </em><strong><em>the values of the actual argument expressions initialize newly created parameter variables</em></strong><em>, each of the declared type, before execution of the body of the method or constructor.</em></blockquote><p>So it assigns (or binds) the value of the argument to the corresponding parameter variable.</p><p><strong>What is the value of the argument?</strong></p><p>Let’s consider reference types, the <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.4">Java Virtual Machine Specification</a> states</p><blockquote><em>There are three kinds of </em><strong><em>reference types</em></strong><em>: class types, array types, and interface types. </em><strong><em>Their values are references to dynamically created class instances, arrays, or class instances or arrays that implement interfaces, respectively.</em></strong></blockquote><p>The <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1">Java Language Specification</a> also states</p><blockquote><strong><em>The reference values (often just references) are pointers to these objects</em></strong><em>, and a special null reference, which refers to no object.</em></blockquote><p>The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.</p><p>So</p><pre>public void method (String param) {} ... String var = new String(&quot;ref&quot;); method(var); method(var.toString()); method(new String(&quot;ref&quot;));</pre><p>all bind the value of a reference to a String instance to the method&#39;s newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, <strong>Java is pass-by-value</strong>.</p><p><strong>The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation.</strong> The definition of pass-by-reference was</p><blockquote><em>This typically means that the function can modify (i.e. assign to) the variable used as argument — something that will be seen by its caller.</em></blockquote><p>In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. <strong>Modifying the object referenced by the variable is a different concept entirely.</strong></p><p>Primitive values are also defined in the Java Virtual Machine Specification, <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3">here</a>. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).</p><p><em>Originally published at </em><a href="https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value"><em>stackoverflow.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a11697eb24d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android : Passing data between main thread and worker threads.]]></title>
            <link>https://medium.com/@ngotantien/android-passing-data-between-main-thread-and-worker-threads-35f2635ce65e?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f2635ce65e</guid>
            <category><![CDATA[multithread]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[passing-data]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Fri, 27 Oct 2017 10:12:34 GMT</pubDate>
            <atom:updated>2017-10-27T10:13:09.895Z</atom:updated>
            <content:encoded><![CDATA[<p>There may be situations where you want to spawn a thread from your Activity or Service to handle long running (and may be blocking) tasks. In such cases, its sometimes necessary to pass data back and forth between the main thread and the worker thread(s). E.g. if the worker thread finishes a task and returns the result to the main activity to display the results OR you want to keep a worker thread around and ask it to switch between tasks depending on some message you pass to it. In the past, I faced some problems understanding these concepts associated with different classes in android.os like the Handler, Looper, HandlerThread etc… I’ll try to explain these concepts in a simple language. Probably most of these explanations are from the developer documentation, but I thought consolidating these at one place may help to get a good picture. Ok. So, when an application runs, it runs in a Main thread called as the UI thread. Any other thread can be created using the standard java.lang.Thread class. As I said in a typical situation you will spawn a thread, may be pass some data to it OR the thread may pass back some data to the Main thread from time to time as well as when its done executing. Let us consider the task where we need to send data to a worker thread. So first, we create a worker thread.</p><p><strong>STEP 1: Create a worker thread</strong></p><p>class MyThread extends Thread {</p><p>@Override<br> public void run(){<br> }<br> } In our main thread…</p><p>MyThread mThread = new MyThread();</p><p>mThread.start();</p><p><strong>When you have to pass any messages to a thread or get messages from a thread, the <em>receiving</em> thread needs a MessageQueue.</strong> By default, a thread created by using the java.lang.Thread class will not have a MessageQueue associated with it. Its just a plain old thread as in the Fig. 1 (Yes, I know. What an innovative diagram !! :D ).</p><p>Now, we need to attach a MessageQueue to our thread. The <a href="http://developer.android.com/reference/android/os/Looper.html">Looper</a> class provides the method prepare() to create a message queue for a thread. We need to call this method from the <em>receiving</em> thread’s run method.</p><p><strong>STEP 2: Call the Looper methods</strong></p><p>class MyThread extends Thread {</p><p>@Override</p><p>public void run(){</p><p>Looper.prepare();</p><p>}</p><p>As you see, there is one more Looper method called in the code. This loop() method will start running the message loop for the current thread. In simple terms, it will start looking at the MessageQueue and processing the messages. This is how I interpret the Looper as in Fig. 2.</p><p>But, who sends the messages to the MessageQueue and how are these processed ? There is a class called the <a href="http://developer.android.com/reference/android/os/Handler.html">Handler</a>. The Hander allows us to send and process <a href="http://developer.android.com/reference/android/os/Message.html">Message</a>s (as well as Runnable Objects) associated with the thread’s MessageQueue. So, we need to create a Handler. <strong>It is important to note that the Handler is associated with the thread that creates it ! </strong>The Handler provides methods to handle (receive) Messages as well as send and schedule messages. For details, please refer to <a href="http://developer.android.com/reference/android/os/Handler.html">documentation</a>.</p><p><strong>STEP 3: Create a Handler to receive the Messages</strong></p><p>class MyThread extends Thread {</p><p>public Handler mHandler;</p><p>@Override</p><p>public void run(){</p><p>Looper.prepare();</p><p>mHandler = new Handler() {</p><p>public void handleMessage(Message msg) {</p><p>// Act on the message</p><p>}</p><p>};</p><p>Looper.loop();</p><p>}</p><p>}</p><p>If you notice, this code is the same that is listed on the Looper documentation page <a href="http://developer.android.com/reference/android/os/Looper.html">here</a>. Few things to mention here are. The Handler is created in this thread, hence it is associated with the default Looper (read MessageQueue) in the current thread. There are constructors for the Handler that allow us to specify the Looper (again, read MessageQueue). This allows us to write a cleaner code by writing the Handler class separately and passing on a Looper (again, again, read MessageQueue) when the Handler is created. I’ll get to this in a while. But as I have insisted, it is worth noting that whenever the developer documentation refers to a Looper, you can assume they are talking about a queue. I’m really not sure why they have surfaced the Looper class. It creates more confusion (at least for me). Also, when dealing with passing the messages, with this mechanism, we really need not care of the MessageQueue call. That is the reason I haven’t linked it to the documentation. Anyways… things are what they are ! For me, I like to interpret this whole mechanism as depicted in Fig. 3.</p><p>Let me know if you like PAT or your way of viewing it !</p><p>So, now any other thread having the reference to mHandler will be able to call the send or post methods of the Handler class to send a Message (or a runnable object) to our thread. The code for sending message will look like:</p><p>Message msg = Message.obtain();</p><p>msg.obj = // Some Arbitrary object</p><p>mHandler.sendMessage(msg);</p><p>Pretty simple yeah ! Btw, there are various methods to set/get data for the Message object which can be found in the developer documentation for the Message class.</p><p><strong>Summary of Steps :</strong></p><p>1. Create a Handler in the receiving thread [If it is the main thread, create one in the main thread]. By default the handler will be associated with the default queue (Looper).</p><p>2. So, if the receiving thread is created by using java.lang.Thread, then we need to call the Looper.prepare() and Looper.loop() in order to set up the message queue for the thread.</p><p>3. In the sending thread, prepare a message object (or a Runnable object)</p><p>4. Get a reference to the Handler in the sending thread and call the send/post methods on it to send a message.</p><p><strong>HandlerThread</strong>:</p><p>Since by default java.lang.Thread doesn’t contain a message queue (Looper), Android provides a class called as the HandlerThread which already contains a message queue. The only difference in using the HandlerThread class over the method described above is that you need not call the Looper.* methods.</p><p>On creation of a HandlerThread, Android will create a thread containing the looper. So, in the main thread the code will look like:</p><p>HandlerThread myThread = new HandlerThread(“Worker Thread”);</p><p>myThread.start();</p><p>We separately create a Handler as follows:</p><p>class MyHandler extends Handler {</p><p>public MyHandler(Looper myLooper) {</p><p>super(myLooper); }</p><p>public void handleMessage(Message msg) {</p><p>}<br> }</p><p>Now in the main thread, we get the looper for the HandlerThread and pass it when we create the Handler as follows:</p><p>Looper mLooper = myThread.getLooper();</p><p>MyHandler mHandler = new MyHandler(mLooper);</p><p>Whenever we want to send a message from the main thread, we do it in a similar fashion.</p><p>Message msg = mHandler.obtainMessage();</p><p>msg.obj = // Some Arbitrary object</p><p>mHandler.sendMessage(msg);</p><p>I like to visualize this as shown below in Fig. 4 where we write the Handler separately and then pass a looper to it on its creation.</p><p><em>Originally published at </em><a href="http://techtej.blogspot.com/2011/02/android-passing-data-between-main.html"><em>techtej.blogspot.com</em></a><em> on October 27, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f2635ce65e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[notifyDataSetChanged example]]></title>
            <link>https://medium.com/@ngotantien/notifydatasetchanged-example-315a95326d50?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/315a95326d50</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Fri, 06 Oct 2017 08:44:44 GMT</pubDate>
            <atom:updated>2017-10-06T08:44:44.622Z</atom:updated>
            <content:encoded><![CDATA[<p>I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged() in the right place.</p><p>So my situation was as follows.</p><p>I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged() of the action bar adapter in the code of the activity which had to return the data.</p><p>This is the code snippet which I used in the activity.</p><pre>@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_new_forward: FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab Intent ina = new Intent(getApplicationContext(), MainActivity.class); ina.putExtra(&quot;stra&quot;, values1); startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment). } }</pre><p>This activity would return some data to FragmentTab2 and it would directly update my listview in FragmentTab2.</p><p>Hope someone finds this useful!</p><p><em>Originally published at </em><a href="https://stackoverflow.com/questions/3669325/notifydatasetchanged-example"><em>stackoverflow.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315a95326d50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is it wrong to use Deprecated methods or classes in Java?]]></title>
            <link>https://medium.com/@ngotantien/is-it-wrong-to-use-deprecated-methods-or-classes-in-java-9c9ef9b2d9ae?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c9ef9b2d9ae</guid>
            <category><![CDATA[java-deprecated-method]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Thu, 05 Oct 2017 02:24:10 GMT</pubDate>
            <atom:updated>2017-10-05T02:24:36.380Z</atom:updated>
            <content:encoded><![CDATA[<p>From the official Sun glossary:</p><blockquote><strong><em>deprecation</em></strong><em>: Refers to a class, interface, constructor, method or field that is no longer recommended, and may cease to exist in a future version.</em></blockquote><p>From the how-and-when to deprecate guide:</p><blockquote><em>You may have heard the term, “self-deprecating humor,” or humor that minimizes the speaker’s importance. A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future.</em></blockquote><p>The @Deprecated annotation went a step further and warn of danger:</p><blockquote><em>A program element annotated </em><em>@Deprecated is one that programmers are discouraged from using, typically because it is </em>dangerous<em>, or because a better alternative exists.</em></blockquote><h3>References</h3><h3>Right or wrong?</h3><p>The question of whether it’s right or wrong to use deprecated methods will have to be examined on individual basis. Here are <strong>ALL</strong> the quotes where the word <em>“deprecated”</em> appears in <em>Effective Java 2nd Edition</em>:</p><blockquote><strong><em>Item 7: Avoid finalizers</em></strong><em>: The only methods that claim to guarantee finalization are </em><em>System.runFinalizersOnExit and its evil twin </em><em>Runtime.runFinalizersOnExit. These methods are fatally flawed and have been deprecated.</em></blockquote><blockquote><strong><em>Item 66: Synchronize access to shared mutable data</em></strong><em>: The libraries provide the </em><em>Thread.stop method, but this method was deprecated long ago because it&#39;s inherently </em>unsafe<em> -- its use can result in data corruption.</em></blockquote><blockquote><strong><em>Item 70: Document thread safety</em></strong><em>: The </em><em>System.runFinalizersOnExit method is thread-hostile and has been deprecated.</em></blockquote><blockquote><strong><em>Item 73: Avoid thread groups</em></strong><em>: They allow you to apply certain </em><em>Thread primitives to a bunch of threads at once. Several of these primitives have been deprecated, and the remainder are infrequently used. [...] thread groups are obsolete.</em></blockquote><p>So at least with all of the above methods, it’s clearly wrong to use them, at least according to Josh Bloch.</p><p>With other methods, you’d have to consider the issues individually, and understand <strong>WHY</strong> they were deprecated, but generally speaking, when the decision to deprecate is justified, it will tend to lean toward wrong than right to continue using them.</p><h3>Related questions</h3><ul><li><a href="https://stackoverflow.com/questions/2873254/difference-between-a-deprecated-and-legacy-api/">Difference between a Deprecated and Legacy API?</a></li></ul><p><em>Originally published at </em><a href="https://stackoverflow.com/questions/2941900/is-it-wrong-to-use-deprecated-methods-or-classes-in-java"><em>stackoverflow.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c9ef9b2d9ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android target sdk vs deprecated methods]]></title>
            <link>https://medium.com/@ngotantien/android-target-sdk-vs-deprecated-methods-8617d2dafa79?source=rss-352e0ff5b8b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8617d2dafa79</guid>
            <dc:creator><![CDATA[Tien Tan]]></dc:creator>
            <pubDate>Thu, 05 Oct 2017 01:58:55 GMT</pubDate>
            <atom:updated>2017-10-05T01:58:55.168Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>However, if you have compileSDK higher eg 23, then Android Studio will tell you, the code above is deprecated (and moreover removed from SDK i guess).</em></blockquote><p>No. getActionBar() <a href="http://developer.android.com/reference/android/app/Activity.html#getActionBar%28%29">is not deprecated</a>. setNavigationMode() is <a href="http://developer.android.com/reference/android/app/ActionBar.html#setNavigationMode%28int%29">deprecated but not removed</a>.</p><blockquote><em>What happens, if i compile my project with compileSDK version and targetSDK version eg 20 (where is not problem with deprecated) and will try run it on Android with SDK eg 21 or 23 where are these functions from SDK obviously removed? Will app crash or work?</em></blockquote><p>The app should work fine. “Deprecated” means “we think that there is a better solution and we would prefer that you use it”.</p><blockquote><em>What happens, if i decide to target the “high” SDK that means eg 23, i will leave the “old” code mentioned above and will use some “new” code for tabs, which appeared eg in SDK 23 or so (that means didn’t exist in lower SDK) and i will try run the application on Android with lower SDK, eg 20? Will app crash or work?</em></blockquote><p>First, I am not aware of any “‘new’ code for tabs, which appeared eg in SDK 23”. The Design Support library has the only new tab implementation that I can think of, and it works back to API Level 7.</p><p>Second, your app should fail to compile, if you are trying to use something that is newer than your minSdkVersion without adequate checks (e.g., using Build.VERSION.SDK_INT and bypassing that code on older devices).</p><p>In the end, if you refer to a class, method, field, interface, and so on that does not exist on the older API level, your app will crash if and when that code gets executed. A typical error is VerifyError, though it depends a bit on the nature of what it is that you are trying to use that does not exist.</p><p>With respect to tabs, there are countless implementations available to you. Most come in the form of <a href="http://android-arsenal.com/tag/111">third-party libraries tied to </a><a href="http://android-arsenal.com/tag/111">ViewPager</a>. In terms of the Android SDK, there the aforementioned TabLayout from the Design Support library, FragmentTabHost, and PagerTabStrip (though <a href="https://stackoverflow.com/questions/32379050/issue-with-pagertitlestrip-and-pagertabstrip-with-support-v4-version-23-0-0">the latter has a bug in the 23.0.0 edition of the </a><a href="https://stackoverflow.com/questions/32379050/issue-with-pagertitlestrip-and-pagertabstrip-with-support-v4-version-23-0-0">support-v4 library, apparently</a>).</p><p><em>Originally published at </em><a href="https://stackoverflow.com/questions/32384485/android-target-sdk-vs-deprecated-methods"><em>stackoverflow.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8617d2dafa79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>