Introduction to Android Espresso

Espresso is a testing framework that exposes a simple API to perform UI testing of android apps. With the latest 2.0 release, Espresso is now part of the Android Support Repository which makes it more easier to add automated testing support for your project.

But before jumping into Espresso API, lets consider what puts it apart from the other testing frameworks.

  • One of the first things you’ll notice about Espresso, is that its code looks a lot like English, which makes it predictable and easy to learn.
  • The API is relatively small, and yet open for customization.
  • Espresso tests run optimally fast (no waits, sleeps)
  • Gradle + Android Studio support

Adding Espresso to your project

1. First of all make sure you have Android Support Repository installed

android sdk manager

2. Add the following dependencies to your application build.gradle file

dependencies {
   androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
   androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
}

3. Finally, specify the test instrumentation runner in default config

android {

    defaultConfig {
        // ....
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

And that is basically what it takes “to invite your project to a cup of Espresso”!

The main components of Espresso

Espresso is built up from 3 major components.

These components are:

  • ViewMatchers – allows you to locate a view in the current view hierarchy
  • ViewActions – allows you to interact with views
  • ViewAssertions – allows you to assert the state of a view.

For simplicity, you may use these shortcuts to refer to them:

  • ViewMatchers – “find something
  • ViewActions – “do something
  • ViewAssertions – “check something

And, for example when you will need to check something (like, is some text displayed on the screen?), you’ll know you’ll need a ViewAssertion for that.

Below is an example of a test in Espresso, and where the main components find their place.

Android Espresso main components

A simple test using onView()

Suppose we have an app where the user is asked to enter his name.
After he enters the name, he taps on the “Next” button and is redirected to another activity where a greeting message is displayed.

espresso simple test

If we would write a test for this scenario, then it might look something like this:

// locate the view with id "user_name" and type the text "John"
onView(withId(R.id.user_name)).perform(typeText("John"));

// locate the view with id "next" and click on it
onView(withId(R.id.next)).perform(click());

// locate the view with id "greeting_message" and check its text is equal with "Hello John!"
onView(withId(R.id.greeting_message)).check(matches(withText("Hello John!")));

Notice that we don’t specify explicitly what kind of view we are interacting with (eg.: EditText, Button), we simply say that we are looking for a view with a specific id.
Also, when clicking on the “Next” button and later checking the text, we don’t have to write some special code to tell Espresso that we have navigated to another activity.

Now, if we want to actually run this test, then it should be put in a class. In Gradle, the location where tests are stored is: yourApp/src/androidTest/java.

This is an example of a test class, and its main characteristics:

Espresso example test class

A simple test using onData()

Whenever you have a ListView, GridView, Spinner, and other Adapter based views, you’ll have to use onData() in order to interact with an item from that list.
onData() is targeting directly the data provided by your adapter. What does this mean, we will see in a moment.

In a hypothetical application we are asked to select a country from a Spinner, once selected, the country is displayed next to the Spinner.

espresso on data

A test to check that the displayed country is equal with what was selected, might look like this:

// locate the view with id "country_spinner" and click on it
onView(withId(R.id.country_spinner)).perform(click());

// match an item that is a String and is equal with whatever value the COUNTRY constant is initialized, then click on it.
onData(allOf(is(instanceOf(String.class)), is(COUNTRY))).perform(click());

// locate the view with id "selected_country" and check its text is equal with COUNTRY
onView(withId(R.id.selected_country)).check(matches(withText("selected: " + COUNTRY)));

The Spinner you saw in the example above is backed by a simple array of strings, and because of this, we specify that we are looking for an item of type String. If, instead of a String, it were some custom object, then we would specify that instead.
To illustrate, consider the following example where a list of books is displayed:

books-adapter

Since the items in the adapter are of type Book, so will look the query:

onData(allOf(is(instanceOf(Book.class)), withBookTitle(BOOK_TITLE))).perform(click());

DataInteractions

Espresso has a few useful methods that can be used to interact with data.

atPosition() – Might be useful when the element to interact with is not relevant, or when the items always appear in a specific order, so you know every item on what position sits.

onData(...).atPosition(2).perform(click());

inRoot() – Use inRoot() to target non-default windows. One scenario where this can be used is when testing autocomplete. The list that appears in the autocomplete view belongs to a window that is drawn on top of application window.
In this case you have to specify that the data you are looking for, is not in the main window.

onView(withText("AutoCompleteText"))
        .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
        .check(matches(isDisplayed()));

onChildView() – This DataInteraction allows to further refine the query by letting you interact with a specific view from a list row.
Let say that you have a list of items and every item has a delete button. You want to click on Delete button of a specific item:

onData(withBookTitle("My Book"))
      .onChildView(withId(R.id.book_delete)).perform(click());

inAdapterView() – This allows to select a particular adapter view to operate on, by default Espresso operates on any adapter view.
You may find this useful when dealing with ViewPagers and Fragments, and you want to interact with the AdapterView that is currently displayed, or when you have more than one adapter view in your activity.

onData(withBookTitle("My Book"))
      .inAdapterView(allOf(isAssignableFrom(AdapterView.class), isDisplayed()))
      .perform(click());

Espresso and RecyclerView

RecyclerView is an UI component designed to render a collection of data just like ListView and GridView, actually, it is intended to be a replacement of these two. What interests us from a testing point of view, is that a RecyclerView is no longer an AdapterView. This means that you can not use onData() to interact with list items.

Fortunately, there is a class called RecyclerViewActions that exposes a small API to operate on a RecyclerView. RecyclerViewActions is part of a separate lib called espresso-contrib, that also should be added to build.gradle:

dependencies {
    // ...

    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.0');
}

Since your project already includes a dependency to recyclerview, and might as well include support libs, some dependencies conflicts might appear. In this case exclude
them from espresso-contrib like this:

dependencies {
    // ...

    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.0') {
        exclude group: 'com.android.support', module: 'appcompat'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude module: 'recyclerview-v7'
    }
}

Here is how to click on an item from the list by position:

onView(withId(R.id.recyclerView))
      .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));

Or how to perform a click on a View from an item:

onView(withId(R.id.recyclerView))
      .perform(RecyclerViewActions.actionOnItem(
                hasDescendant(withText(BOOK_TITLE)), click()));

More Espresso Examples on Github:
https://github.com/vgrec/EspressoExamples

Advertisement

Introducing SectionedActionBarList

This Android library allows you to replace the drop down navigation list with a custom list where the items in the list are grouped by sections. It was inspired from the Google I/O 2014 app how sessions are grouped in the ActionBar list.

While the new Material Design movement discourages the use of ActionBar lists, in some situations it can be the best available option.

At the moment the library is not available on a repository, you have to include it as a source library in your project, but that will be fixed soon.

Github project page: https://github.com/vgrec/SectionedActionBarList

Example
List
<Section> sections = new ArrayList
<Section>();
 
Section themes = new Section("Themes");
themes.add("Design");
themes.add("Develop");
themes.add("Distribute");
sections.add(themes);
 
Section topics = new Section("Topics");
topics.add("Android");
topics.add("Chrome / Web");
topics.add("Cloud Services");
topics.add("Media");
topics.add("Location");
topics.add("Performance");
sections.add(topics);
 
Section types = new Section("Types");
types.add("Sessions");
types.add("App Reviews");
types.add("Box Talks");
sections.add(topics);
 
SectionedActionBarList actionBarList = new SectionedActionBarList(this).from(sections);
actionBarList.setItemSelectedListener(new ItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position, long id, String sectionName, String itemName) {
      Toast.makeText(MainActivity.this, "Section: " + sectionName + ", Item: " + itemName, Toast.LENGTH_LONG).show();
  }
});

The SectionedActionBarList accepts a list of sections List<Section> sections, and every Section has a name and some associated items.

sectioned actionbar list

Configuration

Small customizations can be done to fit with your application design:

ListConfiguration configuration = new ListConfiguration(this);
configuration.setActionBarItemColorResource(R.color.brown);
configuration.setIndicatorDrawableResource(R.drawable.spinner_indicator_dark);
configuration.setSectionTitleColorResource(R.color.teal);
configuration.setDropdownItemColorResources(R.color.light_blue, R.color.dark_grey);

SectionedActionBarSpinner actionBarSpinner = new SectionedActionBarSpinner(this, configuration).from(sections);
// ....

actionbar list

Thanks to Webucator, a provider of Android classes, for producing the below video illustrating the integration of the SectionedActionbarList.


Analysing Android code with SonarQube

sonar analysis

SonarQube, formerly known as Sonar, is a platform to analyze code quality. Analysis covers such aspects as code duplications, potential bugs, coding rules, complexity, unit tests, comments, and architecture & design.
It supports supports more than 20 programming languages and has a reach set of useful plugins that gives you the opportunity to inspect different aspects of the code.

What is caracteristic about SonarQube is that it comes as a platform in the form of a web application. This means that the results of the analysis will be displayed in a web page.

Installing SonarQube

The installation is pretty straightforward, you have just to download an archive and extract it in a folder of your choice.
1. Go to http://www.sonarqube.org/downloads/ and download the latest release.
2. Unzip the archive

Starting SonarQube

1. Go to sonarqube-4.3/bin (or whatever version you downloaded)
2. Open a corresponding folder according to your operating system (linux-x86-64 in my case). There you should see a file called sonar.sh (or StartSonar.bat for Windows)
3. Open up a terminal window and execute: sonar.sh start (or just double click StartSonar.bat on windows). This command will start sonar listening on localhost:9000.
4. Open a browser and enter localhost:9000. The sonar web page should open.
Note that it may take some time until sonar loads, so if you get “page not found” in your browser, try to refresh the page later.

Installing SonarQube Runner

There are several ways to analyse the source code and in this tutorial we will choose to analyse with SonarQube Runner, recommended as the default launcher to analyze a project.

1. Once again go to http://www.sonarqube.org/downloads/ and download SonarQube Runner
2. Extract the downloaded archive into a directory of your choise, which we will refer as: <install_directory>
3. Update global settings by editing: <install_directory>/conf/sonar-runner.properties (if you are running sonar on localhost, like in this tutorial, you don’t have to modify any settings):

#----- Default SonarQube server
#sonar.host.url=http://localhost:9000

#----- PostgreSQL
#sonar.jdbc.url=jdbc:postgresql://localhost/sonar

#----- MySQL
#sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8

#----- Oracle
#sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE

#----- Oracle
#sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE

#----- Microsoft SQLServer
#sonar.jdbc.url=jdbc:jtds:sqlserver://localhost/sonar;SelectMethod=Cursor

#----- Global database settings
#sonar.jdbc.username=sonar
#sonar.jdbc.password=sonar

4. Create a new SONAR_RUNNER_HOME environment variable set to <install_directory>, so that you could invoke sonar runner from any location.
5. Add the <install_directory>/bin directory to your path.

To check that sonar runner was installed properly, open a terminal window and execute sonar-runner -h.

You should get a message like this:

usage: sonar-runner [options]

Options:
-D,--define Define property
-e,--errors Produce execution error messages
-h,--help Display help information
-v,--version Display version information
-X,--debug Produce execution debug output

Analysing source code of a project

Once the sonar runner is properly installed, we can proceed to code analysis.

1. Navigate to the root directory of your project and create a file called sonar-project.properties, which will specify the project settings such as the code source directory, language used, and the project name:

sonar.projectKey=myproject
sonar.projectName=My Project
sonar.projectVersion=1.0

sonar.sources=src
sonar.language=java
sonar.sourceEncoding=UTF-8

Note: for Android Studio, which follows the gradle directory structure, set the sourses as:

sonar.sources=src/main/java

2. Run sonar-runner command to start the analysis.
3. Once the analysis complets, head to localhost:9000 to see the results for your project.

Removing a project from SonarQube

First login as an administrator, admin/admin default username and password.

1. Go to your project dashboard
2. In the top right corner click on Configuration -> Deletion -> Delete Project

delete-shonar-project

Introducing Photo Collage Creator

I was playing with bitmap manipulations and so was born the idea to make this app. It was started some time ago, and, even if at times I was thinking it will never see the daylight, finally it was released!

Description of the app:
Photo Collage Creator is a simple app that lets you create beautiful collages within seconds and share them with your family, friends or colleagues. To create a collage you just need to select the photos, apply the frames, save, and you are done!

Features:
– Create collages composed from up to 5 photos
– Various frames to create a collage
– Shuffle the photos within the collage
– Save your collages
– Share collages on gmail, facebook, picasa, and other social networking sites.

Hope you will like it!

collage maker

photo collage creator android

application on android market

Google Maps API V2 Android Tutorial

In this tutorial we will walk through the process of integrating Google Maps API V2 into an Android project.

(Source code available on GitHub)

Android Google Maps API V2

The necessary steps in order to integrate the Google Maps V2 are :

1. Install Google Play services

The version 2 of Google Maps now is part of the Google Play services SDK, that is why google-play-services lib should be installed first.

Start the Android SDK Manager and choose to install Google Play services from the Extras category:
android sdk manager

After the sdk manager completes the installation, go to <android_sdk_folder>/extras/google/google_play_services/libproject and copy the google-play-services_lib to the location where you maintain your Android projects.

Then import the library project into your workspace, and reference it in your Android project.

2. Get the Google Maps API Key

In order to use Google Maps API in your project you need a valid Google Maps API key. The key can be obtained via the Google APIs Console. You will have to provide the SHA-1 fingerprint and the package name of your application.

Please note that if you already hold a map key from the Google Maps Android V1, also known as MapView, you still will need get a new API key, as the old key won’t work with the V2 API.

2.1 Generate SHA-1 certificate fingerprint

To display the SHA-1 fingerprint, first you need to decide for what type of certificate do you need to generate the fingerprint: for the debug certificate, or for the release certificate.
In this example we well consider displaying the fingerprint for the debug certificate.

The file name of debug certificate is called debug.keystore, and it is located on C:\Users\your_user_name\.android\ on Windows, and on ~/.android/ on Linux.

If you are on a Linux, open the terminal and run the following command:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

If you are on a Windows, open the command prompt and run this:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Copy the SHA1 fingerprint and store it somewhere for later use.
android sha1 certificate fingerprint

(Note that if the command prompt complains that keytool is not a recognizable command, you can find it your java JDK/bin folder. cd there and run the command from that folder.)

2.2 Create an API Project

Navigate to Google APIs Console and create a new project, if you haven’t used Google APIs Console before. Then click on the Services link from the left menu:
google services

and from the presented list of of services toggle Google Maps Android API V2:
google maps android api v2

(Please make sure you namely select “Google Maps Android API V2”, not Google Maps API v2, nor Google Maps API v3)

2.3 Obtain an API Key

a) From the left menu click on API Access
b) Then click on Create New Android Key
c) In the resulting dialog, enter the SHA-1 fingerprint, followed by a semicolon, and then your application package name.
For example:
95:F7:64:E9:3D:D44:70:EF:CB:F9:D9:14:BF:72:88:B4:E8:D7:11:E9;com.example.mapsv2

As a result the page displays a new section entitled Key for Android apps (with certificates), followed by your API key that looks something like this:
AIzaZyAcQKLEyHsamGpNLHdn8wd5-wuCqBnJ3Rk

2.4 Add the API key to AndroidManifest file

Open the AndroidManifest file and add the following element as a child of application tag:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="YOUR_API_KEY"/>

replacing the YOUR_API_KEY with your real API key.

3. Update the AndroidManifest file with other settings

In order to use Google Maps Android API we need to declare a few permissions and specify that the application requires OpenGL ES version 2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    //... >

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    //...
</manifest>
4. Display a MapFragment

Displaying the maps is as simple as declaring a fragment in the xml layout with the name com.google.android.gms.maps.MapFragment.
If you would like to make your application compatible with older devices, then you’ll have to use the Android Support Library and reference SupportMapFragment instead of MapFragment. The below example uses the Android Support Library.

The activity_main.xml layout:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/maps_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

and the MainActivity.java:

public class MainActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

If everything was configured correctly, then when running this example you should see a map.

Full source code can be downloaded from GitHub: https://github.com/vgrec/MapsV2Example

Example using ViewPager with ActionBarSherlock tabs

In this post I’m going to show you an example usage of ViewPager in conjunction with ActionBarSherlock tabs.
The final result should look like this:

ActionBar with ViewPager

1. Add the ActionBarSherlock library to your project. (Here’s a short tutorial on how to integrate ABS with a project, in case you need a refresh on this)

2. Change the AndroidManifest file of your project to use one of the predefined themes by ABS:

<application       
        //....
        android:theme="@style/Theme.Sherlock.Light" >
        //.....
</application>

Note that using ActionBarSherlock requires you to use one of these themes: Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or any other derivate, otherwise a RuntimeException exception will be thrown.

3. Create the MainActivity.java:

public class MainActivity extends SherlockFragmentActivity {

	private ActionBar actionBar;
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setOnPageChangeListener(onPageChangeListener);
		viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
		addActionBarTabs();
	}

	private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
		@Override
		public void onPageSelected(int position) {
			super.onPageSelected(position);
			actionBar.setSelectedNavigationItem(position);
		}
	};

	private void addActionBarTabs() {
		actionBar = getSupportActionBar();
		String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
		for (String tabTitle : tabs) {
			ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
					.setTabListener(tabListener);
			actionBar.addTab(tab);
		}
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	}

	private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
		@Override
		public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
			viewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
		}

		@Override
		public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
		}
	};
}

Another requirement in order to use Sherlock library is that your activity should extend from SherlockFragmentActivity, and this is what MainActivity does first.
Then it takes a reference to the ViewPager and sets the OnPageChangedListener and the PagerAdapter (implementation will be shown below):

viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

In short, a ViewPager is a layout manager that allows you to swipe left and right through pages of data.
It needs to be supplied with an implementation of PagerAdapter in order to generate the pages that the view shows.

Just below the initialization of ViewPager the action bar tabs are added:

private void addActionBarTabs() {
	actionBar = getSupportActionBar();
	String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
	for (String tabTitle : tabs) {
		ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
				.setTabListener(tabListener);
		actionBar.addTab(tab);
	}
	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}

For every string in the tabs[] array a new ActionBar.Tab is created and added to the ActionBar.

4. And the layout of MainActivity, R.layout.activity_main, which simply defines the ViewPager container.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

5. The implementation of ViewPagerAdapter.java:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private final int PAGES = 3;

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new TabFragment1();
            case 1:
                return new TabFragment2();
            case 2:
                return new TabFragment3();
            default:
                throw new IllegalArgumentException("The item position should be less or equal to:" + PAGES);
        }
    }

    @Override
    public int getCount() {
        return PAGES;
    }
}

The PagerAdapter helps represent each page as a Fragment.
By extending FragmentStatePagerAdapter two methods should be overrided:
getCount() – which returns the total number of pages the ViewPager will have, and
getItem() – which returns a new fragment for each page.

6. Bellow follows the fragment classes used for representing each page. The minimalistic implementation is to extend from SherlockFragment, and provide a view for the fragment itself.
TabFragment1.java:

public class TabFragment1 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_1, container, false);
	}
}

TabFragment2.java:

public class TabFragment2 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_2, container, false);
	}
}

TabFragment3.java:

public class TabFragment3 extends SherlockFragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_3, container, false);
	}
}

7. And their corresponding layout files, which in this particular example have just a single TextView element.
fragment_tab_1.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 1" />

</RelativeLayout>

fragment_tab_2.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 2" />

</RelativeLayout>

fragment_tab_3.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 3" />

</RelativeLayout>

Full project can be found on github: https://github.com/vgrec/SherlockActionBarTabs

Using Maven to save the build time in a properties file

Create a folder called build in the root directory of the project, and a file build.properties with the following content:

build.time=@buildtime@

Using the maven replacer plugin we can replace the token @buildtime@ within the build.properties file with the build timestamp value, and then let the Android application read that value and use it.

 
<plugins>
     <plugin>
         <groupId>com.google.code.maven-replacer-plugin</groupId>
         <artifactId>replacer</artifactId>
         <version>1.5.2</version>
         <executions>
            <execution>
               <phase>validate</phase>
               <goals>
                  <goal>replace</goal>
               </goals>
            </execution>
         </executions>
         <configuration>
            <file>build/build.properties</file>
               <outputFile>res/raw/build.properties</outputFile>
               <replacements>
                  <replacement>
                     <token>@buildtime@</token>
                     <value>${maven.build.timestamp}</value>
                  </replacement>
               </replacements>
        </configuration>
   </plugin>
</plugin>

Run this task with mvn validate command. This will do nothing but replace the tokens from build.properties file with the timestamp value, and output the result to a new file in res/raw.

From here on the file can be accessed as a raw resource and read as a regular properties file.

Reading the properties file:

InputStream rawResource = resources.openRawResource(R.raw.build);
Properties properties = new Properties();
properties.load(rawResource);
String buildTime = properties.getProperty("build.time");

Using Maven in Android to build for different environments (dev, staging, prod, etc)

If you are working on a relatively complex project, chances are that you may need to build the application against different environments, such as a development, a staging, and a production environment. Assuming you are using Maven as a build tool, here’s one solution how Maven could help with this.

For the sake of this example let assume that you are working on an Android app that consumes web services. You have a dedicated development environment where you spent most of the time, but once every two weeks you need to make a version of the app that is built for production.

Let assume that the endpoint for the testing environment is dev.mysite.com, and for the production environment is: prod.mysite.com.
But as an aspiring developer and after reading a bunch of books about best practices, you can no longer accept to just go and manually edit the source files by changing all over the place one environment with another, and you ask yourself if Maven could help with this.

It can, and here’s how.
The main idea is to store all the properties, in this particular example all the urls, in separate resource files. Then, using maven resource plugin copy the corresponding property file into values/environment.xml.

1. In your project root directory create following directory structure:
environment/dev/environment.xml
environment/prod/environment.xml

maven environment

2. Then fill the content of the resource files with appropriate values.
/dev/environment.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="url">http://dev.mysite.com</string>
</resources>

/prod/environment.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="url">http://prod.mysite.com</string>
</resources>

3. Add the maven resource plugin to pom.xml by specifying the phase when the copy action should be executed, the resources, and the output directory:

//...
<plugins>
    <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
             <execution>
                <id>copy-string-resources</id>
                <phase>validate</phase> <!-- when to execute copy operation -->
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <resources>
                        <resource>
                            <directory>environment/${environment}/</directory>
                            <includes>
                               <include>environment.xml</include>
                               <filtering>true</filtering>
                            </includes>
                        </resource>
                    </resources>
                    <overwrite>true</overwrite>
                    <outputDirectory>${basedir}/res/values/</outputDirectory>
                </configuration>
      </plugin>
</plugins>

4.1 From this point on, you can automate the preparation of environment by creating 2 run configurations:
mvn validate -Denvironment=dev
mvn validate -Denvironment=prod

that will do nothing but copy the appropriate resources from evironment/${environment}/environment.xml, into values/environment.xml

Now, every time you’ll need to prepare a build against a specific environment, the only thing you’ll need to do will be to run one of those commands.

4.2 Another option, to make the things even more compact, is instead of passing the environment like this: -Denvironment=dev, would be to create 2 profiles in pom.xml:

<profiles>
   <profile>
       <id>development</id>
       <properties>
           <environment>dev</environment>
       </properties>
   </profile>

   <profile>
       <id>prod</id>
       <properties>
           <environment>prod</environment>
       </properties>
   </profile>
</profiles>

and then create 2 run configurations with appropriate profile:
mvn validate -P development
mvn validate -P prod

For easy access at environment resources you could create a class like this that will return all the environment properties your applications uses:

public class ApplicationEnvironment{
	
	//...
	
	public String getServerUrl(){
		return resources.getString(R.string.url);
	}	
}

Dealing with AsyncTask and Screen Orientation

A common task in Android is to perform some background activity in another thread, meanwhile displaying a ProgressDialog to the user. Example of these tasks include downloading some data from internet, logging into an application, etc. Implementing an AsyncTask is fairly a simple job, the big challenge is how to handle it properly when an orientation change occurs.

In this article I will walk though a series of potential solutions to address the screen orientation issues when using an AsyncTask.

So, lets create a proof of concept application that makes use of an AsyncTask which does not handle configuration changes yet, and then present a few solutions.

Here’s the AsyncTask implementation that we will be using during the tutorial:

public class AsyncTaskExample extends AsyncTask<String, Integer, String> {

	private final TaskListener listener;

	public AsyncTaskExample(TaskListener listener) {
		this.listener = listener;
	}

	@Override
	protected void onPreExecute() {
		listener.onTaskStarted();
	}

	@Override
	protected String doInBackground(String... params) {
		for (int i = 1; i <= 10; i++) {
			Log.d("GREC", "AsyncTask is working: " + i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return "All Done!";
	}

	@Override
	protected void onPostExecute(String result) {
		listener.onTaskFinished(result);
	}
}

doInBackground() – this will be called by the AsyncTask on a background thread, and performs all the heavy work. For the sake of this example, I just wrote a simple loop  with a delay of 1 sec between iterations to simulate a task that takes some time.
– The constructor of the class takes a listener as a parameter. The listener will be used to delegate the work of onPreExecute()/onPostExecute() to the calling Activity.

This is the interface definition used by AsyncTaskExample:

public interface TaskListener {
	void onTaskStarted();

	void onTaskFinished(String result);
}

And here’s the usage of AsyncTaskExample (the problematic case):

public class MainActivity extends Activity implements TaskListener, OnClickListener {

	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.start).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.start) {
			new AsyncTaskExample(this).execute();
		}
	}

	@Override
	public void onTaskStarted() {
		progressDialog = ProgressDialog.show(CopyOfMainActivity.this, "Loading", "Please wait a moment!");
	}

	@Override
	public void onTaskFinished(String result) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}
}

The Activity implements the TaskListener interface and provides appropriate implementation for its methods,  displaying the ProgressDialog when the task is started, and dismissing it when the task is finished. The AsyncTask is fired when clicking on a button.

Now, if you run this example without changing the screen orientation, the AsyncTask will start and finish its work normally. Problems begin to appear when the device orientation is changed while the AsyncTask is in the middle of the work. The application will crash, and an exception similar to these ones will be thrown: java.lang.IllegalArgumentException: View not attached to window manager, or Activity has leaked window com.android.internal.policy….

The cause relies in the Activity life cycle. A change in device orientation is interpreted as a configuration change which causes the current activity to be destroyed and then recreated. Android calls onPause(), onStop(), and onDestroy() on currently instance of activity, then a new instance of the same activity is recreated calling onCreate(), onStart(), and onResume(). The reason why Android have to do this, is because depending of screen orientation, portrait or landscape, we may need to load and display different resources, and only through re-creation Android can guarantee that all our resources will be re-requested.

But don’t panic, you are not alone, there are several solutions that will help us to deal with this situation.

Solution 1 – Think twice if you really need an AsyncTask.

AsyncTasks are good for performing background work, but they are bound to the Activity which adds some complexity. For things like making HTTP requests to a server perhaps you should consider an IntentService. IntentService used in conjunction with a BroadcastReceiver or ResultReceiver to deliver results, could do a better job than an AsyncTask in certain situations.

Solution 2 – Put the AsyncTask in a Fragment.

Using fragments probably is the cleanest way to handle configuration changes. By default, Android destroys and recreates the fragments just like activities, however, fragments have the ability to retain their instances, simply by calling: setRetainInstance(true), in one of its callback methods, for example in the onCreate().

There’s however one aspect that should be taken in consideration in order to achieve the desired result. Our AsyncTask uses a ProgressDialog to signal when the AsyncTask is started, and dismisses it when the task is done. This complicates a bit the things because even if we are using setRetainInstance(true), we should close all windows and dialogs when the Activity is destroyed, otherwise we will get an: Activity has leaked window com.android.internal.policy…  exception. This happens when you try to show a dialog after you have exited the Activity.

In order to address this issue, we will add some logic to keep track of AsyncTask status (running/not running). We will dismiss the ProgressDialog when the fragment is detached from activity, and check in onActivityCreated() the status of AsyncTask. If the status is “running”, this means we are returning from a screen orientation and we will just re-create and display the ProgressDialog to show that the AsyncTask is still working.

public class ExampleFragment extends Fragment implements TaskListener, OnClickListener {

	private ProgressDialog progressDialog;
	private boolean isTaskRunning = false;
	private AsyncTaskExample asyncTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// If we are returning here from a screen orientation
		// and the AsyncTask is still working, re-create and display the
		// progress dialog.
		if (isTaskRunning) {
			progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_layout, container, false);
		Button button = (Button) view.findViewById(R.id.start);
		button.setOnClickListener(this);
		return view;
	}

	@Override
	public void onClick(View v) {
		if (!isTaskRunning) {
			asyncTask = new AsyncTaskExample(this);
			asyncTask.execute();
		}
	}

	@Override
	public void onTaskStarted() {
		isTaskRunning = true;
		progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
	}

	@Override
	public void onTaskFinished(String result) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		isTaskRunning = false;
	}

	@Override
	public void onDetach() {
		// All dialogs should be closed before leaving the activity in order to avoid
		// the: Activity has leaked window com.android.internal.policy... exception
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onDetach();
	}
}
Solution 3 – Lock the screen orientation

You could do this in 2 ways:

a) permanently locking the screen orientation of the activity, specifying the screenOrientation attribute in the AndroidManifest with “portrait” or “landscape” values:

<activity
   android:screenOrientation="portrait"
   ...  />

b) or, temporarily locking the screen in onPreExecute(), and unlocking it in onPostExecute(), thus preventing any orientation change while the AsyncTask is working:

@Override
public void onTaskStarted() {
	lockScreenOrientation();
	progressDialog = ProgressDialog.show(CopyOfCopyOfMainActivity.this, "Loading", "Please wait a moment!");
}

@Override
public void onTaskFinished(String result) {
	if (progressDialog != null) {
		progressDialog.dismiss();
	}
	unlockScreenOrientation();
}

private void lockScreenOrientation() {
	int currentOrientation = getResources().getConfiguration().orientation;
	if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	} else {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	}
}

private void unlockScreenOrientation() {
	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
Solution 4 – Prevent the Activity from being recreated.

This is the easiest way to handle configuration changes, but the less advised. The only thing you need to do is to specify the configChanges attribute followed by a list of values that specifies when the activity should prevent itself from restarting.

<activity
   android:configChanges="orientation|keyboardHidden"
   android:name=".MainActivity"
   .... />

Using this approach however, is not recommended, and this is clearly stated in the Android documentation: Using this attribute should be avoided and used only as a last-resort.

You may ask what’s wrong with this approach. Well, if you build the above example against Android 2.2 it will work fine, but if you build it against Android 3.0 and higher, you may notice that the application still crashes on orientation change. This is because starting  with Android 3.0 you need also to handle the screenSize, and smallestScreenSize:

<activity
   android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize"
   android:name=".MainActivity"
   .... />

As it turns out, not only a screen orientation causes the Activity to recreate, there are also other events which may produce configuration changes and restart the Activity, and there’s a good chance that we won’t handle them all. This is why the use of this technique is discouraged.

Integrating Google Analytics SDK (V2) with Android

The Google Analytics SDK for Android makes it easy for developers to collect valuable statics about how the users are using their app.

Here are some features that Android Google Analytics SDK offers:

  • The number of active users that are using the application
  • Usage of specific features
  • The number and type of application crashes
  • From where in the world the application is used
  • And many other useful metrics.

Just to illustrate the integration process lets create a simple proof of concept application with 2 activities: MainActivity and AboutActivity, and 2 buttons: Rate and Share.

Our mission is to integrate Google Analytics SDK with the application, to:

  • track activity views, (MainActivity and About)
  • track events (how many times the buttons “Rate”, and “Share” are clicked)

android google analytics sdk

If you are searching for Google Analytics I’m assuming you are already pretty familiar with Android and could create the proof of concept application yourself, so I will skip this step and concentrate solely on integration.

 

1. Downloading the SDK

Go to downloads page and download GoogleAnalyticsAndroid.zip Version 2.0. Extract the archive and add libGoogleAnalyticsV2.jar to your project’s /libs directory.

At the moment of writing this post, Google provides two versions: version 1.5.1 (legacy), and version 2.0 beta. Still if the Version 2 of SDK is beta, I highly suggest you choose this version, over the 1.5.1 (legacy).
The reason not to choose SDK 1.5.1 is that it uses a tracking model that is designed to track visitors to traditional websites and interaction with widgets in traditional web pages.

The new “App” profiles and reports will only accept data from version 2 or higher of the SDK.

 

2. Creating a Google Analytics account

Before starting to use the SDK you first must create an account at: http://www.google.com/analytics/

  1. Sign in to your account.
  2. Click Admin.
  3. Click Account list (just below the menu bar)
  4. Click +New Account
  5. When asked what you would like to track, select App property.android app profile
  6. Enter all the necessary information and click Get Tracking ID.

Now that you have a Tracking ID, you can begin the integration with the application. The first step is to update the AndroidManifest file.

 

3. Updating AndroidManifest file.

Add folowing permissions to the AndroidManifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

4. Creating the analytics.xml file

In version 2 of Google Analytics SDK for Android, the tracking settings are managed from an xml resource file called: analytics.xml. You will need to create this file in res/values directory, and add your tracking ID as well as other settings here.


<?xml version="1.0" encoding="utf-8"?>
<resources>

   <!-- Replace placeholder ID with your tracking ID -->
   <string name="ga_trackingId">UA-00000000-0</string>

   <!-- Enable Activity tracking -->
   <bool name="ga_autoActivityTracking">true</bool>

   <!-- Enable debug -->
   <bool name="ga_debug">true</bool>

   <!-- The screen names that will appear in your reporting -->
   <string name="com.testgoogleanalytics.MainActivity">MainActivity</string>
   <string name="com.testgoogleanalytics.About">About</string>

   <!--
   The inverval of time after all the collected data
   should be sent to the server, in seconds.
   -->
   <integer name="ga_dispatchPeriod">30</integer>

</resources>

 

5. Tracking activities.

To track activities add the tracking methods to the onStart() and onStop()  of each of your activities.


// Example of tracking MainActivity
public class MainActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   @Override
   protected void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method
   }

   @Override
   protected void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method
   }
}

One thing to note here is that EasyTraker requires a context before you can use it. If you attempt to call any of its methods but did not pass first a context, you may end up with an IllegalStateException.

In the above example, in  the onStart()  and onStop() methods the context is passed as an argument to activityStart() and activityStop(), but  if you need to make EasyTracker calls in other classes or methods, you’ll need to call EasyTracker’s setContext(Context context) method first:

Context context= this;  // Get current context.
EasyTracker.getInstance().setContext(context);  // Set context
// EasyTracker is now ready for use.

 

6. Tracking events

Tracking events is just as easy as tracking activities, you just need a Tracker object and call the trackEvent(String category, String action, String label, int value) method.

public class MainActivity extends Activity {

   private Tracker tracker;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      // Set context
      EasyTracker.getInstance().setContext(getApplicationContext());
      // Instantiate the Tracker
      tracker = EasyTracker.getTracker();

      // Add tracking functionality to "Rate" button
      Button rate = (Button) findViewById(R.id.rate);
      rate.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View arg0) {
            // The rest of your code
            tracker.trackEvent("Buttons Category", "Rate", "", 0L);
         }
      });

      // Add tracking functionality to "Share" button....
   }
}

In this particular example I don’t need a label nor a value, that is why I set for the last 2 parameters of trackEvent() method, an empty string a 0 (zero), but depending of your needs you may populate them with some data.

 

7. Debugging

Debugging helps you deal with troubleshooting, and make you sure that the data actually is sent to the server. To set the Google Analytics in debug mode, add the following setting in the analytics.xml


<bool name="ga_debug">true</bool>

Once your are in debug mode, you can watch the log information in LogCat:

 

Waiting for the big moment!

If everything is configured correctly, the reports should appear on live. Usually it takes about 24 hours to see the data in your account.

android actions google analytics

 

 

What happens if my application is used when no network is available?

Just in case you asked this yourself…, all the events are persisted in a local storage, and they will be sent the next time your app is running and dispatch is called.

 

Last but not least

One important thing not to be forgotten: you must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user’s activity inside of your app.

Android Google Analytics SDK offers more than tracking activities and events, see: https://developers.google.com/analytics/devguides/collection/android/v2/ to get the most out of it.

Please visit the Android Tutorials page for more tutorials.