Category: Android

Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. It was developed by the Open Handset Alliance, led by Google, and other companies.

Android programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn its application development. Its applications are usually developed in the Java language using the Android Software Development Kit. Once developed, the applications can be packaged easily and sold out either through a store such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon Appstore.

Android Distribution

It powers hundreds of millions of mobile devices in more than 190 countries around the world. It’s the largest installed base of any mobile platform and growing fast. Every day more than 1 million new devices are activated worldwide.

This category will help you learn all the basics and advanced areas to enable you become a programming ninja.

UI Testing with Espresso

UI Testing with Espresso

Introduction

It is normal for developers not to be concerned about testing at the beginning when still learning how to program, but as they get involved in larger projects and critical software, getting involved in testing will be inevitable. According to the documentation, Espresso is targeted at developers, who believe that automated testing is an integral part of the development lifecycle.

Software testing is the last thing on the mind of someone who just wants to code and get it going, as long as there are no bugs it is good to go. But that can be costly if done in companies where a minute of failure will cost a lot of money. I was at a GDG (Google developer group) event where a speaker who works at a well known international company said that the company had lost millions at a point, and it was due to the fact that a developer had forgotten to test the UI which was to book international flights for  customers. It was charging the customer’s account but displayed that the transaction was unsuccessful so the customers kept booking assuming that it was because of poor network, imagine how much was lost with that kind of error. Well, testing might not be top priority if I am making a quick to-do list app 🙂 , but it is good practice to properly test your code.

Espresso is a testing framework that includes a set of APIs that simulates and schedules user interactions to help test the user interface and with these tools you can automate the process of testing. So instead of punching, slapping, poking or pressing your phone screen to test if your app works fine as expected, Espresso can do this for you while you relax 🙂 .

Normally if you were to manually test your Android app, you will start the appfind the view you want to test, and verify that the expected output or behavior was what occurred. If you understand these steps then testing should’t be a problem.

According to the documentation, to create an Espresso test, create a Java class that follows this programming model:

  1. Find the UI component you want to test in an Activity  by calling the onView() method, or the onData()method for AdapterView controls.
  2. Simulate a specific user interaction to perform on that UI component, by calling the ViewInteraction.perform() or DataInteraction.perform()method and passing in the user action (for example, click on the pay button). To sequence multiple actions on the same UI component, chain them using a comma-separated list in your method argument.
  3. Repeat the steps above as necessary, to simulate a user flow across multiple activities in the target app.
  4. Use the ViewAssertions methods to check that the UI reflects the expected state or behavior, after these user interactions are performed.

Code time!

Lets take a look at a code snippet below

The first thing done is the search for the view, the withId() is a view matcher, while the check() is the view assertion. So when the code runs it checks if the textView with Id R.id.textView is displayed and if it finds the view the test will pass, otherwise the test will fail.

To properly demonstrate, let us test a simple app that copies a text from an EditText to another EditText view.

Below is the UI.

 

Below is the XML and MainActivity.java code to see what’s under the hood:

activity_main.xml

MainActivity.java

 

The EditText with Id textA is the first view at the top, while textB is the second view below textA but above the button (copyBtn).

To test this app let us create a new instrumented unit test:

I can name mine MainActivityTest:

Start testing!

So this is how my MainActivityTest class looks initially:

You will normally start the class with @RunWith(AndroidJUnit4.classwhich helps control launching the app and running UI tests on it. ActivityTestRule is a rule that provides functional testing for a specific single activity. All these annotations indicate to Android that specific parts of the test code need special processing. @Test indicates where we are testing what we are interested in.

The @Test method can have any name, but for readability be careful to give it a name that indicates the purpose of the test.  I will just quickly name mine TestEditTextA.

So the above test is just a simple test that writes some text on the first EditText view and verifies if what was written on that same EditText (textA) is what appears.  To run the test you right-click on the Java file and select ‘run’, in this case ‘RunMainActivityTest’.

If it is successful you will see a green bar as shown below, also stating how many tests were carried:

 

If it failed for some reason, the bar will be red and you will see the log output for example:

 

Full Code!

The test source code shown above isn’t the main test since it does not test the button click and the copying, below is the full code for the test:

So as shown, the text “123456” is written onto the first EditText (textA) then the button (copyBtn) is clicked and then the second EditText (textB) is checked if the text was truly copied, if so then the test passes and the app works as expected. You can get the full source code at EspressoTutorial.

Read More Read More

Dagger – Dependency Injection Introduction

Dagger – Dependency Injection Introduction

In this article, I will introduce you to the concept of dependency injection with very simple examples.

This article is the first in a series on the topic of Dependency Injection(DI) and why and how to use dagger for dependency injection on android.

 

Dependency Injection (DI) is providing an object the objects it needs instead of having it create them itself. Dependency injection is a (scary) term that is used to express a simple concept of giving an object its instance variables. It is a concept we use daily without knowing. Please bear with me…

Dependency injection can be done is several ways; Constructor injection or Setter injection. We can use a library such as Dagger for such purpose. However, using such a library is not a requirement. You can instantiate a class passing a dependency (object) into its constructor or set the dependency using a setter.

I’ll illustrate below, dependency injection without a framework or library, with a simple example;

1. Without dependency injection;

 

2. With dependency injection;

a) Constructor injection

 

b) Setter injection

 

So, there you have it. Dependency injection is simply passing an object an instance variable.

Some examples of dependency injection include;

  1. Allows your object to be flexible and configurable. In the above example, you could pass in millet flour, maize flour or even sorghum flour which then determines the type of Ugali you get.
  2. Makes your code loosely coupled. This will be important during code refactor (a.k.a changing code for some reason or other, but mainly to make it better). In the above example, if the behavior of Flour, say Flour price rises, the way ugali is cooked doesn’t change, so less code change. This also improves testability of your code; you can inject mock flour and water to test the Ugali object in unit testing.

Disadvantages include;

  1. Possible reliance on a dependency injection framework. In our case, dagger

 

 

Since I want to keep this short and simple, I’ll leave it there for now. If you want to read more on the dependency injection topic and the broader Inversion of Control (IoC) topic, here are some links;

  1. Wikipedia – Dependency Injection
  2. DZone – A beginner tutorial
  3. Dependency Injection for beginners

Next, I’ll look at a more complex scenario and how we can use dagger to do the heavy lifting for us.

In the meantime;

 

Retrofit 2 – Creating an Android Client

Retrofit 2 – Creating an Android Client

Retrofit offers a wide range of functionalities and there are a lot of possible configurations. A lot of larger applications will require some specific setup, for example for OAuth authentication. In order to achieve a clean and stable project,  i’ll introduce you our idea of a sustainable Android client: the RetrofitClient.

The RetrofitClient

As you know from our getting started with Retrofit tutorial, the Retrofit object and its builder are the heart of all requests. Here you configure and prepare your requests, responses, authentication, logging and error handling. Unfortunately, we’ve seen too many developers just copy-and-pasting these parts instead of separating into one clean class. The RetrofitClient will give you our solution, which is based on Bart Kiers’ idea.

Let’s start with the simple code. In its current state, it only defines one method to create a basic REST client for a given class/interface, which returns a service class from the interface.

The RetrofitClient class uses Retrofit’s Retrofit builder to create a new REST client with the given API base url (BASE_URL). For example, GitHub’s API base url is located at https://api.github.com/ and you must update the provided example url with your own url to call your API instead of GitHub’s.

The createService method takes a serviceClass, which is the annotated interface for API requests, as a parameter and creates a usable client from it. On the resulting client you’ll be able to execute your network requests.

Why Is Everything Declared Static Within the RetrofitClient?

You might wonder why we use static fields and methods within the RetrofitClient class. Actually, it has one simple reason: we want to use the same objects (OkHttpClientRetrofit, …) throughout the app to just open one socket connection that handles all the request and responses including caching and many more. It’s common practice to just use one OkHttpClient instance to reuse open socket connections. That means, we either need to inject the OkHttpClientto this class via dependency injection or use a static field. As you can see, we chose to use the static field. And because we use the OkHttpClient throughout this class, we need to make all fields and methods static.

Additionally to speeding things up, we can save a little bit of valuable memory on mobile devices when we don’t have to recreate the same objects over and over again.

Using the RetrofitClient

Remember how our code looked in the getting started with Retrofit tutorial?

For one request, this looks fine. But if you have dozens of network requests throughout your app, it’ll be a nightmare to manage. With our RetrofitClient, you only need a single line:

All of the preparations were moved into our RetrofitClient.

Unfortunately, in most cases the RetrofitClient cannot stay this simple. Thus, the code from above only gives you a starting point. You’ll need to adapt it to your needs just like we’ll do in other tutorials.

Preparing Logging

One of the most common wishes for developers is to know what kind of data is actually being send and received by Retrofit. I will prepare a whole tutorial on logging where you can learn more.

Logging with Retrofit 2 is done by an interceptor called HttpLoggingInterceptor. You’ll need to add an instance of this interceptor to the OkHttpClient. For example, you could solve it the following way:

There are a few things you’ve to be aware of. Firstly, make sure you’re not accidentally adding the interceptor multiple times! We check with httpClient.interceptors().contains(logging) if the logging interceptor is already present. Secondly, make sure to not build the retrofit object on every createService call. Otherwise the entire purpose of the RetrofitClient is defeated.

Prepare Authentication

The requirements for authentication are a little bit different. You will learn more in my upcoming tutorials on Basic Authentication, Token Authentication, OAuth, or even Hawk Authentication. While the details are a little different for each authentication implementation, you probably will have to change the RetrofitClient. One of the changes is that you need to pass additional parameters to createService to create a client.

Let’s look at an example for Hawk authentication:

Our createService now has a second parameter for the HawkCredentials. If you pass a non-null value, it’ll create the necessary Hawk authentication interceptor and add it to the Retrofit client. We also need to rebuild Retrofit to apply our changes to the next request.

One more heads-up, you probably will see slightly different versions of the RetrofitClient in the other tutorials. Don’t be confused! We recommend that you also keep your RetrofitClient slim and specialized for the use case!

Conclusion

In this tutorial you’ve learned why centralizing your Retrofit client generation makes sense and is recommended. You’ve seen one approach how you can implement it with the RetrofitClient class. Nevertheless, you probably will have to adjust it to your purposes.

If you’ve feedback or a question, let me know in the comments.

Happy Coding!

Retrofit 2 – Basics of API Description

Retrofit 2 – Basics of API Description

In the getting started with Retrofit tutorial you’ve implemented your first request against one GitHub endpoint. Hopefully, you’re excited to try out more of Retrofit’s functionality. In this tutorial, you’ll learn in more detail how to describe API endpoints in Retrofit.

How to Describe API Endpoints

As you’ve learned in the getting started with Retrofit tutorial, we describe all the Retrofit requests we make in an interface class. Our first example, where we showcase a few functionalities at once, was this one:

It’s time to look at all of these options in more detail.

HTTP Method

You already know that we use annotations on the Java interface methods to describe individual API endpoints and ultimately, the handling of requests. One of the first things you want to define is the HTTP request method like GETPOSTPUTDELETE, and so on.

Retrofit provides an annotation for each of the main standard request methods. You simply use the appropriate Retrofit annotations for each HTTP method: @GET@POST@PUT@DELETE@PATCH or @HEAD.

You always need to specify what kind of request method the endpoint expects from your app. If you never heard of HTTP request methods, read up on it on wikipedia’s HTTP page. You should be able to pull the expected HTTP request method from the API documentation.

A few simple examples for @GET@PUT and @DELETE:

HTTP Resource Location

Additionally, you need to add the relative endpoint URL as a String parameter to the annotation, e.g. @GET("/user/info"). In most cases, you’ll pass only a relative URL, and not a full URL (like https://androidstudy.com/api/user/info). This has the advantage, that Retrofit only has to ask for the base URL (https://androidstudy.com) once. If you’re changing the API base URL, you only have to change it in one place.

Furthermore, it makes a couple of more advanced things, like dynamic base URLs, much easier. Nevertheless, you can specify a full URL.

Again, some simple examples:

Function Name & Return Type

You now have an idea what the HTTP request method annotation is used for. However, we haven’t talked about the actual Java method declaration: Call<UserInfo> getUserInfo();. This contains three parts:

  1. Method Name
  2. Method Return Type
  3. Method Parameters

Let’s start with the easy one: method name. You can freely define the method name. Retrofit doesn’t care and it won’t have any effect on the functionality. Nevertheless, you should choose a name, which helps you and other developers to understand what API request this is.

On the other hand, the method’s return type is critical. You have to define what kind of data you expect from the server. For example, when you’re requesting some user information, you might specify it as Call<UserInfo>. The UserInfoclass contains the properties that will hold the user data. Retrofit will map it automatically and you won’t have to do any manual parsing.

If you want the raw response, you can use ResponseBody instead of a specific class like UserInfo. If you don’t care at all what the server responds, you can use Void. In all those cases, you’ll have to wrap it into a typed Retrofit Call<> class.

Finally, and this highly depends on the API endpoint, you can pass parameters to the method. There is a wide variety of possible options, so we’ll just link you some options:

  • @Body: send Java objects as request body.
  • @Url: use dynamic URLs.
  • @Field: send data as form-urlencoded.

Again, a demonstration of some use cases:

Since path and query parameters are so common, we’ll talk about them in more detail in the next two sections.

Path Parameters

REST APIs are build on dynamic URLs. You access the resource by replacing parts of the URL, for example getting the third tutorial on our page might be https://androidstudy.com/api/tutorials/3. The 3 at the end specifies which tutorial you want to access. Retrofit offers a simple way of replacing these so called path parameters. You’ve already seen an example in the getting started tutorial:

Here, the {user} indicates to Retrofit that the value is dynamic and will be set when the request is being made. If you include a path parameter in the URL, you need to add a @Path() function parameter, where the @Path value matches the placeholder in the URL (in this case it’d be @Path("user")). You can use multiple placeholders, if necessary. Just make sure you always have the exact amount of matching parameters.

Query Parameters

Another large part of dynamic URLs are query parameters. If you’ve used our filters already, you’ve seen them on some websites: https://demowebsite.com/tutorials?filter=video. The ?filter=video is a query parameter which further describes the request resource. Unlike the path parameters, you don’t need to add them to the annotation URL. You can simply add a method parameter with @Query() and a query parameter name, describe the type and you’re good to go. Retrofit will automatically attach it to the request. If you pass a null value as query parameter, Retrofit will ignore it. You can also add multiple query parameters.

In the example above, you could also remove the first getTutorials() method and just use the second one by passing a null value as the value for the last three parameters.

What Comes Next?

This was only an introduction to describing API endpoints. You’ve learned the basics of adding new endpoints to your interfaces. You can adjust the resource locations, the HTTP method, return types, path and query parameters.

Retrofit offers a lot more options to further modify requests. For example, we didn’t talk at all about headers yet. There is a lot more to learn, so keep on reading more tutorials!

If you’ve feedback or a question, let me know in the comments.

Happy Coding!

Retrofit – Getting Started and Creating an Android Client

Retrofit – Getting Started and Creating an Android Client

Hi guys! This is the first tutorial in an extensive series on Retrofit. The series dives through all aspects of Retrofit and prepares you for many potential use cases. You’ll get to know Retrofit’s range of functions and extensibility.

Within this first tutorial we’re going through the basics of Retrofit and create an Android client for HTTP requests against the GitHub API.

What is Retrofit?

The official page describes Retrofit as

A type-safe REST client for Android and Java.

You’ll use annotations to describe HTTP requests, URL parameter replacement and query parameter support is integrated by default. Additionally, it provides functionality for custom headers, multipart request body, file uploads and downloads, mocking responses and much more. In later tutorials we’ll look at all of these in more details.

Prepare Your Android Project

Let’s get our hands dirty and back to the keyboard. If you already created your Android project, just go ahead and start from the next section. Otherwise, create a new project in our favorite IDE, Android Studio. I prefer Android Studio with Gradle as the build system, but you surely can use your IDE of choice or Maven as well.

Define Dependencies: Gradle

At first, set Retrofit as a dependency for your project. Define Retrofit and its dependencies in your build.gradle. When running the command to build your code, the build system will download and provide the library for your project.

Retrofit 2

I recommend Retrofit 2 as it leverages OkHttp as the networking layer by default and is built on top of it. You don’t need to explicitly define OkHttp as a dependency for your project, unless you have a specific version requirement.

However, Retrofit 2 requires a dependency for the automatic conversion of request and response payloads. Use the following dependencies if you’re using Retrofit in version 2 and want to map JSON payloads with GSON:

Android’s Network Permission

Retrofit performs HTTP requests against an API running on a server somewhere in the Internet. Executing those requests from an Android application requires the Internet permission to open network sockets. You need to define the permission within the AndroidManifest.xml file. If you didn’t set the Internet permission yet, please add the following line within your AndroidManifest.xml definition:

How to Describe API Endpoints

Before you can start with your first requests, you need to describe the API endpoints you want to interact with. In this tutorial we’ll just describe a simple GitHub endpoint. We’ll go into more detail on API endpoint description in a later tutorial.

First, you have to create an interface and define required methods.

GitHub Client

The following code defines the GitHubClient and a method reposForUser to request the list of repositories for a given user. The @GET annotation declares that this request uses the HTTP GET method. The code snippet also illustrates the usage of Retrofit’s path parameter replacement functionality. In the defined method the {user} path will be replaced with the given variable values when calling the reposForUser method.

Retrofit 2

There is a defined class GitHubRepo. This class comprises required class properties to map the response data.

With regard to the previously mentioned JSON mapping: the GitHubClient interface defines a method named reposForUser with return type List<GitHubRepo>. Retrofit makes sure the server response gets mapped correctly (in case the response matches the given class).

Retrofit REST Client

After describing the API interface and the object model, it’s time to prepare an actual request. Retrofit’s basis for all requests is the Retrofit (2.0+) class. You create and configure it with a fluent API. To that end, you can use the builder to set some general options for all requests, i.e. the base URL or the converter. We’ll go into more detail for all of the available options in a later tutorial.

Once you’ve created an adapter, you’re able to create a client. You’ll use the client to execute the actual requests.

Retrofit 2

In our example, GitHub’s API base URL is https://api.github.com/. In the code snippets above we just went with the minimum options. There are a lot more options for fine-tuned control over your requests. But it’s sufficient for the purpose of making our first request!

JSON Mapping

In most cases requests to a server, and the responses from the server, are not Java objects. They’re mapped to some language neutral format like JSON. Since GitHub’s API uses JSON, we need to prepare Retrofit for it.

Retrofit 1.9 ships with Google’s Gson (which parses JSON to and from Java objects) by default. All you need to do is define the class of your response object and the response will be mapped automatically.

When using Retrofit 2, you need to add a converter explicitly to the Retrofit object.  Above, we have added the following line in our build.gradle file to import the Gson converter.

If you followed our tutorial from the beginning, you’ve already done this!

Retrofit in Use

After doing a ton of prep work, it’s time to reap the benefits and finally make your request. The good news: it’s only going to be a few lines!

The first line of creating a client object should already be familiar. The way of actually executing the request depends on the Retrofit version.

Retrofit 2

In Retrofit 2, you also use your client object. However, here you don’t pass your callback as the last parameter. You use the client to get a call object. Once you’ve invoked .enqueue on the created call object the request will be made by Retrofit. There is also an option to do a synchronous request, but we’ll look at those later.

In either case, you should be able to make your very first request with Retrofit. If everything went well, Retrofit will return you a handy List<GitHubRepo>, which you can further use to display the data in your app.

Initially, Retrofit looks pretty complex. We promise, it’s very clean and pays off if you’re working on a larger project. If you spend a little more time reading a few more tutorials, you’ll soon also love Retrofit.

What Comes Next?

In this tutorial you’ve learned the basics of Retrofit. In multiple sections we’ve only given you the code without much explanations. We highly recommend to read up on those parts in more detail. You should start by reading how to describe API endpoints with Retrofit, which will be available soon.

If you’ve feedback or a question, let me know in the comments.

Happy Coding!