Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all 1836 articles
Browse latest View live

Create Intelligent Chatbots on Android With IBM Watson

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29387

If you've ever spoken to voice-based personal assistants such as Siri or Google Now, or chatted with one of the many text-based bots active on messaging platforms such as Facebook Messenger and Kik, you probably realize how fun, intuitive, and powerful conversational user interfaces can be. However, because most natural languages are extremely complex, creating such interfaces from scratch tends to be hard. Fortunately, there's IBM Watson.

By using the IBM Watson Conversation service, you can create AI-powered conversational user interfaces in minutes, often with just a few lines of code. In this tutorial, I'll introduce you to the service and show you how to use it in Android apps.

Prerequisites

To make the most of this tutorial, you'll need the following:

1. Creating a Conversation Service

Before you can use the IBM Watson Conversation API, you must create a Conversation service on the IBM Bluemix platform and acquire login credentials for it. To do so, sign in to the Bluemix console, navigate to Services > Watson, and press the Create Watson service button. On the next screen, choose Conversation from the catalog of available services.

Watson services catalog

In the configuration form that's displayed next, type in an appropriate name for the service and press the Create button.

Conversation service configuration form

2. Creating a Conversation Workspace

A Conversation service can work only if it has at least one Conversation workspace associated with it. For now, you can think of a workspace as a collection of rules and configuration details, which defines the capabilities and personality of your conversational UI.

The Bluemix console has an easy-to-use tool that allows you to create and manage workspaces. To launch it, press the Launch tool button.

Conversation workspace tool launcher

In the next screen, press the Create button to create a new workspace. In the dialog that pops up, give a meaningful name to the workspace and choose a language for it.

Workspace configuration dialog

Once the workspace has been created, you are expected to add intents, entities, and dialog details to it.

Intents entities and dialog tabs

While intents define actions a user can perform using your conversational UI, entities define objects that are relevant to those actions. For example, in the sentence "book me a ticket from New York to Chicago", "book a ticket" would be an intent, and "New York" and "Chicago" would be entities. Dialog details define the actual responses the conversational UI generates, and how its conversations flow.

Step 1: Create Intents

In this tutorial, we'll be creating a very simple Android chatbot capable of performing the following actions:

  • greet the user
  • introduce itself
  • quote inspirational quotes

Accordingly, our chatbot needs three intents.

Press the Create New button to create the first intent. In the form that shows up, name the intent #Greeting, provide a few sample words or sentences the user might use for the intent, such as "hi" and "hello", and press the Done button.

Greeting intent creation

The best thing about the Watson Conversation service is that it intelligently trains itself using the sample user inputs you provide to the intent. Consequently, it will be able to respond to several variations of those sample inputs. For example, it will be able to correctly match words and phrases such as "howdy", "good morning", and "yo!" to the #Greeting intent.

Press the Create New button again to create the next intent. Name it #Name, and provide the following user examples.

Name intent creation

Similarly, name the third intent #RequestQuote, and provide the following user examples.

RequestQuote intent creation

Step 2: Create a Dialog

Our chatbot is so simple that we don't need to define any entities for it. Therefore, we can now directly start specifying how it responds to each intent we created.

Start by going to the Dialog tab and pressing the Create button. In the next screen, you'll see that two dialog nodes are created for you automatically: one named Welcome, which is to greet the user, and one named Anything else, which is to catch inputs the bot doesn't understand.

Default dialog nodes

For now, let's leave the Anything else node as it is, and configure the Welcome node. In the dialog that pops up, type in #Greeting in the If bot recognizes field, and then add a few responses. Obviously, the more responses you add, the more human-like your chatbot will be.

Dialog for Greeting

Next, create a new node for the #Name intent by pressing the Add Node button. Again, fill the form shown appropriately.

Dialog for Name

The node for the #RequestQuote intent is going to be slightly different. We won't be manually typing in a few inspirational quotes as the responses of this node because doing so would make our bot too static and uninteresting. Instead, our Android chatbot should be able to fetch quotes from an external API. Therefore, the responses of this node should be sentences that ask the user to wait while the bot searches for a new quote.

Dialog for RequestQuote

At this point, our workspace is ready. You can test it right away by clicking the speech balloon icon. Feel free to test it with a variety of sentences to make sure that it associates the right intents with them.

Testing the workspace

Step 3: Determine Credentials

To be able to use the Conversation service in an Android app, you'll need its username and password. Additionally, you'll need the ID of the Conversation workspace. Therefore, go to the Deploy section and switch to the Credentials tab.

You should now be able to see the credentials you need. After noting them all down, you can close the Bluemix console.

Credentials tab

3. Android Studio Project Setup

Although it is possible to interact with the Conversation service using any Android networking library, using the Watson Java SDK is a better idea because it offers a very intuitive and high-level API. To add it to your Android Studio project, add the following compile dependency in the app module's build.gradle file:

Additionally, we'll be needing the Fuel networking library to fetch inspirational quotes from a remote server, and the Design support library to able to work with a few Material Design widgets.

Both Fuel and the Watson Java SDK require your app to have the INTERNET permission, so don't forget to ask for it in your project's manifest file:

Lastly, open the res/values/strings.xml file and add the Conversation service's username and password, and the Conversation workspace's ID to it as <string> tags:

You can now press the Sync Now button to complete the project setup.

4. Defining a Layout

We will be creating a text-based bot in this tutorial. Therefore, our app's layout should contain an EditText widget where users can type in their messages, and a TextView widget where the user-bot conversation can be shown. Optionally, you can place the EditText widget inside a TextInputLayout container to make sure that it follows the Material Design guidelines.

It's also a good idea to place the TextView widget inside a ScrollView container to make sure that long conversations aren't truncated.

Note that we've set the value of the EditText widget's imeOptions attribute to actionDone. This allows users to press a Done button on their virtual keyboards when they've finished typing their messages.

5. Using the Conversation Service

The ConversationService class of the Watson SDK has all the methods you'll need to communicate with the Conversation service. Therefore, the first thing you need to do in your Activity class is create an instance of it. Its constructor expects a version date, the service's username, and its password.

Next, to be able to work with the widgets present in the layout XML file, you must get references to them using the findViewById() method.

When the users have finished typing their input messages, they will be pressing the Done button on their virtual keyboards. To be able to listen to that button-press event, you must add an OnEditorActionListener to the EditText widget.

Inside the listener, you can call the getText() method of the EditText widget to fetch the user's message.

The TextView widget will be displaying both the messages of the user and the replies of the bot. Therefore, append the message to the TextView widget using its append() method.

The user's message must be sent to the Conversation service wrapped in a MessageRequest object. You can create one easily using the MessageRequest.Builder class.

Once the request is ready, you must pass it to the message() method of the ConversationService object, along with the workspace's ID. Finally, to actually send the message to the Conversation service, you must call the enqueue() method.

Because the enqueue() method runs asynchronously, you will also need a ServiceCallback object to get the service's response.

Inside the onResponse() method, you can call the getText() method of the MessageResponse object to get the Conversation service's response.

You can now append the response to the TextView widget again using its append() method. However, make sure you do so inside the runOnUiThread() method because you are currently on a different thread.

Our bot is almost ready. If you try running the app, you'll be able to get correct responses from it for the #Greeting and #Name intents. It still can't recite inspirational quotes, though. Therefore, we must now add code to explicitly look for the #RequestQuote intent and generate a response manually.

To extract the name of the detected intent from the MessageResponse object, you must call its getIntents() method, which returns a list of MessageResponse.Intent objects, pick the first item, and call its getIntent() method.

There are many websites with free APIs you can use to fetch inspirational quotes. Forismatic is one of them. Its REST API provides quotes as plain text, which you can directly use in your app.

To make an HTTP request to the Forismatic API's URL, all you need to do is call the get() method of the Fuel class. Because the method runs asynchronously, you must handle the HTTP response by calling the responseString() method and passing a Handler object to it.

Inside the success() method of the handler, you can simply append the quote to the TextView widget. The following code shows you how:

The bot is now complete, and will be able to generate the right responses for all the intents we added to the workspace.

The Android chatbot running

Conclusion

Conversational user interfaces are all the rage today. They are so easy to use that everybody loves them. In this tutorial, you learned the basics of creating such interfaces on the Android platform using the IBM Watson Conversation service.

There's a lot more the service can do. To learn more about it, you can refer to the official documentation.

And be sure to check out some of our other posts on using machine learning for your Android apps!

2017-08-17T12:09:11.000Z2017-08-17T12:09:11.000ZAshraff Hathibelagal

Put Your View Controllers on a Diet With MVVM

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29473

In my previous post in this series, I wrote about the Model-View-Controller pattern and some of its imperfections. Despite the clear benefits MVC brings to software development, it tends to fall short in large or complex Cocoa applications.

This isn't news, though. Several architectural patterns have emerged over the years, aiming to address the shortcomings of the Model-View-Controller pattern. You may have heard of MVP, Model-View-Presenter, and MVVM, Model-View-ViewModel, for example. These patterns look and feel similar to the Model-View-Controller pattern, but they also tackle some of the issues the Model-View-Controller pattern suffers from.

1. Why Model-View-ViewModel

I had been using the Model-View-Controller pattern for years before I accidentally stumbled upon the Model-View-ViewModel pattern. It's not surprising that MVVM is a latecomer to the Cocoa community, since its origins lead back to Microsoft. However, the MVVM pattern has been ported to Cocoa and adapted to the requirements and needs of the Cocoa frameworks and has recently been gaining traction in the Cocoa community.

Most appealing is how MVVM feels like an improved version of the Model-View-Controller pattern. This means that it doesn't require a dramatic change of mindset. In fact, once you understand the fundamentals of the pattern, it's fairly easy to implement, no more difficult than implementing the Model-View-Controller pattern.

2. Putting View Controllers on a Diet

In the previous post, I wrote that the controllers in a typical Cocoa application are a bit different from the controllers Reenskaug defined in the original MVC pattern. On iOS, for example, a view controller controls a view. Its sole responsibility is populating the view it manages and responding to user interaction. But that's not the only responsibility of view controllers in most iOS applications, is it?

The MVVM pattern introduces a fourth component to the mix, the view model, which helps refocus the view controller. It does this by taking over some of the responsibilities of the view controller. Take a look at the diagram below to better understand how the view model fits into the Model-View-ViewModel pattern.

The MVVM Pattern

As the diagram illustrates, the view controller no longer owns the model. It's the view model that owns the model, and the view controller asks the view model for the data it needs to display.

This is an important difference from the Model-View-Controller pattern. The view controller has no direct access to the model. The view model hands the view controller the data it needs to display in its view.

The relationship between the view controller and its view remains unchanged. That's important because it means that the view controller can focus exclusively on populating its view and handling user interaction. That's what the view controller was designed for.

The result is pretty dramatic. The view controller is put on a diet, and many responsibilities are shifted to the view model. You no longer end up with a view controller that spans hundreds or even thousands of lines of code.

3. Responsibilities of the View Model

You're probably wondering how the view model fits into the bigger picture. What are the tasks of the view model? How does it relate to the view controller? And what about the model?

The diagram I showed you earlier gives us a few hints. Let's start with the model. The model is no longer owned by the view controller. The view model owns the model, and it acts as a proxy to the view controller. Whenever the view controller needs a piece of data from its view model, the latter asks its model for the raw data and formats it in such a way that the view controller can immediately use it in its view. The view controller isn't responsible for data manipulation and formatting.

The diagram also reveals that the model is owned by the view model, not the view controller. It's also worth pointing out that the Model-View-ViewModel pattern respects the close relationship of the view controller and its view, which is characteristic for Cocoa applications. That's why MVVM feels like a natural fit for Cocoa applications.

4. An Example

Because the Model-View-ViewModel pattern is not native to Cocoa, there are no strict rules to implement the pattern. Unfortunately, this is something many developers get confused by. To clarify a few things, I'd like to show you a basic example of an application that uses the MVVM pattern. We create a very simple application that fetches weather data for a predefined location from the Dark Sky API and displays the current temperature to the user.

Step 1: Set Up the Project

Fire up Xcode and create a new project based on the Single View Application template. I'm using Xcode 8 and Swift 3 for this tutorial.

Setting Up the Project

Name the project MVVM, and set Language to Swift and Devices to iPhone.

Configuring the Project

Step 2: Create a View Model

In a typical Cocoa application powered by the Model-View-Controller pattern, the view controller would be in charge of performing the network request. You could use a manager for performing the network request, but the view controller would still know about the origins of the weather data. More importantly, it would receive the raw data and would need to format it before displaying it to the user. This isn't the approach we take when adopting the Model-View-ViewModel pattern.

Let's create a view model. Create a new Swift file, name it WeatherViewViewModel.swift, and define a class named WeatherViewViewModel.

Creating a View Model

The idea is simple. The view controller asks the view model for the current temperature for a predefined location. Because the view model sends a network request to the Dark Sky API, the method accepts a closure, which is invoked when the view model has data for the view controller. That data could be the current temperature, but it could also be an error message. This is what the currentTemperature(completion:) method of the view model looks like. We'll fill in the details in a few moments.

We declare a type alias for convenience and define a method, currentTemperature(completion:), that accepts a closure of type CurrentTemperatureCompletion

The implementation isn't hard if you're familiar with networking and the URLSession API. Take a look at the code below and notice that I've used an enum, API, to keep everything nice and tidy.

The only piece of code that I haven't showed you yet is the implementation of the temperature(from:) method. In this method, we extract the current temperature from the Dark Sky response.

In a production application, I'd opt for a more robust solution to parse the response, such as ObjectMapper or Unbox.

Step 3: Integrate the View Model

We can now use the view model in the view controller. We create a property for the view model, and we also define three outlets for the user interface.

Notice that the view controller owns the view model. In this example, the view controller is also responsible for instantiating its view model. In general, I prefer to inject the view model into the view controller, but let's keep it simple for now.

In the view controller's viewDidLoad() method, we invoke a helper method, fetchWeatherData().

In fetchWeatherData(), we ask the view model for the current temperature. Before we request the temperature, we'll hide the label and button and show the activity indicator view. In the closure we pass to fetchWeatherData(completion:), we update the user interface by populating the temperature label and hiding the activity indicator view.

The button is wired to an action, fetchWeatherData(_:), in which we also invoke the fetchWeatherData() helper method. As you can see, the helper method helps us avoid code duplication.

Step 4: Create the User Interface

The last piece of the puzzle is to create the user interface of the example application. Open Main.storyboard and add a label and a button to a vertical stack view. We'll also add an activity indicator view on top of the stack view, centered vertically and horizontally.

Creating the User Interface

Don't forget to wire up the outlets and the action we defined in the ViewController class!

Now build and run the application to give it a try. Remember that you need a Dark Sky API key to make the application work. You can sign up for a free account on the Dark Sky website.

5. What Are the Benefits?

Even though we only moved a few bits and pieces to the view model, you may be wondering why this is necessary. What did we gain? Why would you add this additional layer of complexity?

The most obvious gain is that the view controller is leaner and more focused on managing its view. That's the core task of a view controller: managing its view.

But there's a more subtle benefit. Because the view controller isn't responsible for fetching the weather data from the Dark Sky API, it isn't aware of the details related to this task. The weather data could come from a different weather service or from a cached response. The view controller wouldn't know, and it doesn't need to know.

Testing also improves dramatically. View controllers are known to be hard to test because of their close relationship to the view layer. By moving some of the business logic to the view model, we instantly improve the testability of the project. Testing view models is surprisingly easy because they don't have a link to the application's view layer.

Conclusion

The Model-View-ViewModel pattern is a significant step forward in designing Cocoa applications. View controllers aren't so massive, view models are easier to compose and test, and your project becomes more manageable as a result.

In this short series, we only scratched the surface. There's a lot more to write about the Model-View-ViewModel pattern. It's become one of my favorite patterns over the years, and that's why I keep speaking and writing about it. Give it a try and let me know what you think!

In the meantime, check out some of our other posts about Swift and iOS app development.

2017-09-08T13:00:00.000Z2017-09-08T13:00:00.000ZBart Jacobs

Kotlin From Scratch: More Fun With Functions

$
0
0

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.  

In the previous article, you learned about packages and basic functions in Kotlin. Functions are at the heart of Kotlin, so in this post we'll look more closely at them. We'll be exploring the following kinds of functions in Kotlin:

  • top-level functions
  • lambda expressions or function literals
  • anonymous functions
  • local or nested functions
  • infix functions
  • member functions

You'll be amazed at all the cool things you can do with functions in Kotlin!

1. Top-Level Functions

Top-level functions are functions inside a Kotlin package that are defined outside of any class, object, or interface. This means that they are functions you call directly, without the need to create any object or call any class. 

If you're a Java coder, you know that we typically create utility static methods inside helper classes. These helper classes don't really do anything—they don't have any state or instance methods, and they just act as a container for the static methods. A typical example is the Collections class in the java.util package and its static methods. 

Top-level functions in Kotlin can be used as a replacement for the static utility methods inside helper classes we code in Java. Let's look at how to define a top-level function in Kotlin. 

In the code above, we defined a package com.chikekotlin.projectx.utils inside a file called UserUtils.kt and also defined a top-level utility function called checkUserStatus() inside this same package and file. For brevity's sake, this very simple function returns the string "online". 

The next thing we'll do is to use this utility function in another package or file.

In the preceding code, we imported the function into another package and then executed it! As you can see, we don't have to create an object or reference a class to call this function.

Java Interoperability

Given that Java doesn't support top-level functions, the Kotlin compiler behind the scenes will create a Java class, and the individual top-level functions will be converted to static methods. In our own case, the Java class generated was UserUtilsKt with a static method checkUserStatus()

This means that Java callers can simply call the method by referencing its generated class, just like for any other static method.

Note that we can change the Java class name that the Kotlin compiler generates by using the @JvmName annotation.

In the code above, we applied the @JvmName annotation and specified a class name UserUtils for the generated file. Note also that this annotation is placed at the beginning of the Kotlin file, before the package definition. 

It can be referenced from Java like this:

2. Lambda Expressions

Lambda expressions (or function literals) are also not bound to any entity such as a class, object, or interface. They can be passed as arguments to other functions called higher-order functions (we'll discuss these more in the next post). A lambda expression represents just the block of a function, and using them reduces the noise in our code. 

If you're a Java coder, you know that Java 8 and above provides support for lambda expressions. To use lambda expressions in a project that supports earlier Java versions such as Java 7, 6, or 5, we can use the popular Retrolambda library

One of the awesome things about Kotlin is that lambda expressions are supported out of the box. Because lambda is not supported in Java 6 or 7, for Kotlin to interoperate with it, Kotlin creates a Java anonymous class behind the scene. But note that creating a lambda expression in Kotlin is quite different than it is in Java.

Here are the characteristics of a lambda expression in Kotlin:

  • It must be surrounded by curly braces {}.
  • It doesn't have the fun keyword. 
  • There is no access modifier (private, public or protected) because it doesn't belong to any class, object, or interface.
  • It has no function name. In other words, it's anonymous. 
  • No return type is specified because it will be inferred by the compiler.
  • Parameters are not surrounded by parentheses ()

And, what's more, we can assign a lambda expression to a variable and then execute it. 

Creating Lambda Expressions

Let's now see some examples of lambda expressions. In the code below, we created a lambda expression without any parameters and assigned it a variable message. We then executed the lambda expression by calling message()

Let's also see how to include parameters in a lambda expression. 

In the code above, we created a lambda expression with the parameter myString, along with the parameter type String. As you can see, in front of the parameter type, there is an arrow: this refers to the lambda body. In other words, this arrow separates the parameter list from the lambda body. To make it more concise, we can completely ignore the parameter type (already inferred by the compiler). 

To have multiple parameters, we just separate them with a comma. And remember, we don't wrap the parameter list in parentheses like in Java. 

However, note that if the parameter types can't be inferred, they must be specified explicitly (as in this example), otherwise the code won't compile.

Passing Lambdas to Functions

We can pass lambda expressions as parameters to functions: these are called "higher-order functions", because they are functions of functions. These kinds of functions can accept a lambda or an anonymous function as parameter: for example, the last() collection function. 

In the code below, we passed in a lambda expression to the last() function. (If you want a refresher on collections in Kotlin, visit the third tutorial in this series) As the name says, it returns the last element in the list.  last() accepts a lambda expression as a parameter, and this expression in turn takes one argument of type String. Its function body serves as a predicate to search within a subset of elements in the collection. That means that the lambda expression will decide which elements of the collection will be considered when looking for the last one.

Let's see how to make that last line of code above more readable.

The Kotlin compiler allows us to remove the function parentheses if the last argument in the function is a lambda expression. As you can observe in the code above, we were allowed to do this because the last and only argument passed to the last() function is a lambda expression. 

Furthermore, we can make it more concise by removing the parameter type.

We don't need to specify the parameter type explicitly, because the parameter type is always the same as the collection element type. In the code above, we're calling last on a list collection of String objects, so the Kotlin compiler is smart enough to know that the parameter will also be a String type. 

The it Argument Name

We can even simplify the lambda expression further again by replacing the lambda expression argument with the auto-generated default argument name it.

The it argument name was auto-generated because last can accept a lambda expression or an anonymous function (we'll get to that shortly) with only one argument, and its type can be inferred by the compiler.  

Local Return in Lambda Expressions

Let's start with an example. In the code below, we pass a lambda expression to the foreach() function invoked on the intList collection. This function will loop through the collection and execute the lambda on each element in the list. If any element is divisible by 2, it will stop and return from the lambda. 

Running the above code might not have given you the result you might have expected. This is because that return statement won't return from the lambda but instead from the containing function surroundingFunction()! This means that the last code statement in the surroundingFunction() won't execute. 

To fix this problem, we need to tell it explicitly which function to return from by using a label or name tag. 

In the updated code above, we specified the default tag @forEach immediately after the return keyword inside the lambda. We have now instructed the compiler to return from the lambda instead of the containing function surroundingFunction(). Now the last statement of surroundingFunction() will execute. 

Note that we can also define our own label or name tag. 

In the code above, we defined our custom label called myLabel@ and then specified it for the return keyword. The @forEach label generated by the compiler for the forEach function is no longer available because we have defined our own. 

However, you'll soon see how this local return problem can be solved without labels when we discuss anonymous functions in Kotlin shortly.

3. Member Functions

This kind of function is defined inside a class, object, or interface. Using member functions helps us to modularize our programs further. Let's now see how to create a member function.

This code snippet shows a class Circle (we'll discuss Kotlin classes in later posts) that has a member function calculateArea(). This function takes a parameter radius to calculate the area of a circle.

To invoke a member function, we use the name of the containing class or object instance with a dot, followed by the function name, passing any arguments if need be.

4. Anonymous Functions

An anonymous function is another way to define a block of code that can be passed to a function. It is not bound to any identifier. Here are the characteristics of an anonymous function in Kotlin:

  • has no name
  • is created with the fun keyword
  • contains a function body

Because we passed a lambda to the last() function above, we can't be explicit about the return type. To be explicit about the return type, we need to use an anonymous function instead.

In the above code, we have replaced the lambda expression with an anonymous function because we want to be explicit about the return type. 

Towards the end of the lambda section in this tutorial, we used a label to specify which function to return from. Using an anonymous function instead of a lambda inside the forEach() function solves this problem more simply. The return expression returns from the anonymous function and not from the surrounding one, which in our case is surroundingFunction().

5. Local or Nested Functions

To take program modularization further, Kotlin provides us with local functions—also known as nested functions. A local function is a function that is declared inside another function. 

As you can observe in the code snippet above, we have two single-line functions: calCircumference() and calArea() nested inside the printCircumferenceAndAread() function. The nested functions can be called only from within the enclosing function and not outside. Again, the use of nested functions makes our program more modular and tidy. 

We can make our local functions more concise by not explicitly passing parameters to them. This is possible because local functions have access to all parameters and variables of the enclosing function. Let's see that now in action:

As you can see, this updated code looks more readable and reduces the noise we had before. Though the enclosing function in this example given is small, in a larger enclosing function that can be broken down into smaller nested functions, this feature can really come in handy. 

6. Infix Functions

The infix notation allows us to easily call a one-argument member function or extension function. In addition to a function being one-argument, you must also define the function using the infix modifier. To create an infix function, two parameters are involved. The first parameter is the target object, while the second parameter is just a single parameter passed to the function. 

Creating an Infix Member Function

Let's look at how to create an infix function in a class. In the code example below, we created a Student class with a mutable kotlinScore instance field. We created an infix function by using the infix modifier before the fun keyword. As you can see below, we created an infix function addKotlinScore() that takes a score and adds to the kotlinScore instance field. 

Calling an Infix Function

Let's also see how to invoke the infix function we have created. To call an infix function in Kotlin, we don't need to use the dot notation, and we don't need to wrap the parameter with parentheses. 

In the code above, we called the infix function, the target object is student, and the double 95.00 is the parameter passed to the function. 

Using infix functions wisely can make our code more expressive and clearer than the normal style. This is greatly appreciated when writing unit tests in Kotlin (we'll discuss testing in Kotlin in a future post).

The to Infix Function

In Kotlin, we can make the creation of a Pair instance more succinct by using the to infix function instead of the Pair constructor. (Behind the scenes, to also creates a Pair instance.) Note that the to function is also an extension function (we'll discuss these more in the next post).

Let's now compare the creation of a Pair instance using both the to infix function and directly using the Pair constructor, which performs the same operation, and see which one is better.

As you can see in the code above, using the to infix function is more concise than directly using the Pair constructor to create a Pair instance. Remember that using the to infix function, 234 is the target object and the String "Nigeria" is the parameter passed to the function. Moreover, note that we can also do this to create a Pair type:

In the Ranges and Collections post, we created a map collection in Kotlin by giving it a list of pairs—the first value being the key, and the second the value. Let's also compare the creation of a map by using both the to infix function and the Pair constructor to create the individual pairs.

In the code above, we created a comma-separated list of Pair types using the to infix function and passed them to the mapOf() function. We can also create the same map by directly using the Pair constructor for each pair.

As you can see again, sticking with the to infix function has less noise than using the Pair constructor. 

Conclusion

In this tutorial, you learned about some of the cool things you can do with functions in Kotlin. We covered:

  • top-level functions
  • lambda expressions or function literals
  • member functions
  • anonymous functions
  • local or nested functions
  • infix functions

But that's not all! There is still more to learn about functions in Kotlin. So in the next post, you'll learn some advanced uses of functions, such as extension functions, higher-order functions, and closures. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts+!

2017-09-12T14:00:00.000Z2017-09-12T14:00:00.000ZChike Mgbemena

Kotlin From Scratch: More Fun With Functions

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29479

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.  

In the previous article, you learned about packages and basic functions in Kotlin. Functions are at the heart of Kotlin, so in this post we'll look more closely at them. We'll be exploring the following kinds of functions in Kotlin:

  • top-level functions
  • lambda expressions or function literals
  • anonymous functions
  • local or nested functions
  • infix functions
  • member functions

You'll be amazed at all the cool things you can do with functions in Kotlin!

1. Top-Level Functions

Top-level functions are functions inside a Kotlin package that are defined outside of any class, object, or interface. This means that they are functions you call directly, without the need to create any object or call any class. 

If you're a Java coder, you know that we typically create utility static methods inside helper classes. These helper classes don't really do anything—they don't have any state or instance methods, and they just act as a container for the static methods. A typical example is the Collections class in the java.util package and its static methods. 

Top-level functions in Kotlin can be used as a replacement for the static utility methods inside helper classes we code in Java. Let's look at how to define a top-level function in Kotlin. 

In the code above, we defined a package com.chikekotlin.projectx.utils inside a file called UserUtils.kt and also defined a top-level utility function called checkUserStatus() inside this same package and file. For brevity's sake, this very simple function returns the string "online". 

The next thing we'll do is to use this utility function in another package or file.

In the preceding code, we imported the function into another package and then executed it! As you can see, we don't have to create an object or reference a class to call this function.

Java Interoperability

Given that Java doesn't support top-level functions, the Kotlin compiler behind the scenes will create a Java class, and the individual top-level functions will be converted to static methods. In our own case, the Java class generated was UserUtilsKt with a static method checkUserStatus()

This means that Java callers can simply call the method by referencing its generated class, just like for any other static method.

Note that we can change the Java class name that the Kotlin compiler generates by using the @JvmName annotation.

In the code above, we applied the @JvmName annotation and specified a class name UserUtils for the generated file. Note also that this annotation is placed at the beginning of the Kotlin file, before the package definition. 

It can be referenced from Java like this:

2. Lambda Expressions

Lambda expressions (or function literals) are also not bound to any entity such as a class, object, or interface. They can be passed as arguments to other functions called higher-order functions (we'll discuss these more in the next post). A lambda expression represents just the block of a function, and using them reduces the noise in our code. 

If you're a Java coder, you know that Java 8 and above provides support for lambda expressions. To use lambda expressions in a project that supports earlier Java versions such as Java 7, 6, or 5, we can use the popular Retrolambda library

One of the awesome things about Kotlin is that lambda expressions are supported out of the box. Because lambda is not supported in Java 6 or 7, for Kotlin to interoperate with it, Kotlin creates a Java anonymous class behind the scene. But note that creating a lambda expression in Kotlin is quite different than it is in Java.

Here are the characteristics of a lambda expression in Kotlin:

  • It must be surrounded by curly braces {}.
  • It doesn't have the fun keyword. 
  • There is no access modifier (private, public or protected) because it doesn't belong to any class, object, or interface.
  • It has no function name. In other words, it's anonymous. 
  • No return type is specified because it will be inferred by the compiler.
  • Parameters are not surrounded by parentheses ()

And, what's more, we can assign a lambda expression to a variable and then execute it. 

Creating Lambda Expressions

Let's now see some examples of lambda expressions. In the code below, we created a lambda expression without any parameters and assigned it a variable message. We then executed the lambda expression by calling message()

Let's also see how to include parameters in a lambda expression. 

In the code above, we created a lambda expression with the parameter myString, along with the parameter type String. As you can see, in front of the parameter type, there is an arrow: this refers to the lambda body. In other words, this arrow separates the parameter list from the lambda body. To make it more concise, we can completely ignore the parameter type (already inferred by the compiler). 

To have multiple parameters, we just separate them with a comma. And remember, we don't wrap the parameter list in parentheses like in Java. 

However, note that if the parameter types can't be inferred, they must be specified explicitly (as in this example), otherwise the code won't compile.

Passing Lambdas to Functions

We can pass lambda expressions as parameters to functions: these are called "higher-order functions", because they are functions of functions. These kinds of functions can accept a lambda or an anonymous function as parameter: for example, the last() collection function. 

In the code below, we passed in a lambda expression to the last() function. (If you want a refresher on collections in Kotlin, visit the third tutorial in this series) As the name says, it returns the last element in the list.  last() accepts a lambda expression as a parameter, and this expression in turn takes one argument of type String. Its function body serves as a predicate to search within a subset of elements in the collection. That means that the lambda expression will decide which elements of the collection will be considered when looking for the last one.

Let's see how to make that last line of code above more readable.

The Kotlin compiler allows us to remove the function parentheses if the last argument in the function is a lambda expression. As you can observe in the code above, we were allowed to do this because the last and only argument passed to the last() function is a lambda expression. 

Furthermore, we can make it more concise by removing the parameter type.

We don't need to specify the parameter type explicitly, because the parameter type is always the same as the collection element type. In the code above, we're calling last on a list collection of String objects, so the Kotlin compiler is smart enough to know that the parameter will also be a String type. 

The it Argument Name

We can even simplify the lambda expression further again by replacing the lambda expression argument with the auto-generated default argument name it.

The it argument name was auto-generated because last can accept a lambda expression or an anonymous function (we'll get to that shortly) with only one argument, and its type can be inferred by the compiler.  

Local Return in Lambda Expressions

Let's start with an example. In the code below, we pass a lambda expression to the foreach() function invoked on the intList collection. This function will loop through the collection and execute the lambda on each element in the list. If any element is divisible by 2, it will stop and return from the lambda. 

Running the above code might not have given you the result you might have expected. This is because that return statement won't return from the lambda but instead from the containing function surroundingFunction()! This means that the last code statement in the surroundingFunction() won't execute. 

To fix this problem, we need to tell it explicitly which function to return from by using a label or name tag. 

In the updated code above, we specified the default tag @forEach immediately after the return keyword inside the lambda. We have now instructed the compiler to return from the lambda instead of the containing function surroundingFunction(). Now the last statement of surroundingFunction() will execute. 

Note that we can also define our own label or name tag. 

In the code above, we defined our custom label called myLabel@ and then specified it for the return keyword. The @forEach label generated by the compiler for the forEach function is no longer available because we have defined our own. 

However, you'll soon see how this local return problem can be solved without labels when we discuss anonymous functions in Kotlin shortly.

3. Member Functions

This kind of function is defined inside a class, object, or interface. Using member functions helps us to modularize our programs further. Let's now see how to create a member function.

This code snippet shows a class Circle (we'll discuss Kotlin classes in later posts) that has a member function calculateArea(). This function takes a parameter radius to calculate the area of a circle.

To invoke a member function, we use the name of the containing class or object instance with a dot, followed by the function name, passing any arguments if need be.

4. Anonymous Functions

An anonymous function is another way to define a block of code that can be passed to a function. It is not bound to any identifier. Here are the characteristics of an anonymous function in Kotlin:

  • has no name
  • is created with the fun keyword
  • contains a function body

Because we passed a lambda to the last() function above, we can't be explicit about the return type. To be explicit about the return type, we need to use an anonymous function instead.

In the above code, we have replaced the lambda expression with an anonymous function because we want to be explicit about the return type. 

Towards the end of the lambda section in this tutorial, we used a label to specify which function to return from. Using an anonymous function instead of a lambda inside the forEach() function solves this problem more simply. The return expression returns from the anonymous function and not from the surrounding one, which in our case is surroundingFunction().

5. Local or Nested Functions

To take program modularization further, Kotlin provides us with local functions—also known as nested functions. A local function is a function that is declared inside another function. 

As you can observe in the code snippet above, we have two single-line functions: calCircumference() and calArea() nested inside the printCircumferenceAndAread() function. The nested functions can be called only from within the enclosing function and not outside. Again, the use of nested functions makes our program more modular and tidy. 

We can make our local functions more concise by not explicitly passing parameters to them. This is possible because local functions have access to all parameters and variables of the enclosing function. Let's see that now in action:

As you can see, this updated code looks more readable and reduces the noise we had before. Though the enclosing function in this example given is small, in a larger enclosing function that can be broken down into smaller nested functions, this feature can really come in handy. 

6. Infix Functions

The infix notation allows us to easily call a one-argument member function or extension function. In addition to a function being one-argument, you must also define the function using the infix modifier. To create an infix function, two parameters are involved. The first parameter is the target object, while the second parameter is just a single parameter passed to the function. 

Creating an Infix Member Function

Let's look at how to create an infix function in a class. In the code example below, we created a Student class with a mutable kotlinScore instance field. We created an infix function by using the infix modifier before the fun keyword. As you can see below, we created an infix function addKotlinScore() that takes a score and adds to the kotlinScore instance field. 

Calling an Infix Function

Let's also see how to invoke the infix function we have created. To call an infix function in Kotlin, we don't need to use the dot notation, and we don't need to wrap the parameter with parentheses. 

In the code above, we called the infix function, the target object is student, and the double 95.00 is the parameter passed to the function. 

Using infix functions wisely can make our code more expressive and clearer than the normal style. This is greatly appreciated when writing unit tests in Kotlin (we'll discuss testing in Kotlin in a future post).

The to Infix Function

In Kotlin, we can make the creation of a Pair instance more succinct by using the to infix function instead of the Pair constructor. (Behind the scenes, to also creates a Pair instance.) Note that the to function is also an extension function (we'll discuss these more in the next post).

Let's now compare the creation of a Pair instance using both the to infix function and directly using the Pair constructor, which performs the same operation, and see which one is better.

As you can see in the code above, using the to infix function is more concise than directly using the Pair constructor to create a Pair instance. Remember that using the to infix function, 234 is the target object and the String "Nigeria" is the parameter passed to the function. Moreover, note that we can also do this to create a Pair type:

In the Ranges and Collections post, we created a map collection in Kotlin by giving it a list of pairs—the first value being the key, and the second the value. Let's also compare the creation of a map by using both the to infix function and the Pair constructor to create the individual pairs.

In the code above, we created a comma-separated list of Pair types using the to infix function and passed them to the mapOf() function. We can also create the same map by directly using the Pair constructor for each pair.

As you can see again, sticking with the to infix function has less noise than using the Pair constructor. 

Conclusion

In this tutorial, you learned about some of the cool things you can do with functions in Kotlin. We covered:

  • top-level functions
  • lambda expressions or function literals
  • member functions
  • anonymous functions
  • local or nested functions
  • infix functions

But that's not all! There is still more to learn about functions in Kotlin. So in the next post, you'll learn some advanced uses of functions, such as extension functions, higher-order functions, and closures. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts+!

2017-09-12T14:00:00.000Z2017-09-12T14:00:00.000ZChike Mgbemena

What Is the Android Activity Lifecyle?

$
0
0

In my previous post, you learned that Intents let us send messages from one Android component to another. Well, one very important kind of component is an Activity. 

Activities are a fundamental part of Android app development. And it's impossible to understand Activities without also understanding their lifecycles. In this post, you'll learn all about the Activity lifecycle.

Activity Lifecycle

An Activity is a single screen in Android. It is like a window in a desktop app, or a Frame in a Java program. An Activity allows you place all your UI components or widgets together on the screen.

It's important to understand that an Activity has a lifecycle: that is to say that it can be in one of several different states, depending on what is happening with the app and with the user interaction. 

Lifecycle Methods

Let's look more closely at the lifecycle of an Android Activity. Each time the Activity state changes, one of the following lifecycle methods will be called on the Activity class. 

onCreate(): This is called when the Activity is first initialized. You need to implement this method in order to do any initialization specific to your Activity.

onStart(): This is called the first time that the Activity is about to become visible to the user, as the Activity prepares to come to the foreground become interactive. Once this callback finishes, the onResume() method will be called.

onResume(): When the Activity goes into this state, it begins to interacts with the user. The Activity continues in this state till something happen to take focus from the app or Activity (such as an incoming call). When this happens, the onPause() method will be called.

onPause(): This method is used to pause operations that should not happen when the Activity is in paused state. A call to this method indicates that the user is leaving the app. For example, in a music player app, an incoming call will cause the app to transition into a paused state. This should mute or pause the currently playing music. When the user returns to the app, the onResume() method will be called.

onStop(): This method is called when the Activity is no longer visible in the app. It can happen, for example, when another Activity has been loaded and is taking the full screen of the device. When this method is called, the Activity is said to be in a stopped state. In this state, the system either calls the onRestart() to bring back interactivity with Activity. Or it calls the onDestroy() method to destroy the Activity.

onDestroy(): This gets called before the Activity is destroyed. The system calls this method when a user terminates the Activity, or because the system is temporarily destroying the process that contains the Activity to save space. Be sure to free up any resources your Activity has created in this method, or else your app will have a memory leak!

onRestart(): This gets called when an Activity restarts after it had been stopped.

Starting an Activity

Most user interactions with an app cause the active Activity to be changed. So an app transitions between Activities many times during its lifetime.

It's necessary to link Activities together when one Activity needs to start another Activity. To start an Activity, you either use startActivity() or startActivityForResult(). You have to pass an Intent in either case.

Starting an Activity With No Expected Result

startActivity() is used if the newly started Activity does not need to return a result.

The following code snippet shows how to start another Activity using this method:

You can also perform actions such as passing data from one Activity to another. In this case, your current Activity (the calling Activity) wants to pass data a target Activity. This is where Intents come in handy. To learn about using Intents to start an Activity, check out my previous article.

Starting an Activity With a Result

startActivityForResult() is used to start another Activity and expects to get data back from the newly started Activity. In other words, use this when you want to get a result from the target Activity back to the calling Activity, e.g. if the target Activity is collecting some user information in a modal dialog.

You receive the result from the Activity in the onActivityResult(int requestCode, int resultCode, Intent data) method. The result will be returned as an Intent.

Example of Starting an Activity

Here is an example to show how starting an Activity works.

First, you create your MainActivity with your onCreate() method, a layout file, and a request code.

In your onCreate() method, you'll create a new instance of an intent to start your second Activity. 

When you're ready to start that Activity, say in response to a button click, you'll call startActivityForResult(), which will pass the newly created intent and the request code.

Still, in your MainActivity, you need to handle Activity result events. You do this by implementing the onActivityResult()  method. This is how you will receive the result from the other Activity. 

Here's how it should look:

Now go ahead and create your SecondActivity. It should look something like the code below.

Terminating an Activity

Before an Activity terminates, the corresponding lifecycle methods will be called.

The onPause() method should stop all listeners and UI updates. The onStop() method should save the application data. Finally, the onDestroy() method will free up any resources that the Activity has allocated. 

When the user switches back to an app that has been terminated by the system, the onResume() method is called. Based on saved data, it can re-register listeners and trigger UI updates.

Activity Instance State

An Activity needs a way to keep valuable state and user data that it has obtained. These data might be obtained from user input or created while the Activity was not on-screen.

For example, a change of device orientation can cause an Activity to be destroyed and recreated. In such a scenario, you need to make sure to save all Activity state before it is destroyed and reload it again when it is recreated. Otherwise, any data your Activity has at that time can be completely lost.

To save Activity state, you can override the onSaveInstanceState() method. This method is passed a Bundle object as a parameter. A bundle can contain strings, primitive data types, or objects. In this method, simply add any important state data to the bundle. This bundle will be returned to the Activity later so you can restore the Activity state.

To extract the saved state from the bundle and restore it, implement the onRestoreInstanceState() method. This callback is invoked between the onStart() and the onResume() lifecycle methods.

We will look deeper into Activity instance state in a future article.

Conclusion

After following this post, you'll have a good understanding of how an Activity lifecycle works. And you've learned that there are two ways to start an Activity, as well as getting some pointers to how instance state is handled in the Activity lifecycle.

Thanks for reading, and while you're here, check out some of our other posts on coding Android apps.

2017-09-13T14:00:00.000Z2017-09-13T14:00:00.000ZChinedu Izuchukwu

What Is the Android Activity Lifecyle?

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29518

In my previous post, you learned that Intents let us send messages from one Android component to another. Well, one very important kind of component is an Activity. 

Activities are a fundamental part of Android app development. And it's impossible to understand Activities without also understanding their lifecycles. In this post, you'll learn all about the Activity lifecycle.

Activity Lifecycle

An Activity is a single screen in Android. It is like a window in a desktop app, or a Frame in a Java program. An Activity allows you place all your UI components or widgets together on the screen.

It's important to understand that an Activity has a lifecycle: that is to say that it can be in one of several different states, depending on what is happening with the app and with the user interaction. 

Lifecycle Methods

Let's look more closely at the lifecycle of an Android Activity. Each time the Activity state changes, one of the following lifecycle methods will be called on the Activity class. 

onCreate(): This is called when the Activity is first initialized. You need to implement this method in order to do any initialization specific to your Activity.

onStart(): This is called the first time that the Activity is about to become visible to the user, as the Activity prepares to come to the foreground become interactive. Once this callback finishes, the onResume() method will be called.

onResume(): When the Activity goes into this state, it begins to interacts with the user. The Activity continues in this state till something happen to take focus from the app or Activity (such as an incoming call). When this happens, the onPause() method will be called.

onPause(): This method is used to pause operations that should not happen when the Activity is in paused state. A call to this method indicates that the user is leaving the app. For example, in a music player app, an incoming call will cause the app to transition into a paused state. This should mute or pause the currently playing music. When the user returns to the app, the onResume() method will be called.

onStop(): This method is called when the Activity is no longer visible in the app. It can happen, for example, when another Activity has been loaded and is taking the full screen of the device. When this method is called, the Activity is said to be in a stopped state. In this state, the system either calls the onRestart() to bring back interactivity with Activity. Or it calls the onDestroy() method to destroy the Activity.

onDestroy(): This gets called before the Activity is destroyed. The system calls this method when a user terminates the Activity, or because the system is temporarily destroying the process that contains the Activity to save space. Be sure to free up any resources your Activity has created in this method, or else your app will have a memory leak!

onRestart(): This gets called when an Activity restarts after it had been stopped.

Starting an Activity

Most user interactions with an app cause the active Activity to be changed. So an app transitions between Activities many times during its lifetime.

It's necessary to link Activities together when one Activity needs to start another Activity. To start an Activity, you either use startActivity() or startActivityForResult(). You have to pass an Intent in either case.

Starting an Activity With No Expected Result

startActivity() is used if the newly started Activity does not need to return a result.

The following code snippet shows how to start another Activity using this method:

You can also perform actions such as passing data from one Activity to another. In this case, your current Activity (the calling Activity) wants to pass data a target Activity. This is where Intents come in handy. To learn about using Intents to start an Activity, check out my previous article.

Starting an Activity With a Result

startActivityForResult() is used to start another Activity and expects to get data back from the newly started Activity. In other words, use this when you want to get a result from the target Activity back to the calling Activity, e.g. if the target Activity is collecting some user information in a modal dialog.

You receive the result from the Activity in the onActivityResult(int requestCode, int resultCode, Intent data) method. The result will be returned as an Intent.

Example of Starting an Activity

Here is an example to show how starting an Activity works.

First, you create your MainActivity with your onCreate() method, a layout file, and a request code.

In your onCreate() method, you'll create a new instance of an intent to start your second Activity. 

When you're ready to start that Activity, say in response to a button click, you'll call startActivityForResult(), which will pass the newly created intent and the request code.

Still, in your MainActivity, you need to handle Activity result events. You do this by implementing the onActivityResult()  method. This is how you will receive the result from the other Activity. 

Here's how it should look:

Now go ahead and create your SecondActivity. It should look something like the code below.

Terminating an Activity

Before an Activity terminates, the corresponding lifecycle methods will be called.

The onPause() method should stop all listeners and UI updates. The onStop() method should save the application data. Finally, the onDestroy() method will free up any resources that the Activity has allocated. 

When the user switches back to an app that has been terminated by the system, the onResume() method is called. Based on saved data, it can re-register listeners and trigger UI updates.

Activity Instance State

An Activity needs a way to keep valuable state and user data that it has obtained. These data might be obtained from user input or created while the Activity was not on-screen.

For example, a change of device orientation can cause an Activity to be destroyed and recreated. In such a scenario, you need to make sure to save all Activity state before it is destroyed and reload it again when it is recreated. Otherwise, any data your Activity has at that time can be completely lost.

To save Activity state, you can override the onSaveInstanceState() method. This method is passed a Bundle object as a parameter. A bundle can contain strings, primitive data types, or objects. In this method, simply add any important state data to the bundle. This bundle will be returned to the Activity later so you can restore the Activity state.

To extract the saved state from the bundle and restore it, implement the onRestoreInstanceState() method. This callback is invoked between the onStart() and the onResume() lifecycle methods.

We will look deeper into Activity instance state in a future article.

Conclusion

After following this post, you'll have a good understanding of how an Activity lifecycle works. And you've learned that there are two ways to start an Activity, as well as getting some pointers to how instance state is handled in the Activity lifecycle.

Thanks for reading, and while you're here, check out some of our other posts on coding Android apps.

2017-09-13T14:00:00.000Z2017-09-13T14:00:00.000ZChinedu Izuchukwu

Code a Real-Time App With NativeScript: Push Notifications

$
0
0

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we're trying out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we're building a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how easy it is to add push notifications to your NativeScript app with the Firebase Cloud Messaging Service.

What You'll Be Creating

Picking up from the previous tutorial, you'll be adding push notifications to the app. A notification will be triggered when the user breaks their current record or when one of their friends takes first place away from them.

Setting Up the Project

If you have followed the previous tutorial on Firebase, you can simply use the same project and build the features that we will be adding in this tutorial. Otherwise, you can create a new project and copy the starter files into your project's app folder.

After that, you also need to install the geolocation, Google Maps, SQLite and Firebase plugins:

Once installed, you need to configure the Google Maps plugin. You can read the complete instructions on how to do this by reading the section on Installing the Google Maps Plugin in the earlier tutorial.

Next, install the fecha library for formatting dates:

After that, you also need to configure the Firebase plugin. Be sure to read the following sections in the previous tutorial so you can get the app running:

  • Running the Project
  • Setting Up a Firebase App
  • Setting Up a Facebook App
  • Installing the Firebase Plugin
  • Configuring Facebook Integration

Since we've already set up the Firebase plugin in the previous post, there's only a little work that needs to be done to set up push notifications.

First, you have to reconfigure the plugin by going inside the node_modules/nativescript-plugin-firebase directory and running npm run config. This time, select both Facebook authentication and Messaging.

Once that's done, open the firebase.nativescript.json file in the root directory of your project, and make sure that messaging is set to true:

Next, open app/App_Resources/Android/AndroidManifest.xml and add the following services inside the <application>. This enables the Firebase messaging service for the app:

Running the Project

You can run the project by executing tns run android. But since this app will build on the geolocation functionality, I recommend that you use a GPS emulator for quickly setting and changing your location. You can read about how to do so in the section on Running the App in the earlier tutorial.

If you get any build errors, you can remove the platform and rerun the app:

Setting Up Firebase Cloud Functions

You'll be using Firebase Cloud Functions to create a server that will send out the push notifications. This Firebase feature is used to run back-end code whenever a specific event happens within Firebase features that you're using—for example, if there's a new data saved in the real-time database, or when there's a newly added user via the Firebase auth service. For this app, you'll be using HTTP Triggers to send push notifications when the mobile app makes a request to a specific endpoint.

To use Firebase Cloud Functions, you first need to install the firebase-tools package globally:

Next, create a new folder that will house the server code. This should be outside your app folder. Inside that folder, install the firebase-functions package:

Once it's installed, log in to Firebase by running firebase login. This opens a new browser tab that allows you to log in with your Google account. Go through the whole process and agree to all permissions being asked.

Once you're logged in, you can now initialize Firebase functions for a specific Firebase project:

This will ask you whether you want to set up a default project or not. Select the Firebase project that you created in the previous tutorial:

setup firebase functions

Next, you will be asked if you want the dependencies installed. Say yes.

Once the dependencies have all been installed, you should see a firebase.json file and a functions folder inside the directory. The file that you'll be working on is the functions/index.js file. Open that file and you'll see the following:

Uncomment the helloWorld function, and you'll get to see HTTP triggers in action.

Run the following to deploy the function to the cloud:

Once the deployment is complete, it should show you the URL where the function has been deployed:

deploy firebase functions

Access that URL from your browser to see the output "Hello from Firebase!"

Adding the Server Code

Now you're ready to add the code for implementing push notifications. First, you'll add the code for the server component, then the code for the app.

Open the functions/index.js file and empty its contents. 

Creating the Firebase Function

Import the Firebase packages that you'll need:

Create the init_push function. Note that the HTTP trigger is called for any request method, so you have to filter for the request method that you want to process. In this case, we only want to process POST requests. We expect the app to submit the id, steps, and friend_ids as the request data. 

Getting the User and Friends Data

Next, query the Firebase database to check if the user ID exists. This serves as a way to secure the endpoint so not just anyone can trigger push notifications. (Of course, a real app should have much better back-end security, so that users can't spoof their own data or the data of somebody else.) 

If the user does exist, query the database again so it returns all the users. Note that Firebase does not currently provide a way to return records based on an array of IDs, so we'll have to filter the relevant data ourselves:

Next, loop through the results returned from Firebase and create a new array that houses the friends_data. Once this is done, sort the array according to the number of steps by each user. The one with the highest number of steps has the first index.

Construct the Notification Payload

Now we're ready to determine who will receive the notification and construct the notification payload. Who is in first place? Is it the current user or one of the user's friends? Since the current user will also have broken their own record when they break the overall record of whoever's in first place, we just need to check if that record has been broken.

Sending the Notification

Finally, send out the notification:

Updating the App Code

Earlier, you set up the app so that it was able to receive push notifications. This time, you'll be adding code so that your app can process those push notifications and display them to the user. 

Receiving Push Notifications

The first thing that you need to do in order to receive push notifications is to update the firebase.init() function to include a listener for receiving the device token:

This function only executes once, so you have to save the token locally using application settings. Later on, this will allow us to get the device token when the user logs in for the first time. If you still remember from the previous tutorial, we're saving the user's data to Firebase the first time they log in.

Next, you can add the listener for when notifications are received. This will display an alert box which uses the title and body of the message as the content:

Saving the Device Token to Firebase

Firebase Cloud Messaging requires the device token when sending out a push notification to a specific device. Since we're already using Firebase, we'll just save the device token along with the user data. For that, you need to edit the code for saving the user's data to include the device token that we got earlier:

Triggering Push Notifications

Push Notifications are triggered when one of two things happens:

  • when the user breaks their current record
  • when one of the user's friends breaks their record and goes to first place

The first one is easy, so there's really no need for additional setup. But for the second one, you need to do a little work. First, you have to edit the code for when the auth state changes. Right after extracting the friend IDs from the Facebook result, you have to save the friend IDs using application settings.

Next, update the code for when the user stops tracking their walk. Right after the code for constructing the user data for updating the user, get the friend IDs from application settings and include it in the object which contains the request data for triggering the push notification.

Make the request to the Firebase Cloud Functions endpoint that you created earlier. Once a success response is returned, only then will the user's data be updated on the Firebase database. 

Testing Push Notifications

You can test the sending of push notifications by first uninstalling the app from the emulator or device. This allows us to properly trigger the function for getting the device token. Be sure to add console.log to output the device token:

When the device token is outputted in the NativeScript console, copy it, click on the Database menu on your Firebase app dashboard, and add it as a device token to all the users of the app. Use device_token as the property name.

To trigger the push notification, you can use curl to make a POST request to the Firebase Function endpoint:

If you don't have curl installed, you can use the Postman App to send the request. Use the following settings for the request:

  • Request method: POST
  • URL: Your Firebase function endpoint
  • Headers Key: Content-type
  • Headers Value: application/json
  • Body: 

Once triggered, you'll see an output similar to the following:

push notification received

If the app isn't currently open, you'll see the notification in the notification area:

push notification outside app

Conclusion

Congratulations! You've finally completed the fitness app. Over the course of four tutorials, you've built a NativeScript app which uses Google maps, SQLite, Firebase Realtime database, and Firebase Cloud Messaging. Now you have a pretty good foundation for building NativeScript apps which use those technologies.

To learn more about NativeScript or other cross-platform mobile technologies, be sure to check out some of our other courses and tutorials here on Envato Tuts+!

2017-09-14T14:00:00.000Z2017-09-14T14:00:00.000ZWernher-Bel Ancheta

Code a Real-Time App With NativeScript: Push Notifications

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29475

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we're trying out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we're building a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how easy it is to add push notifications to your NativeScript app with the Firebase Cloud Messaging Service.

What You'll Be Creating

Picking up from the previous tutorial, you'll be adding push notifications to the app. A notification will be triggered when the user breaks their current record or when one of their friends takes first place away from them.

Setting Up the Project

If you have followed the previous tutorial on Firebase, you can simply use the same project and build the features that we will be adding in this tutorial. Otherwise, you can create a new project and copy the starter files into your project's app folder.

After that, you also need to install the geolocation, Google Maps, SQLite and Firebase plugins:

Once installed, you need to configure the Google Maps plugin. You can read the complete instructions on how to do this by reading the section on Installing the Google Maps Plugin in the earlier tutorial.

Next, install the fecha library for formatting dates:

After that, you also need to configure the Firebase plugin. Be sure to read the following sections in the previous tutorial so you can get the app running:

  • Running the Project
  • Setting Up a Firebase App
  • Setting Up a Facebook App
  • Installing the Firebase Plugin
  • Configuring Facebook Integration

Since we've already set up the Firebase plugin in the previous post, there's only a little work that needs to be done to set up push notifications.

First, you have to reconfigure the plugin by going inside the node_modules/nativescript-plugin-firebase directory and running npm run config. This time, select both Facebook authentication and Messaging.

Once that's done, open the firebase.nativescript.json file in the root directory of your project, and make sure that messaging is set to true:

Next, open app/App_Resources/Android/AndroidManifest.xml and add the following services inside the <application>. This enables the Firebase messaging service for the app:

Running the Project

You can run the project by executing tns run android. But since this app will build on the geolocation functionality, I recommend that you use a GPS emulator for quickly setting and changing your location. You can read about how to do so in the section on Running the App in the earlier tutorial.

If you get any build errors, you can remove the platform and rerun the app:

Setting Up Firebase Cloud Functions

You'll be using Firebase Cloud Functions to create a server that will send out the push notifications. This Firebase feature is used to run back-end code whenever a specific event happens within Firebase features that you're using—for example, if there's a new data saved in the real-time database, or when there's a newly added user via the Firebase auth service. For this app, you'll be using HTTP Triggers to send push notifications when the mobile app makes a request to a specific endpoint.

To use Firebase Cloud Functions, you first need to install the firebase-tools package globally:

Next, create a new folder that will house the server code. This should be outside your app folder. Inside that folder, install the firebase-functions package:

Once it's installed, log in to Firebase by running firebase login. This opens a new browser tab that allows you to log in with your Google account. Go through the whole process and agree to all permissions being asked.

Once you're logged in, you can now initialize Firebase functions for a specific Firebase project:

This will ask you whether you want to set up a default project or not. Select the Firebase project that you created in the previous tutorial:

setup firebase functions

Next, you will be asked if you want the dependencies installed. Say yes.

Once the dependencies have all been installed, you should see a firebase.json file and a functions folder inside the directory. The file that you'll be working on is the functions/index.js file. Open that file and you'll see the following:

Uncomment the helloWorld function, and you'll get to see HTTP triggers in action.

Run the following to deploy the function to the cloud:

Once the deployment is complete, it should show you the URL where the function has been deployed:

deploy firebase functions

Access that URL from your browser to see the output "Hello from Firebase!"

Adding the Server Code

Now you're ready to add the code for implementing push notifications. First, you'll add the code for the server component, then the code for the app.

Open the functions/index.js file and empty its contents. 

Creating the Firebase Function

Import the Firebase packages that you'll need:

Create the init_push function. Note that the HTTP trigger is called for any request method, so you have to filter for the request method that you want to process. In this case, we only want to process POST requests. We expect the app to submit the id, steps, and friend_ids as the request data. 

Getting the User and Friends Data

Next, query the Firebase database to check if the user ID exists. This serves as a way to secure the endpoint so not just anyone can trigger push notifications. (Of course, a real app should have much better back-end security, so that users can't spoof their own data or the data of somebody else.) 

If the user does exist, query the database again so it returns all the users. Note that Firebase does not currently provide a way to return records based on an array of IDs, so we'll have to filter the relevant data ourselves:

Next, loop through the results returned from Firebase and create a new array that houses the friends_data. Once this is done, sort the array according to the number of steps by each user. The one with the highest number of steps has the first index.

Construct the Notification Payload

Now we're ready to determine who will receive the notification and construct the notification payload. Who is in first place? Is it the current user or one of the user's friends? Since the current user will also have broken their own record when they break the overall record of whoever's in first place, we just need to check if that record has been broken.

Sending the Notification

Finally, send out the notification:

Updating the App Code

Earlier, you set up the app so that it was able to receive push notifications. This time, you'll be adding code so that your app can process those push notifications and display them to the user. 

Receiving Push Notifications

The first thing that you need to do in order to receive push notifications is to update the firebase.init() function to include a listener for receiving the device token:

This function only executes once, so you have to save the token locally using application settings. Later on, this will allow us to get the device token when the user logs in for the first time. If you still remember from the previous tutorial, we're saving the user's data to Firebase the first time they log in.

Next, you can add the listener for when notifications are received. This will display an alert box which uses the title and body of the message as the content:

Saving the Device Token to Firebase

Firebase Cloud Messaging requires the device token when sending out a push notification to a specific device. Since we're already using Firebase, we'll just save the device token along with the user data. For that, you need to edit the code for saving the user's data to include the device token that we got earlier:

Triggering Push Notifications

Push Notifications are triggered when one of two things happens:

  • when the user breaks their current record
  • when one of the user's friends breaks their record and goes to first place

The first one is easy, so there's really no need for additional setup. But for the second one, you need to do a little work. First, you have to edit the code for when the auth state changes. Right after extracting the friend IDs from the Facebook result, you have to save the friend IDs using application settings.

Next, update the code for when the user stops tracking their walk. Right after the code for constructing the user data for updating the user, get the friend IDs from application settings and include it in the object which contains the request data for triggering the push notification.

Make the request to the Firebase Cloud Functions endpoint that you created earlier. Once a success response is returned, only then will the user's data be updated on the Firebase database. 

Testing Push Notifications

You can test the sending of push notifications by first uninstalling the app from the emulator or device. This allows us to properly trigger the function for getting the device token. Be sure to add console.log to output the device token:

When the device token is outputted in the NativeScript console, copy it, click on the Database menu on your Firebase app dashboard, and add it as a device token to all the users of the app. Use device_token as the property name.

To trigger the push notification, you can use curl to make a POST request to the Firebase Function endpoint:

If you don't have curl installed, you can use the Postman App to send the request. Use the following settings for the request:

  • Request method: POST
  • URL: Your Firebase function endpoint
  • Headers Key: Content-type
  • Headers Value: application/json
  • Body: 

Once triggered, you'll see an output similar to the following:

push notification received

If the app isn't currently open, you'll see the notification in the notification area:

push notification outside app

Conclusion

Congratulations! You've finally completed the fitness app. Over the course of four tutorials, you've built a NativeScript app which uses Google maps, SQLite, Firebase Realtime database, and Firebase Cloud Messaging. Now you have a pretty good foundation for building NativeScript apps which use those technologies.

To learn more about NativeScript or other cross-platform mobile technologies, be sure to check out some of our other courses and tutorials here on Envato Tuts+!

2017-09-14T14:00:00.000Z2017-09-14T14:00:00.000ZWernher-Bel Ancheta

Creating Digital Signatures With Swift

$
0
0

The main purpose of a digital signature is to verify the integrity of some information. For a simple example, let's say you had a file that was transferred over the network and you want to check that the entire file was transferred correctly. In that case, you would use a checksum.

“A checksum is a small-sized datum derived from a block of digital data for the purpose of detecting errors which may have been introduced during its transmission or storage” — Wikipedia

How do we derive that checksum? The best option is to use a hash. A hash function will take a variable amount of data and will output a signature of fixed length. For example, we could publish a file along with its hash online. When someone downloads the file, they can then run the same hash function on their version of the file and compare the result. If the hashes are the same then the copied or downloaded file is the same as the original. 

A hash is also a one-way function. Given the resulting output, there is no computationally feasible way to reverse that hash to reveal what the original input was. SHA, Secure Hash Algorithm, is a well-known standard that refers to a group of hash functions that have this property and certain others, which make them useful for digital signatures.

About SHA

SHA has undergone many iterations since it was first published. The first and second iterations, SHA-0 and SHA-1, are now known to have major weaknesses. They are no longer approved for security implementations: they generally shouldn't be used for applications relying on security. However, the SHA-2 family includes versions called SHA-256 and SHA-512, and these are considered secure. "256" and "512" simply refer to the resulting number of bits produced. For this tutorial, we are going to use SHA-512.

Note: Another older popular hash algorithm was MD5. It was also found to have significant flaws.

Using SHA is great for checking if data was accidentally corrupted, but this doesn't prevent a malicious user from tampering with the data. Given that a hash output is of a fixed size, all an attacker needs to do is figure out which algorithm was used given the output size, alter the data, and recompute the hash. What we need is some secret information added to the mix when hashing the data so that the attacker cannot recompute the hash without knowledge of the secret. This is called a Hash Message Authentication Code (HMAC).

HMAC

HMAC can authenticate a piece of information or message to make sure that it originated from the correct sender and that the information has not been altered. A common scenario is when you are talking to a server with a back-end API for your app. It may be important to authenticate to ensure that only your app is allowed to talk to the API. The API would have access control to a specific resource, such as a /register_user endpoint. The client would need to sign its request to the /register_user endpoint in order to successfully use it.

When signing a request, it is common practice to take selected parts of the request, such as POST parameters and the URL, and join them together into a string. Taking agreed-upon elements and putting them in a particular order is called canonicalization. In HMAC, the joined string is hashed along with the secret key to produce the signature. Instead of calling it a hash, we use the term signature in the same way that a person's signature in real life is used to verify identity or integrity. The signature is added back to the client's request as a request header (usually also named “Signature”). A signature is sometimes called a message digest, but the two terms can be used interchangeably.

Over on the API side, the server repeats the process of joining the strings and creating a signature. If the signatures match, it proves that the app must have possession of the secret. This proves the identity of the app. Since specific parameters of the request were also part of the string to be signed, it also guarantees the integrity of the request. It prevents an attacker from performing a man-in-the-middle attack, for example, and altering the request parameters to their liking.

In this code, the CCHmac function takes a parameter for the type of hash function to be used, along with two byte-strings and their lengths—the message and a secret key. For the best security, use at least a 256-bit (32 byte) key generated from a cryptographically secure random number generator. To verify everything is working correctly on the other side, run the example and then input the secret key and message on this remote server and verify that the output is the same.

You can also add a timestamp header to the request and signing string to make the request more unique. This can help the API weed out replay attacks. For example, the API could drop the request if the timestamp is 10 minutes stale.

While it's good to stick to using SHA versions that are secure, it turns out that many of the vulnerabilities of the insecure SHA versions do not apply to HMAC. For this reason, you may see SHA1 being used in production code. However, from a public relations standpoint, it may look bad if you have to explain why, cryptographically speaking, it is okay to use SHA1 in this context. Many of the weaknesses of SHA1 are due to what are called collision attacks. Code auditors or security researchers may expect your code to be collision resistant, regardless of the context. Also, if you write modular code where you can swap out the signing function for a different one in the future, you might forget to update the insecure hash functions. Therefore, we will still stick to SHA-512 as our algorithm of choice.

The HMAC CPU operations are fast, but one disadvantage is the problem of key exchange. How do we let each other know what the secret key is without it being intercepted? For example, maybe your API will need to dynamically add or remove multiple apps or platforms from a whitelist. In this scenario, apps would be required to register, and the secret would need to be passed to the app upon successful registration. You could send the key over HTTPS and use SSL pinning, but even then there is always a worry that somehow the key is stolen during the exchange. The solution to the problem of key exchange is to generate a key that doesn't ever need to leave the device in the first place. This can be accomplished using Public Key Cryptography, and a very popular and accepted standard is RSA.

RSA

RSA stands for Rivest-Shamir-Adleman (the authors of the cryptosystem). It involves taking advantage of the difficulty of factoring the product of two very large prime numbers. RSA can be used for encryption or authentication, although for this example we are going to be using it just for authentication. RSA generates two keys, a public and a private, which we can accomplish using the SecKeyGeneratePair function. When used for authentication, the private key is used to create the signature, while the public key verifies the signature. Given a public key, it is computationally unfeasible to derive the private key.

The next example demonstrates what Apple and all the popular gaming console companies use when distributing their software. Let's say your company creates and delivers a file periodically that users will drag into the file sharing portion of your app in iTunes. You want to make sure the files you send out are never tampered with before being parsed in the app. Your company will hold onto and guard the private key which it uses to sign the files. In the bundle of the app is a copy of the public key used to verify the file. Given that the private key is never transmitted or included in the app, there is no way for a malicious user to be able to sign their own versions of the files (apart from breaking into the company and stealing the private key).

We will use SecKeyRawSign to sign the file. It would be slow to sign the entire contents of the file using RSA, so the hash of the file is signed instead. Additionally, the data passed to RSA should also be hashed before signing because of some security weaknesses.

In this code, we used the CC_SHA512 function to specify SHA-512 again. (RSA, unlike HMAC, becomes insecure if the underlying hash function is insecure.) We are also using 4096 as the key size, which is set by the kSecAttrKeySizeInBits parameter. 2048 is the minimum recommended size. This is to prevent a powerful network of computer systems cracking the RSA key (by cracking I mean factoring the RSA key—also known as factorization of a public modulus). The RSA group has estimated that 2048-bit keys could become crackable some time before 2030. If you want your data to be safe beyond that time then it's a good idea to choose a higher key size like 4096.

The generated keys are in the form of SecKey objects. An issue with Apple's implementation of SecKey is that it does not include all of the essential information that makes up a public key, so it's not a valid DER-encoded X.509 certificate. Adding the missing information back into the format for an iOS or OS X app, even server-side platforms such as PHP, requires some work and involves working in a format known as ASN.1. Fortunately, this was fixed in iOS 10 with new SecKey functions for generating, exporting, and importing keys. 

The code below shows you the other side of the communication—the class that accepts a public key via SecKeyCreateWithData to verify files using the SecKeyRawVerify function.

You could try this out and verify that it works using a simple test like the following:

There is one downside to RSA—key generation is slow! The time to generate the keys is dependent on the size of the key. On newer devices a 4096 bit key takes only a few seconds, but if you run this code on an iPod Touch 4th generation, it may take about a minute. This is fine if you are just generating the keys a few times on a computer, but what happens when we need to generate keys frequently on a mobile device? We can't just lower the key size because that downgrades the security. 

So what's the solution? Well, Elliptic Curve Cryptography (ECC) is an up-and-coming approach—a new set of algorithms based on elliptic curves over finite fields. ECC keys are much smaller in size and faster to generate than RSA keys. A key of only 256-bits offers a very strong level of security! To take advantage of ECC, we don't need to change a lot of code. We can sign our data using the same SecKeyRawSign function and then adjust the parameters to use Elliptic Curve Digital Signature Algorithm (ECDSA).

Tip: For more RSA implementation ideas, you can check out the SwiftyRSA helper library, which is focused on encryption as well as signing messages.

ECDSA

Imagine the following scenario: a chat app lets users send private messages to each other, but you want to make sure that an adversary has not changed the message on its way to the other user. Let's see how you could secure their communication with cryptography. 

First, each user generates a keypair of public and private keys on their mobile device. Their private keys are stored in memory and never leave the device, while the public keys are transmitted to each other. As before, the private key is used for signing the data being sent out, while the public key is used for verifying. If an attacker were to capture a public key during transit, all that could be done is to verify the integrity of the original message from the sender. An attacker can't alter a message because they don't have the private key needed to reconstruct the signature.

There is another pro to using ECDSA on iOS. We can make use of the fact that currently, elliptic curve keys are the only ones that can be stored in the secure enclave of the device. All other keys are stored in the keychain which encrypts its items to the default storage area of the device. On devices that have one, the secure enclave sits separate from the processor, and key storage is implemented in hardware without direct software access. The secure enclave can store a private key and operate on it to produce output that is sent to your app without ever exposing the actual private key by loading it into memory!

I will add support for creating the ECDSA private key on the secure enclave by adding the kSecAttrTokenIDSecureEnclave option for the kSecAttrTokenID parameter. We can start this example with a User object that will generate a keypair upon initialization.

Next, we will create some helper and example functions. As an example, the class will allow a user to initiate a conversation and send a message. Of course, in your app, you would configure this to include your specific networking setup.

Next, we will do the actual signing and verification. ECDSA, unlike RSA, does not need to be hashed prior to signing. However, if you wanted to have a function where the algorithm can be easily swapped without making many changes, then it's perfectly fine to continue to hash the data before signing.

This verifies the message, as well as the “identify” of a specific user since only that user has possession of their private key. 

This doesn't mean that we're connecting the key with who the user is in real life—the problem of matching a public key to a specific user is another domain. While the solutions are out of the scope of this tutorial, popular secure chat apps such as Signal and Telegram allow users to verify a fingerprint or number via a secondary communication channel. Similarly, Pidgin offers a question and answer scheme whereby you ask a question that only the user should know. These solutions open a whole world of debate on what the best approach should be.

However, our cryptographic solution does verify that the message can only have been sent by someone who is in possession of a specific private key.

Let's run a simple test of our example:

OAuth and SSO

Often when working with third-party services, you will notice other high-level terms used for authentication, such as OAuth and SSO. While this tutorial is about creating a signature, I will briefly explain what the other terms mean.

OAuth is a protocol for authentication and authorization. It acts as an intermediary to use someone's account for third-party services and aims to solve the problem of selectively authorizing access to your data. If you log in to service X via Facebook, a screen asks you, for example, if service X is allowed to access your Facebook photos. It accomplishes this by providing a token without revealing the user's password.

Single sign-on, or SSO, describes the flow where an authenticated user can use their same login credentials to access multiple services. An example of this is how your Gmail account works to log in to YouTube. If you had several different services at your company, you may not want to create separate user accounts for all of the different services.

Conclusion

In this tutorial, you saw how to create signatures using the most popular standards. Now that we have covered all the main concepts, let's recap!

  • Use HMAC when you need speed and are sure that the secret key can be exchanged securely.
  • If the keys have to travel across a network, it's better to use RSA or ECDSA.
  • RSA is still the most popular standard. Its verification step is quite fast. Use RSA if the rest of your team is already familiar with or using the standard.
  • If you need to constantly generate keys on a slow device, however, use ECDSA. While the ECDSA verification is a tad slower than RSA verification, that doesn't compare to the many seconds saved over RSA for key generation.

So that's it for digital signatures in Swift. If you have any questions, feel free to drop me a line in the comments section, and in the meantime check out some of our other tutorials on data security and app development in Swift!


2017-09-19T16:00:00.000Z2017-09-19T16:00:00.000ZCollin Stuart

Creating Digital Signatures With Swift

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29287

The main purpose of a digital signature is to verify the integrity of some information. For a simple example, let's say you had a file that was transferred over the network and you want to check that the entire file was transferred correctly. In that case, you would use a checksum.

“A checksum is a small-sized datum derived from a block of digital data for the purpose of detecting errors which may have been introduced during its transmission or storage” — Wikipedia

How do we derive that checksum? The best option is to use a hash. A hash function will take a variable amount of data and will output a signature of fixed length. For example, we could publish a file along with its hash online. When someone downloads the file, they can then run the same hash function on their version of the file and compare the result. If the hashes are the same then the copied or downloaded file is the same as the original. 

A hash is also a one-way function. Given the resulting output, there is no computationally feasible way to reverse that hash to reveal what the original input was. SHA, Secure Hash Algorithm, is a well-known standard that refers to a group of hash functions that have this property and certain others, which make them useful for digital signatures.

About SHA

SHA has undergone many iterations since it was first published. The first and second iterations, SHA-0 and SHA-1, are now known to have major weaknesses. They are no longer approved for security implementations: they generally shouldn't be used for applications relying on security. However, the SHA-2 family includes versions called SHA-256 and SHA-512, and these are considered secure. "256" and "512" simply refer to the resulting number of bits produced. For this tutorial, we are going to use SHA-512.

Note: Another older popular hash algorithm was MD5. It was also found to have significant flaws.

Using SHA is great for checking if data was accidentally corrupted, but this doesn't prevent a malicious user from tampering with the data. Given that a hash output is of a fixed size, all an attacker needs to do is figure out which algorithm was used given the output size, alter the data, and recompute the hash. What we need is some secret information added to the mix when hashing the data so that the attacker cannot recompute the hash without knowledge of the secret. This is called a Hash Message Authentication Code (HMAC).

HMAC

HMAC can authenticate a piece of information or message to make sure that it originated from the correct sender and that the information has not been altered. A common scenario is when you are talking to a server with a back-end API for your app. It may be important to authenticate to ensure that only your app is allowed to talk to the API. The API would have access control to a specific resource, such as a /register_user endpoint. The client would need to sign its request to the /register_user endpoint in order to successfully use it.

When signing a request, it is common practice to take selected parts of the request, such as POST parameters and the URL, and join them together into a string. Taking agreed-upon elements and putting them in a particular order is called canonicalization. In HMAC, the joined string is hashed along with the secret key to produce the signature. Instead of calling it a hash, we use the term signature in the same way that a person's signature in real life is used to verify identity or integrity. The signature is added back to the client's request as a request header (usually also named “Signature”). A signature is sometimes called a message digest, but the two terms can be used interchangeably.

Over on the API side, the server repeats the process of joining the strings and creating a signature. If the signatures match, it proves that the app must have possession of the secret. This proves the identity of the app. Since specific parameters of the request were also part of the string to be signed, it also guarantees the integrity of the request. It prevents an attacker from performing a man-in-the-middle attack, for example, and altering the request parameters to their liking.

In this code, the CCHmac function takes a parameter for the type of hash function to be used, along with two byte-strings and their lengths—the message and a secret key. For the best security, use at least a 256-bit (32 byte) key generated from a cryptographically secure random number generator. To verify everything is working correctly on the other side, run the example and then input the secret key and message on this remote server and verify that the output is the same.

You can also add a timestamp header to the request and signing string to make the request more unique. This can help the API weed out replay attacks. For example, the API could drop the request if the timestamp is 10 minutes stale.

While it's good to stick to using SHA versions that are secure, it turns out that many of the vulnerabilities of the insecure SHA versions do not apply to HMAC. For this reason, you may see SHA1 being used in production code. However, from a public relations standpoint, it may look bad if you have to explain why, cryptographically speaking, it is okay to use SHA1 in this context. Many of the weaknesses of SHA1 are due to what are called collision attacks. Code auditors or security researchers may expect your code to be collision resistant, regardless of the context. Also, if you write modular code where you can swap out the signing function for a different one in the future, you might forget to update the insecure hash functions. Therefore, we will still stick to SHA-512 as our algorithm of choice.

The HMAC CPU operations are fast, but one disadvantage is the problem of key exchange. How do we let each other know what the secret key is without it being intercepted? For example, maybe your API will need to dynamically add or remove multiple apps or platforms from a whitelist. In this scenario, apps would be required to register, and the secret would need to be passed to the app upon successful registration. You could send the key over HTTPS and use SSL pinning, but even then there is always a worry that somehow the key is stolen during the exchange. The solution to the problem of key exchange is to generate a key that doesn't ever need to leave the device in the first place. This can be accomplished using Public Key Cryptography, and a very popular and accepted standard is RSA.

RSA

RSA stands for Rivest-Shamir-Adleman (the authors of the cryptosystem). It involves taking advantage of the difficulty of factoring the product of two very large prime numbers. RSA can be used for encryption or authentication, although for this example we are going to be using it just for authentication. RSA generates two keys, a public and a private, which we can accomplish using the SecKeyGeneratePair function. When used for authentication, the private key is used to create the signature, while the public key verifies the signature. Given a public key, it is computationally unfeasible to derive the private key.

The next example demonstrates what Apple and all the popular gaming console companies use when distributing their software. Let's say your company creates and delivers a file periodically that users will drag into the file sharing portion of your app in iTunes. You want to make sure the files you send out are never tampered with before being parsed in the app. Your company will hold onto and guard the private key which it uses to sign the files. In the bundle of the app is a copy of the public key used to verify the file. Given that the private key is never transmitted or included in the app, there is no way for a malicious user to be able to sign their own versions of the files (apart from breaking into the company and stealing the private key).

We will use SecKeyRawSign to sign the file. It would be slow to sign the entire contents of the file using RSA, so the hash of the file is signed instead. Additionally, the data passed to RSA should also be hashed before signing because of some security weaknesses.

In this code, we used the CC_SHA512 function to specify SHA-512 again. (RSA, unlike HMAC, becomes insecure if the underlying hash function is insecure.) We are also using 4096 as the key size, which is set by the kSecAttrKeySizeInBits parameter. 2048 is the minimum recommended size. This is to prevent a powerful network of computer systems cracking the RSA key (by cracking I mean factoring the RSA key—also known as factorization of a public modulus). The RSA group has estimated that 2048-bit keys could become crackable some time before 2030. If you want your data to be safe beyond that time then it's a good idea to choose a higher key size like 4096.

The generated keys are in the form of SecKey objects. An issue with Apple's implementation of SecKey is that it does not include all of the essential information that makes up a public key, so it's not a valid DER-encoded X.509 certificate. Adding the missing information back into the format for an iOS or OS X app, even server-side platforms such as PHP, requires some work and involves working in a format known as ASN.1. Fortunately, this was fixed in iOS 10 with new SecKey functions for generating, exporting, and importing keys. 

The code below shows you the other side of the communication—the class that accepts a public key via SecKeyCreateWithData to verify files using the SecKeyRawVerify function.

You could try this out and verify that it works using a simple test like the following:

There is one downside to RSA—key generation is slow! The time to generate the keys is dependent on the size of the key. On newer devices a 4096 bit key takes only a few seconds, but if you run this code on an iPod Touch 4th generation, it may take about a minute. This is fine if you are just generating the keys a few times on a computer, but what happens when we need to generate keys frequently on a mobile device? We can't just lower the key size because that downgrades the security. 

So what's the solution? Well, Elliptic Curve Cryptography (ECC) is an up-and-coming approach—a new set of algorithms based on elliptic curves over finite fields. ECC keys are much smaller in size and faster to generate than RSA keys. A key of only 256-bits offers a very strong level of security! To take advantage of ECC, we don't need to change a lot of code. We can sign our data using the same SecKeyRawSign function and then adjust the parameters to use Elliptic Curve Digital Signature Algorithm (ECDSA).

Tip: For more RSA implementation ideas, you can check out the SwiftyRSA helper library, which is focused on encryption as well as signing messages.

ECDSA

Imagine the following scenario: a chat app lets users send private messages to each other, but you want to make sure that an adversary has not changed the message on its way to the other user. Let's see how you could secure their communication with cryptography. 

First, each user generates a keypair of public and private keys on their mobile device. Their private keys are stored in memory and never leave the device, while the public keys are transmitted to each other. As before, the private key is used for signing the data being sent out, while the public key is used for verifying. If an attacker were to capture a public key during transit, all that could be done is to verify the integrity of the original message from the sender. An attacker can't alter a message because they don't have the private key needed to reconstruct the signature.

There is another pro to using ECDSA on iOS. We can make use of the fact that currently, elliptic curve keys are the only ones that can be stored in the secure enclave of the device. All other keys are stored in the keychain which encrypts its items to the default storage area of the device. On devices that have one, the secure enclave sits separate from the processor, and key storage is implemented in hardware without direct software access. The secure enclave can store a private key and operate on it to produce output that is sent to your app without ever exposing the actual private key by loading it into memory!

I will add support for creating the ECDSA private key on the secure enclave by adding the kSecAttrTokenIDSecureEnclave option for the kSecAttrTokenID parameter. We can start this example with a User object that will generate a keypair upon initialization.

Next, we will create some helper and example functions. As an example, the class will allow a user to initiate a conversation and send a message. Of course, in your app, you would configure this to include your specific networking setup.

Next, we will do the actual signing and verification. ECDSA, unlike RSA, does not need to be hashed prior to signing. However, if you wanted to have a function where the algorithm can be easily swapped without making many changes, then it's perfectly fine to continue to hash the data before signing.

This verifies the message, as well as the “identify” of a specific user since only that user has possession of their private key. 

This doesn't mean that we're connecting the key with who the user is in real life—the problem of matching a public key to a specific user is another domain. While the solutions are out of the scope of this tutorial, popular secure chat apps such as Signal and Telegram allow users to verify a fingerprint or number via a secondary communication channel. Similarly, Pidgin offers a question and answer scheme whereby you ask a question that only the user should know. These solutions open a whole world of debate on what the best approach should be.

However, our cryptographic solution does verify that the message can only have been sent by someone who is in possession of a specific private key.

Let's run a simple test of our example:

OAuth and SSO

Often when working with third-party services, you will notice other high-level terms used for authentication, such as OAuth and SSO. While this tutorial is about creating a signature, I will briefly explain what the other terms mean.

OAuth is a protocol for authentication and authorization. It acts as an intermediary to use someone's account for third-party services and aims to solve the problem of selectively authorizing access to your data. If you log in to service X via Facebook, a screen asks you, for example, if service X is allowed to access your Facebook photos. It accomplishes this by providing a token without revealing the user's password.

Single sign-on, or SSO, describes the flow where an authenticated user can use their same login credentials to access multiple services. An example of this is how your Gmail account works to log in to YouTube. If you had several different services at your company, you may not want to create separate user accounts for all of the different services.

Conclusion

In this tutorial, you saw how to create signatures using the most popular standards. Now that we have covered all the main concepts, let's recap!

  • Use HMAC when you need speed and are sure that the secret key can be exchanged securely.
  • If the keys have to travel across a network, it's better to use RSA or ECDSA.
  • RSA is still the most popular standard. Its verification step is quite fast. Use RSA if the rest of your team is already familiar with or using the standard.
  • If you need to constantly generate keys on a slow device, however, use ECDSA. While the ECDSA verification is a tad slower than RSA verification, that doesn't compare to the many seconds saved over RSA for key generation.

So that's it for digital signatures in Swift. If you have any questions, feel free to drop me a line in the comments section, and in the meantime check out some of our other tutorials on data security and app development in Swift!


2017-09-19T16:00:00.000Z2017-09-19T16:00:00.000ZCollin Stuart

Kotlin From Scratch: Advanced Functions

$
0
0

Kotlin is a functional language, and that means functions are front and center. The language is packed with features to make coding functions easy and expressive. In this post, you'll learn about extension functions, higher-order functions, closures, and inline functions in Kotlin.

In the previous article, you learned about top-level functions, lambda expressions, member functions, anonymous functions, local functions, infix functions, and finally member functions in Kotlin. In this tutorial, we'll continue to learn more about functions in Kotlin by digging into:

  • extension functions 
  • higher-order functions
  • closures
  • inline functions

1. Extension Functions 

Wouldn't it be nice if the String type in Java had a method to capitalize the first letter in a String—like ucfirst() in PHP? We could call this method upperCaseFirstLetter()

To realize this, you could create a String subclass which extends the String type in Java. But remember that the String class in Java is final—which means that you can't extend it. A possible solution for Kotlin would be to create helper functions or top-level functions, but this might not be ideal because we then couldn't make use of the IDE auto-complete feature to see the list of methods available for the String type. What would be really nice would be to somehow add a function to a class without having to inherit from that class.

Well, Kotlin has us covered with yet another awesome feature: extension functions. These give us the ability to extend a class with new functionality without having to inherit from that class. In other words, we don't need to create a new subtype or alter the original type. 

An extension function is declared outside the class it wants to extend. In other words, it is also a top-level function (if you want a refresher on top-level functions in Kotlin, visit the More Fun With Functions tutorial in this series). 

Along with extension functions, Kotlin also supports extension properties. In this post, we'll discuss extension functions, and we'll wait until a future post to discuss extension properties along with classes in Kotlin. 

Creating an Extension Function

As you can see in the code below, we defined a top-level function as normal for us to declare an extension function. This extension function is inside a package called com.chike.kotlin.strings

To create an extension function, you have to prefix the name of the class that you're extending before the function name. The class name or the type on which the extension is defined is called the receiver type, and the receiver object is the class instance or value on which the extension function is called.

Note that the this keyword inside the function body references the receiver object or instance. 

Calling an Extension Function

After creating your extension function, you'll first need to import the extension function into other packages or files to be used in that file or package. Then, calling the function is just the same as calling any other method of the receiver type class.

In the example above, the receiver type is class String, and the receiver object is "chike". If you're using an IDE such as IntelliJ IDEA that has the IntelliSense feature, you'd see your new extension function suggested among the list of other functions in a String type. 

IntelliJ IDEA intellisense feature

Java Interoperability

Note that behind the scenes, Kotlin will create a static method. This static method's first argument is the receiver object. So it is easy for Java callers to call this static method and then pass the receiver object as an argument. 

For example, if our extension function was declared in a StringUtils.kt file, the Kotlin compiler would create a Java class StringUtilsKt with a static method upperCaseFirstLetter()

This means that Java callers can simply call the method by referencing its generated class, just like for any other static method. 

Remember that this Java interop mechanism is similar to how top-level functions work in Kotlin, as we discussed in the More Fun With Functions post!

Extension Functions vs. Member Functions

Note that extension functions can't override functions already declared in a class or interface—known as member functions (if you want a refresher on member functions in Kotlin, take a look at the previous tutorial in this series). So, if you have defined an extension function with exactly the same function signature—the same function name and same number, types and order of arguments, regardless of return type—the Kotlin compiler won't invoke it. In the process of compilation, when a function is invoked, the Kotlin compiler will first look for a match in the member functions defined in the instance type or in its superclasses. If there is a match, then that member function is the one that is invoked or bound. If there is no match, then the compiler will invoke any extension function of that type. 

So in summary: member functions always win. 

Let's see a practical example.

In the code above, we defined a type called Student with two member functions: printResult() and expel(). We then defined two extension functions that have the same names as the member functions. 

Let's call the printResult() function and see the result. 

As you can see, the function that was invoked or bound was the member function and not the extension function with same function signature (though IntelliJ IDEA would still give you a hint about it).

However, calling the member function expel() and the extension function expel(reason: String) will produce different results because the function signatures are different. 

Member Extension Functions

You'll declare an extension function as a top-level function most of the time, but note that you can also declare them as member functions. 

In the code above, we declared an extension function exFunction() of ClassB type inside another class ClassA. The dispatch receiver is the instance of the class in which the extension is declared, and the instance of the receiver type of the extension method is called the extension receiver. When there is a name conflict or shadowing between the dispatch receiver and the extension receiver, note that the compiler chooses the extension receiver. 

So in the code example above, the extension receiver is an instance of ClassB—so it means the toString() method is of type ClassB when called inside the extension function exFunction(). For us to invoke the toString() method of the dispatch receiverClassA instead, we need to use a qualified this:

2. Higher-Order Functions 

A higher-order function is just a function that takes another function (or lambda expression) as a parameter, returns a function, or does both. The last() collection function is an example of a higher-order function from the standard library. 

Here we passed a lambda to the last function to serve as a predicate to search within a subset of elements. We'll now dive into creating our own higher-order functions in Kotlin. 

Creating a Higher-Order Function

Looking at the function circleOperation() below, it has two parameters. The first, radius, accepts a double, and the second, op, is a function that accepts a double as input and also returns a double as output—we can say more succinctly that the second parameter is "a function from double to double". 

Observe that the op function parameter types for the function are wrapped in parentheses (), and the output type is separated by an arrow. The function circleOperation() is a typical example of a higher-order function that accepts a function as a parameter.

Invoking a Higher-Order Function

In the invocation of this circleOperation() function, we pass another function, calArea(), to it. (Note that if the method signature of the passed function doesn't match what the higher-order function declares, the function call won't compile.) 

To pass the calArea() function as a parameter to circleOperation(), we need to prefix it with :: and omit the () brackets.

Using higher-order functions wisely can make our code easier to read and more understandable. 

Lambdas and Higher-Order Functions

We can also pass a lambda (or function literal) to a higher-order function directly when invoking the function: 

Remember, for us to avoid naming the argument explicitly, we can use the it argument name auto-generated for us only if the lambda has one argument. (If you want a refresher on lambda in Kotlin, visit the More Fun With Functions tutorial in this series).

Returning a Function

Remember that in addition to accepting a function as a parameter, higher-order functions can also return a function to callers. 

Here the multiplier() function will return a function that applies the given factor to any number passed into it. This returned function is a lambda (or function literal) from double to double (meaning the input param of the returned function is a double type, and the output result is also a double type).  

To test this out, we passed in a factor of two and assigned the returned function to the variable doubler. We can invoke this like a normal function, and whatever value we pass into it will be doubled.

3. Closures

A closure is a function that has access to variables and parameters which are defined in an outer scope. 

In the code above, the lambda passed to the filter() collection function uses the parameter length of the outer function printFilteredNamesByLength(). Note that this parameter is defined outside the scope of the lambda, but that the lambda is still able to access the length. This mechanism is an example of closure in functional programming.

4. Inline Functions

In More Fun With Functions, I mentioned that the Kotlin compiler creates an anonymous class in earlier versions of Java behind the scenes when creating lambda expressions. 

Unfortunately, this mechanism introduces overhead because an anonymous class is created under the hood every time we create a lambda. Also, a lambda that uses the outer function parameter or local variable with a closure adds its own memory allocation overhead because a new object is allocated to the heap with every invocation. 

Comparing Inline Functions With Normal Functions

To prevent these overheads, the Kotlin team provided us with the inline modifier for functions. A higher-order function with the inline modifier will be inlined during code compilation. In other words, the compiler will copy the lambda (or function literal) and also the higher-order function body and paste them at the call site. 

Let's look at a practical example. 

In the code above, we have a higher-order function circleOperation() that doesn't have the inline modifier. Now let's see the Kotlin bytecode generated when we compile and decompile the code, and then compare it with one that has the inline modifier. 

In the generated Java bytecode above, you can see that the compiler called the function circleOperation() inside the main() method.

Let's now specify the higher-order function as inline instead, and also see the bytecode generated.

To make a higher-order function inline, we have to insert the inline modifier before the fun keyword, just like we did in the code above. Let's also check the bytecode generated for this inline function. 

Looking at the generated bytecode for the inline function inside the main() function, you can observe that instead of calling the circleOperation() function, it has now copied the circleOperation() function body including the lambda body and pasted it at its call-site.

With this mechanism, our code has been significantly optimized—no more creation of anonymous classes or extra memory allocations. But be very aware that we'd have a larger bytecode behind the scenes than before. For this reason, it is highly recommended to only inline smaller higher-order functions that accept lambda as parameters. 

Many of the standard library higher-order functions in Kotlin have the inline modifier. For example, if you take a peek at the collection operation functions filter() and first(), you'll see that they have the inline modifier and are also small in size. 

Remember not to inline normal functions which don't accept a lambda as a parameter! They will compile, but there would be no significant performance improvement (IntelliJ IDEA would even give a hint about this).  

The noinline Modifier

If you have more than two lambda parameters in a function, you have the option to decide which lambda not to inline using the noinline modifier on the parameter. This functionality is useful especially for a lambda parameter that will take in a lot of code. In other words, the Kotlin compiler won't copy and paste that lambda where it is called but instead will create an anonymous class behind the scene.  

Here, we inserted the noinline modifier to the second lambda parameter. Note that this modifier is only valid if the function has the inline modifier.

Stack Trace in Inline Functions

Note that when an exception is thrown inside an inline function, the method call stack in the stack trace is different from a normal function without the inline modifier. This is because of the copy and paste mechanism employed by the compiler for inline functions. The cool thing is that IntelliJ IDEA helps us to easily navigate the method-call stack in the stack trace for an inline function. Let's see an example.

In the code above, an exception is thrown deliberately inside the inline function myFunc(). Let's now see the stack trace inside IntelliJ IDEA when the code is run. Looking at the screenshot below, you can see that we are given two navigation options to choose: the Inline function body or the inline function call site. Choosing the former will take us to the point the exception was thrown in the function body, while the latter will take us to the point the method was called.

IntelliJ IDEA stack trace for inline function

If the function was not an inline one, our stack trace would be like the one you might be already familiar with:

IntelliJ IDEA stack trace for normal function

Conclusion

In this tutorial, you learned even more things you can do with functions in Kotlin. We covered:

  • extension functions
  • higher-order functions
  • closures
  • inline functions

In the next tutorial in the Kotlin From Scratch series, we'll dig into object-oriented programming and start learning how classes work in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts+!

2017-09-21T11:00:00.000Z2017-09-21T11:00:00.000ZChike Mgbemena

Kotlin From Scratch: Advanced Functions

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29534

Kotlin is a functional language, and that means functions are front and center. The language is packed with features to make coding functions easy and expressive. In this post, you'll learn about extension functions, higher-order functions, closures, and inline functions in Kotlin.

In the previous article, you learned about top-level functions, lambda expressions, anonymous functions, local functions, infix functions, and finally member functions in Kotlin. In this tutorial, we'll continue to learn more about functions in Kotlin by digging into:

  • extension functions 
  • higher-order functions
  • closures
  • inline functions

1. Extension Functions 

Wouldn't it be nice if the String type in Java had a method to capitalize the first letter in a String—like ucfirst() in PHP? We could call this method upperCaseFirstLetter()

To realize this, you could create a String subclass which extends the String type in Java. But remember that the String class in Java is final—which means that you can't extend it. A possible solution for Kotlin would be to create helper functions or top-level functions, but this might not be ideal because we then couldn't make use of the IDE auto-complete feature to see the list of methods available for the String type. What would be really nice would be to somehow add a function to a class without having to inherit from that class.

Well, Kotlin has us covered with yet another awesome feature: extension functions. These give us the ability to extend a class with new functionality without having to inherit from that class. In other words, we don't need to create a new subtype or alter the original type. 

An extension function is declared outside the class it wants to extend. In other words, it is also a top-level function (if you want a refresher on top-level functions in Kotlin, visit the More Fun With Functions tutorial in this series). 

Along with extension functions, Kotlin also supports extension properties. In this post, we'll discuss extension functions, and we'll wait until a future post to discuss extension properties along with classes in Kotlin. 

Creating an Extension Function

As you can see in the code below, we defined a top-level function as normal for us to declare an extension function. This extension function is inside a package called com.chike.kotlin.strings

To create an extension function, you have to prefix the name of the class that you're extending before the function name. The class name or the type on which the extension is defined is called the receiver type, and the receiver object is the class instance or value on which the extension function is called.

Note that the this keyword inside the function body references the receiver object or instance. 

Calling an Extension Function

After creating your extension function, you'll first need to import the extension function into other packages or files to be used in that file or package. Then, calling the function is just the same as calling any other method of the receiver type class.

In the example above, the receiver type is class String, and the receiver object is "chike". If you're using an IDE such as IntelliJ IDEA that has the IntelliSense feature, you'd see your new extension function suggested among the list of other functions in a String type. 

IntelliJ IDEA intellisense feature

Java Interoperability

Note that behind the scenes, Kotlin will create a static method. This static method's first argument is the receiver object. So it is easy for Java callers to call this static method and then pass the receiver object as an argument. 

For example, if our extension function was declared in a StringUtils.kt file, the Kotlin compiler would create a Java class StringUtilsKt with a static method upperCaseFirstLetter()

This means that Java callers can simply call the method by referencing its generated class, just like for any other static method. 

Remember that this Java interop mechanism is similar to how top-level functions work in Kotlin, as we discussed in the More Fun With Functions post!

Extension Functions vs. Member Functions

Note that extension functions can't override functions already declared in a class or interface—known as member functions (if you want a refresher on member functions in Kotlin, take a look at the previous tutorial in this series). So, if you have defined an extension function with exactly the same function signature—the same function name and same number, types and order of arguments, regardless of return type—the Kotlin compiler won't invoke it. In the process of compilation, when a function is invoked, the Kotlin compiler will first look for a match in the member functions defined in the instance type or in its superclasses. If there is a match, then that member function is the one that is invoked or bound. If there is no match, then the compiler will invoke any extension function of that type. 

So in summary: member functions always win. 

Let's see a practical example.

In the code above, we defined a type called Student with two member functions: printResult() and expel(). We then defined two extension functions that have the same names as the member functions. 

Let's call the printResult() function and see the result. 

As you can see, the function that was invoked or bound was the member function and not the extension function with same function signature (though IntelliJ IDEA would still give you a hint about it).

However, calling the member function expel() and the extension function expel(reason: String) will produce different results because the function signatures are different. 

Member Extension Functions

You'll declare an extension function as a top-level function most of the time, but note that you can also declare them as member functions. 

In the code above, we declared an extension function exFunction() of ClassB type inside another class ClassA. The dispatch receiver is the instance of the class in which the extension is declared, and the instance of the receiver type of the extension method is called the extension receiver. When there is a name conflict or shadowing between the dispatch receiver and the extension receiver, note that the compiler chooses the extension receiver. 

So in the code example above, the extension receiver is an instance of ClassB—so it means the toString() method is of type ClassB when called inside the extension function exFunction(). For us to invoke the toString() method of the dispatch receiverClassA instead, we need to use a qualified this:

2. Higher-Order Functions 

A higher-order function is just a function that takes another function (or lambda expression) as a parameter, returns a function, or does both. The last() collection function is an example of a higher-order function from the standard library. 

Here we passed a lambda to the last function to serve as a predicate to search within a subset of elements. We'll now dive into creating our own higher-order functions in Kotlin. 

Creating a Higher-Order Function

Looking at the function circleOperation() below, it has two parameters. The first, radius, accepts a double, and the second, op, is a function that accepts a double as input and also returns a double as output—we can say more succinctly that the second parameter is "a function from double to double". 

Observe that the op function parameter types for the function are wrapped in parentheses (), and the output type is separated by an arrow. The function circleOperation() is a typical example of a higher-order function that accepts a function as a parameter.

Invoking a Higher-Order Function

In the invocation of this circleOperation() function, we pass another function, calArea(), to it. (Note that if the method signature of the passed function doesn't match what the higher-order function declares, the function call won't compile.) 

To pass the calArea() function as a parameter to circleOperation(), we need to prefix it with :: and omit the () brackets.

Using higher-order functions wisely can make our code easier to read and more understandable. 

Lambdas and Higher-Order Functions

We can also pass a lambda (or function literal) to a higher-order function directly when invoking the function: 

Remember, for us to avoid naming the argument explicitly, we can use the it argument name auto-generated for us only if the lambda has one argument. (If you want a refresher on lambda in Kotlin, visit the More Fun With Functions tutorial in this series).

Returning a Function

Remember that in addition to accepting a function as a parameter, higher-order functions can also return a function to callers. 

Here the multiplier() function will return a function that applies the given factor to any number passed into it. This returned function is a lambda (or function literal) from double to double (meaning the input param of the returned function is a double type, and the output result is also a double type).  

To test this out, we passed in a factor of two and assigned the returned function to the variable doubler. We can invoke this like a normal function, and whatever value we pass into it will be doubled.

3. Closures

A closure is a function that has access to variables and parameters which are defined in an outer scope. 

In the code above, the lambda passed to the filter() collection function uses the parameter length of the outer function printFilteredNamesByLength(). Note that this parameter is defined outside the scope of the lambda, but that the lambda is still able to access the length. This mechanism is an example of closure in functional programming.

4. Inline Functions

In More Fun With Functions, I mentioned that the Kotlin compiler creates an anonymous class in earlier versions of Java behind the scenes when creating lambda expressions. 

Unfortunately, this mechanism introduces overhead because an anonymous class is created under the hood every time we create a lambda. Also, a lambda that uses the outer function parameter or local variable with a closure adds its own memory allocation overhead because a new object is allocated to the heap with every invocation. 

Comparing Inline Functions With Normal Functions

To prevent these overheads, the Kotlin team provided us with the inline modifier for functions. A higher-order function with the inline modifier will be inlined during code compilation. In other words, the compiler will copy the lambda (or function literal) and also the higher-order function body and paste them at the call site. 

Let's look at a practical example. 

In the code above, we have a higher-order function circleOperation() that doesn't have the inline modifier. Now let's see the Kotlin bytecode generated when we compile and decompile the code, and then compare it with one that has the inline modifier. 

In the generated Java bytecode above, you can see that the compiler called the function circleOperation() inside the main() method.

Let's now specify the higher-order function as inline instead, and also see the bytecode generated.

To make a higher-order function inline, we have to insert the inline modifier before the fun keyword, just like we did in the code above. Let's also check the bytecode generated for this inline function. 

Looking at the generated bytecode for the inline function inside the main() function, you can observe that instead of calling the circleOperation() function, it has now copied the circleOperation() function body including the lambda body and pasted it at its call-site.

With this mechanism, our code has been significantly optimized—no more creation of anonymous classes or extra memory allocations. But be very aware that we'd have a larger bytecode behind the scenes than before. For this reason, it is highly recommended to only inline smaller higher-order functions that accept lambda as parameters. 

Many of the standard library higher-order functions in Kotlin have the inline modifier. For example, if you take a peek at the collection operation functions filter() and first(), you'll see that they have the inline modifier and are also small in size. 

Remember not to inline normal functions which don't accept a lambda as a parameter! They will compile, but there would be no significant performance improvement (IntelliJ IDEA would even give a hint about this).  

The noinline Modifier

If you have more than two lambda parameters in a function, you have the option to decide which lambda not to inline using the noinline modifier on the parameter. This functionality is useful especially for a lambda parameter that will take in a lot of code. In other words, the Kotlin compiler won't copy and paste that lambda where it is called but instead will create an anonymous class behind the scene.  

Here, we inserted the noinline modifier to the second lambda parameter. Note that this modifier is only valid if the function has the inline modifier.

Stack Trace in Inline Functions

Note that when an exception is thrown inside an inline function, the method call stack in the stack trace is different from a normal function without the inline modifier. This is because of the copy and paste mechanism employed by the compiler for inline functions. The cool thing is that IntelliJ IDEA helps us to easily navigate the method-call stack in the stack trace for an inline function. Let's see an example.

In the code above, an exception is thrown deliberately inside the inline function myFunc(). Let's now see the stack trace inside IntelliJ IDEA when the code is run. Looking at the screenshot below, you can see that we are given two navigation options to choose: the Inline function body or the inline function call site. Choosing the former will take us to the point the exception was thrown in the function body, while the latter will take us to the point the method was called.

IntelliJ IDEA stack trace for inline function

If the function was not an inline one, our stack trace would be like the one you might be already familiar with:

IntelliJ IDEA stack trace for normal function

Conclusion

In this tutorial, you learned even more things you can do with functions in Kotlin. We covered:

  • extension functions
  • higher-order functions
  • closures
  • inline functions

In the next tutorial in the Kotlin From Scratch series, we'll dig into object-oriented programming and start learning how classes work in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts+!

2017-09-21T11:00:00.000Z2017-09-21T11:00:00.000ZChike Mgbemena

10 Best React Native App Templates of 2017

$
0
0

React Native has been gaining in popularity for one obvious reason: it allows developers to write code across different mobile operating systems. This means that they no longer have to build the same app for iOS and for Android from scratch or specialise in one or the other operating system. Now you can code apps for both platforms with the same powerful JavaScript technologies you use for building web apps.

Pioneered by Facebook and released as open source, React Native is being used by apps such as Facebook, Instagram, Netflix, Airbnb, etc., and can only go from strength to strength.

This is why we’ve pulled together this list of the ten best React Native app templates currently available at CodeCanyon.

1. MStore Pro

One of the most popular React Native app templates available at CodeCanyon, MStore Pro allows users to convert their existing online shop to a mobile store app.

MStore Pro

The template requires no coding skills and is very easy to customise. It is fully integrated with WordPress and WooCommerce, supports PayPal, Stripe, and COD, and allows users to log in with their Facebook account.

Product reviewer jandosul says of the template: 

“This template is exactly what I need. No need to know deeply about Java etc. to make a mobile app. just basics of React Native and some patience.”

2. Currency Converter

If you’ve been looking for a straightforward currency conversion app template, you’ll be very pleased with Currency Converter. The React Native app template allows users to quickly and easily create a currency converter mobile app for any country in the world. 

Currency Converter

The design includes flags of all countries, and the app provides the market rate of each currency. It can also show the conversion rate from one currency to two different currencies at the same time.

3. BeoNews

BeoNews has been gaining in popularity since it hit the market at the end of 2016. Currently one of the best-rated templates in this category, it allows users to convert any of the content on their WordPress site, including video, photos, and blog, into a mobile app. BeoNews stores user data on Firebase and synchronises across devices.

BeoNews

Reviewer bull-tech says of the template: 

“Excellent support! Code is very good and clear. Best WordPress to React Native project on the market.”

4. Tudu

With our demanding jobs and busy family lives, it is no wonder that productivity apps are among the most popular of mobile apps.

Tudu

The cleverly named Tudu React Native app template aims to help developers create a simple, streamlined productivity app that will appeal to a wide cross-section of users. The app features a splash screen, offline storage, swipe actions to complete or remove items, insights charts, and more.

5. Track Money

Track Money is one of the latest React Native app templates to become available on CodeCanyon. It’s designed to help users keep track of both their income streams and expenses.

Track Money

The app allows users to arrange revenue and expenditure by categories and provides good documentation and video tutorials.

6. Real Time Chat

If you’re looking for a template to help you create a messaging app that can be used for membership groups, Real Time Chat could be a good choice for you.

Real Time Chat

This React Native app template allows users to register with their name, email and a password, and lets them start chatting with other members in the group. As with the other templates included here, the Real Time Chat app template includes good documentation and video tutorials.

7. Basic Pairs Memory Game

Basic Pairs Memory Game is a simple memory game for kids with four levels of difficulty. The goal is to test and improve memory by having players find matching tiles.  

Basic Pairs Memory Game

This React Native app template makes it very easy to customise all aspects of the game including the background, images used, text, and colour.

8. BeOnboard

First impressions count. So polish up your app’s initial appearance with BeOnboard, a collection of 18 React Native app templates which are designed to be used with any app in order to explain the app’s functionality to new users. 

BeOnboard

Easy to customise and use, the template aims to provide great user interface and experience.

9. BeoUI

BeoUI is a React Native app template for e-commerce. The template focuses on creating an attractive user interface that is easy to use. 

BeoUI

Its best features are the intro page with parallax effect, its choice of list or two-column views, the product slideshow, its selection of categories, and the profile page where shoppers can track their orders, receive notification, or create a wish list.

10. gikApp

If you need to convert WordPress or Shopify sites into professional and fully functioning mobile apps quickly and easily, the gikApp React Native mobile app template is ideal. 

gikApp

The developers provide step-by-step video instructions, and if you’re not sure the app is right for you, you can take advantage of the free trial on offer and take it for a test run before you buy.

Template user phowr says: 

“I decided to use gikApp to build a mobile for my spa business. Work like a charm. Very smooth, no lag.”

Conclusion

These app templates just scratch the surface of products available at CodeCanyon. So if none of them catch your fancy, there are plenty of other great options there to hold your interest.

And if you want to improve your skills building React Native applications, check out the ever so useful free tutorials we have on offer.

2017-09-25T08:00:00.000Z2017-09-25T08:00:00.000ZNona Blackman

10 Best React Native App Templates of 2017

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29602

React Native has been gaining in popularity for one obvious reason: it allows developers to write code across different mobile operating systems. This means that they no longer have to build the same app for iOS and for Android from scratch or specialise in one or the other operating system. Now you can code apps for both platforms with the same powerful JavaScript technologies you use for building web apps.

Pioneered by Facebook and released as open source, React Native is being used by apps such as Facebook, Instagram, Netflix, Airbnb, etc., and can only go from strength to strength.

This is why we’ve pulled together this list of the ten best React Native app templates currently available at CodeCanyon.

1. MStore Pro

One of the most popular React Native app templates available at CodeCanyon, MStore Pro allows users to convert their existing online shop to a mobile store app.

MStore Pro

The template requires no coding skills and is very easy to customise. It is fully integrated with WordPress and WooCommerce, supports PayPal, Stripe, and COD, and allows users to log in with their Facebook account.

Product reviewer jandosul says of the template: 

“This template is exactly what I need. No need to know deeply about Java etc. to make a mobile app. just basics of React Native and some patience.”

2. Currency Converter

If you’ve been looking for a straightforward currency conversion app template, you’ll be very pleased with Currency Converter. The React Native app template allows users to quickly and easily create a currency converter mobile app for any country in the world. 

Currency Converter

The design includes flags of all countries, and the app provides the market rate of each currency. It can also show the conversion rate from one currency to two different currencies at the same time.

3. BeoNews

BeoNews has been gaining in popularity since it hit the market at the end of 2016. Currently one of the best-rated templates in this category, it allows users to convert any of the content on their WordPress site, including video, photos, and blog, into a mobile app. BeoNews stores user data on Firebase and synchronises across devices.

BeoNews

Reviewer bull-tech says of the template: 

“Excellent support! Code is very good and clear. Best WordPress to React Native project on the market.”

4. Tudu

With our demanding jobs and busy family lives, it is no wonder that productivity apps are among the most popular of mobile apps.

Tudu

The cleverly named Tudu React Native app template aims to help developers create a simple, streamlined productivity app that will appeal to a wide cross-section of users. The app features a splash screen, offline storage, swipe actions to complete or remove items, insights charts, and more.

5. Track Money

Track Money is one of the latest React Native app templates to become available on CodeCanyon. It’s designed to help users keep track of both their income streams and expenses.

Track Money

The app allows users to arrange revenue and expenditure by categories and provides good documentation and video tutorials.

6. Real Time Chat

If you’re looking for a template to help you create a messaging app that can be used for membership groups, Real Time Chat could be a good choice for you.

Real Time Chat

This React Native app template allows users to register with their name, email and a password, and lets them start chatting with other members in the group. As with the other templates included here, the Real Time Chat app template includes good documentation and video tutorials.

7. Basic Pairs Memory Game

Basic Pairs Memory Game is a simple memory game for kids with four levels of difficulty. The goal is to test and improve memory by having players find matching tiles.  

Basic Pairs Memory Game

This React Native app template makes it very easy to customise all aspects of the game including the background, images used, text, and colour.

8. BeOnboard

First impressions count. So polish up your app’s initial appearance with BeOnboard, a collection of 18 React Native app templates which are designed to be used with any app in order to explain the app’s functionality to new users. 

BeOnboard

Easy to customise and use, the template aims to provide great user interface and experience.

9. BeoUI

BeoUI is a React Native app template for e-commerce. The template focuses on creating an attractive user interface that is easy to use. 

BeoUI

Its best features are the intro page with parallax effect, its choice of list or two-column views, the product slideshow, its selection of categories, and the profile page where shoppers can track their orders, receive notification, or create a wish list.

10. gikApp

If you need to convert WordPress or Shopify sites into professional and fully functioning mobile apps quickly and easily, the gikApp React Native mobile app template is ideal. 

gikApp

The developers provide step-by-step video instructions, and if you’re not sure the app is right for you, you can take advantage of the free trial on offer and take it for a test run before you buy.

Template user phowr says: 

“I decided to use gikApp to build a mobile for my spa business. Work like a charm. Very smooth, no lag.”

Conclusion

These app templates just scratch the surface of products available at CodeCanyon. So if none of them catch your fancy, there are plenty of other great options there to hold your interest.

And if you want to improve your skills building React Native applications, check out the ever so useful free tutorials we have on offer.

2017-09-25T08:00:00.000Z2017-09-25T08:00:00.000ZNona Blackman

Concurrency in RxJava 2

$
0
0

A multithreaded app has two or more parts that can run in parallel. This lets the app make better use of the cores inside the device CPU. This lets it get tasks done faster and leads to a smoother and more responsive experience for the user. 

Coding for concurrency in Java can be painful, but thanks to RxJava, it is now much easier to do. With RxJava, you just need to declare the thread on which you want the task to be executed (declaratively) instead of creating and managing threads (imperatively). 

RxJava makes use of Schedulers along with the subscribeOn() and observeOn() concurrency operators to achieve this. In this tutorial, you'll learn about Schedulers, the subscribeOn() operator, the observeOn() operator, and also how to leverage the flatMap() operator to achieve concurrency. But first, let's start with Schedulers in RxJava.

Prerequisites 

To follow along with this tutorial, you should be familiar with:

Check out our other posts to get up to speed on the basics of RxJava and lambda expressions.

Schedulers in RxJava 2

Schedulers in RxJava are used to execute a unit of work on a thread. A Scheduler provides an abstraction to the Android and Java threading mechanism. When you want to run a task and you make use of a Scheduler to execute that task, the Scheduler goes to its thread pool (a collection of threads that are ready for use) and then runs the task in an available thread. 

You can also specify that a task should run in one specific thread. (There are two operators, subscribeOn() and observeOn(), which can be used to specify on which thread from the Scheduler thread pool the task should be executed.)

As you know, in Android, long-running processes or CPU-intensive tasks should not be run on the main thread. If a subscription by an Observer to an Observable is conducted on the main thread, any associated operator will run on the main thread also. In the case of a long-running task (e.g. performing a network request) or a CPU-intensive task (e.g. image transformation), this will block the UI until the task is finished, leading to the awful ANR (Application Not Responding) dialog and the app crashing. These operators can instead be switched over to another thread with the observeOn() operator. 

In the next section, we are going to explore the different kinds of Schedulers and their uses.

Types of Schedulers

Here are some of the types of Schedulers available in RxJava and RxAndroid to indicate the kind of thread to execute tasks on. 

  • Schedulers.immediate(): returns a Scheduler which executes the work instantly in the current thread. Be aware that this will block the current thread, so it should be used with caution. 
  • Schedulers.trampoline(): schedules tasks in the current thread. These tasks are not executed immediately but instead are executed after the thread has finished its current tasks. This is different from Schedulers.immediate() because instead of executing a task immediately, it waits for the current tasks to complete. 
  • Schedulers.newThread(): fires up a new thread and returns a Scheduler to execute the task in the new thread for each Observer. You should be careful using this because the new thread is not reused afterwards but instead is destroyed. 
  • Schedulers.computation(): this gives us a Scheduler that is intended for computationally intensive work such as image transformation, complex calculations, etc. This operation fully employs the CPU cores. This Scheduler uses a fixed thread pool size which is dependent on the CPU cores for optimal usage. You should be careful not to create more threads than the available CPU cores because this can reduce performance. 
  • Schedulers.io(): creates and returns a Scheduler designated for I/O-bound work such as performing asynchronous network calls or reading and writing to the database. These tasks are not CPU-intensive or else make use of Schedulers.computation().
  • Schedulers.single(): creates and returns a Scheduler and executes several tasks sequentially in a single thread. 
  • Schedulers.from(Executor executor): this will create a Scheduler that will execute a task or unit of work on the given Executor
  • AndroidSchedulers.mainThread(): this will create a Scheduler that executes the task on the Android application main thread. This scheduler type is provided by the RxAndroid library. 

The subscribeOn() Operator

By using the subscribeOn() concurrency operator, you specify that the Scheduler should perform the operation in the Observable upstream. It will then push the values to the Observers using the same thread. Now let's see a practical example:

In the code above, we have a static ArrayList which contains some states in Nigeria. We also have a field which is of type Disposable. We get the Disposable instance by calling Observable.subscribe(), and we'll use it later when we call the dispose() method to release any resources that were used. This helps to prevent memory leaks. Our dataSource() method (which can return data from a remote or local database source) will return ObservableOnSubscribe<T>: this is required for us to create our own Observable later using the method Observable.create()

Inside the dataSource() method, we loop through the array, emitting each element to the Observers by calling emitter.onNext(). After each value is emitted, we sleep the thread so as to simulate intensive work being performed. Finally, we call the onComplete() method to signal to the Observers that we are done passing values and they shouldn't expect any more. 

Now, our dataSource() method should not be executed on the main UI thread. But how is this specified? In the example above, we provided Schedulers.newThread() as an argument to subscribeOn(). This means that the dataSource() operation will be run in a new thread. Note also that in the example above, we have just one Observer. If we had multiple Observers, each of them would get its own thread. 

So that we can see this working, our Observer prints out the values it gets in its onNext() method from the Observable

When we run this and view our logcat on Android Studio, you can see that the emissions from the dataSource() method to the Observer happened on the same thread—RxNewThreadScheduler-1—in which the Observer received them. 

Android Studio logcat result showing execution logs on a single thread

If you don't specify the .subscribeOn() method after the Observable.create() method, it will be executed on the current thread—which in our case is the main thread, thereby blocking the app UI. 

Android Studio Logcat showing execution logs on main thread

There are some important details you should be aware of concerning the subscribeOn() operator. You should only have one subscribeOn() in the Observable chain; adding another one anywhere in the chain will have no effect at all. The recommended place to put this operator is as close to the source as possible for the sake of clarity. In other words, place it first in the operator chain. 

The observeOn() Operator

As we saw, the subscribeOn() concurrency operator will instruct the Observable which Scheduler to use to push emissions forward along the Observable chain to the Observers

The job of the observeOn() concurrency operator, on the other hand, is to switch the subsequent emissions over to another thread or Scheduler. We use this operator to control on what thread downstream consumers will receive the emissions. Let's see a practical example. 

In the code above, we used the observeOn() operator and then passed the AndroidSchedulers.mainThread() to it. What we have done is to switch the thread from Schedulers.newThread() to the Android main thread. This is necessary because we want to update the TextView widget, and can only do that from the main UI thread. Note that if you don't switch over to the main thread when you try to update the TextView widget, the app will crash and throw a CalledFromWrongThreadException

Unlike the subscribeOn() operator, the observeOn() operator can be applied multiple times in the operator chain, thereby changing the Scheduler more than once. 

This code has two observeOn() operators. The first one uses the Schedulers.io(), which means that the saveToCache() method will be executed on the Schedulers.io() thread. After that, it then switches over to the AndroidSchedulers.mainThread() where Observers will receive the emissions from the upstream. 

Android Studio logcat result showing logs

Concurrency With the flatMap() Operator

The flatMap() operator is another very powerful and important operator that can be used to achieve concurrency. The definition according to the official documentation is as follows:

Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable.

FlatMap operator diagram

Let's take a look at a practical example that uses this operator: 

This will print the following on Android Studio logcat:

From the result above, you can see that the results we got were in the same order as in the array. Also, the getPopulation() method for each state was processed on the same thread—the main thread. This makes the output result slow because they were processed sequentially on the main thread. 

Now, in order for us to achieve concurrency with this operator, we want the getPopulation() method for each state (emissions from the statesObservable) to be processed on different threads. Doing this will lead to faster processing. We'll use the flatMap() operator to do this because it creates a new Observable for each emission. We then apply the subscribeOn() concurrency operator to each one, passing a Scheduler to it. 

As each emission produces an Observable, the flatMap() operator's job is to merge them together and then send them out as a single stream. 

In the result above, we can observe that each state's getPopulation() method was processed on different threads. This makes the processing much faster, but also observe that the emissions from the flatMap() operator which were received by the Observer are not in the same order as the original emissions upstream. 

Conclusion

In this tutorial, you learned about handling concurrency using RxJava 2: what it is, the different Schedulers available, and how to use the subscribeOn() and observeOn() concurrency operators. I also showed you how to use the flatMap() operator to achieve concurrency. 

In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!

2017-09-26T10:00:00.000Z2017-09-26T10:00:00.000ZChike Mgbemena

What Is the Android Activity Lifecycle?

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29518

In my previous post, you learned that Intents let us send messages from one Android component to another. Well, one very important kind of component is an Activity. 

Activities are a fundamental part of Android app development. And it's impossible to understand Activities without also understanding their lifecycles. In this post, you'll learn all about the Activity lifecycle.

Activity Lifecycle

An Activity is a single screen in Android. It is like a window in a desktop app, or a Frame in a Java program. An Activity allows you place all your UI components or widgets together on the screen.

It's important to understand that an Activity has a lifecycle: that is to say that it can be in one of several different states, depending on what is happening with the app and with the user interaction. 

Lifecycle Methods

Let's look more closely at the lifecycle of an Android Activity. Each time the Activity state changes, one of the following lifecycle methods will be called on the Activity class. 

onCreate(): This is called when the Activity is first initialized. You need to implement this method in order to do any initialization specific to your Activity.

onStart(): This is called the first time that the Activity is about to become visible to the user, as the Activity prepares to come to the foreground become interactive. Once this callback finishes, the onResume() method will be called.

onResume(): When the Activity goes into this state, it begins to interacts with the user. The Activity continues in this state till something happen to take focus from the app or Activity (such as an incoming call). When this happens, the onPause() method will be called.

onPause(): This method is used to pause operations that should not happen when the Activity is in paused state. A call to this method indicates that the user is leaving the app. For example, in a music player app, an incoming call will cause the app to transition into a paused state. This should mute or pause the currently playing music. When the user returns to the app, the onResume() method will be called.

onStop(): This method is called when the Activity is no longer visible in the app. It can happen, for example, when another Activity has been loaded and is taking the full screen of the device. When this method is called, the Activity is said to be in a stopped state. In this state, the system either calls the onRestart() to bring back interactivity with Activity. Or it calls the onDestroy() method to destroy the Activity.

onDestroy(): This gets called before the Activity is destroyed. The system calls this method when a user terminates the Activity, or because the system is temporarily destroying the process that contains the Activity to save space. Be sure to free up any resources your Activity has created in this method, or else your app will have a memory leak!

onRestart(): This gets called when an Activity restarts after it had been stopped.

Starting an Activity

Most user interactions with an app cause the active Activity to be changed. So an app transitions between Activities many times during its lifetime.

It's necessary to link Activities together when one Activity needs to start another Activity. To start an Activity, you either use startActivity() or startActivityForResult(). You have to pass an Intent in either case.

Starting an Activity With No Expected Result

startActivity() is used if the newly started Activity does not need to return a result.

The following code snippet shows how to start another Activity using this method:

You can also perform actions such as passing data from one Activity to another. In this case, your current Activity (the calling Activity) wants to pass data a target Activity. This is where Intents come in handy. To learn about using Intents to start an Activity, check out my previous article.

Starting an Activity With a Result

startActivityForResult() is used to start another Activity and expects to get data back from the newly started Activity. In other words, use this when you want to get a result from the target Activity back to the calling Activity, e.g. if the target Activity is collecting some user information in a modal dialog.

You receive the result from the Activity in the onActivityResult(int requestCode, int resultCode, Intent data) method. The result will be returned as an Intent.

Example of Starting an Activity

Here is an example to show how starting an Activity works.

First, you create your MainActivity with your onCreate() method, a layout file, and a request code.

In your onCreate() method, you'll create a new instance of an intent to start your second Activity. 

When you're ready to start that Activity, say in response to a button click, you'll call startActivityForResult(), which will pass the newly created intent and the request code.

Still, in your MainActivity, you need to handle Activity result events. You do this by implementing the onActivityResult()  method. This is how you will receive the result from the other Activity. 

Here's how it should look:

Now go ahead and create your SecondActivity. It should look something like the code below.

Terminating an Activity

Before an Activity terminates, the corresponding lifecycle methods will be called.

The onPause() method should stop all listeners and UI updates. The onStop() method should save the application data. Finally, the onDestroy() method will free up any resources that the Activity has allocated. 

When the user switches back to an app that has been terminated by the system, the onResume() method is called. Based on saved data, it can re-register listeners and trigger UI updates.

Activity Instance State

An Activity needs a way to keep valuable state and user data that it has obtained. These data might be obtained from user input or created while the Activity was not on-screen.

For example, a change of device orientation can cause an Activity to be destroyed and recreated. In such a scenario, you need to make sure to save all Activity state before it is destroyed and reload it again when it is recreated. Otherwise, any data your Activity has at that time can be completely lost.

To save Activity state, you can override the onSaveInstanceState() method. This method is passed a Bundle object as a parameter. A bundle can contain strings, primitive data types, or objects. In this method, simply add any important state data to the bundle. This bundle will be returned to the Activity later so you can restore the Activity state.

To extract the saved state from the bundle and restore it, implement the onRestoreInstanceState() method. This callback is invoked between the onStart() and the onResume() lifecycle methods.

We will look deeper into Activity instance state in a future article.

Conclusion

After following this post, you'll have a good understanding of how an Activity lifecycle works. And you've learned that there are two ways to start an Activity, as well as getting some pointers to how instance state is handled in the Activity lifecycle.

Thanks for reading, and while you're here, check out some of our other posts on coding Android apps.

2017-09-13T14:00:00.000Z2017-09-13T14:00:00.000ZChinedu Izuchukwu

Concurrency in RxJava 2

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29288

A multithreaded app has two or more parts that can run in parallel. This lets the app make better use of the cores inside the device CPU. This lets it get tasks done faster and leads to a smoother and more responsive experience for the user. 

Coding for concurrency in Java can be painful, but thanks to RxJava, it is now much easier to do. With RxJava, you just need to declare the thread on which you want the task to be executed (declaratively) instead of creating and managing threads (imperatively). 

RxJava makes use of Schedulers along with the subscribeOn() and observeOn() concurrency operators to achieve this. In this tutorial, you'll learn about Schedulers, the subscribeOn() operator, the observeOn() operator, and also how to leverage the flatMap() operator to achieve concurrency. But first, let's start with Schedulers in RxJava.

Prerequisites 

To follow along with this tutorial, you should be familiar with:

Check out our other posts to get up to speed on the basics of RxJava and lambda expressions.

Schedulers in RxJava 2

Schedulers in RxJava are used to execute a unit of work on a thread. A Scheduler provides an abstraction to the Android and Java threading mechanism. When you want to run a task and you make use of a Scheduler to execute that task, the Scheduler goes to its thread pool (a collection of threads that are ready for use) and then runs the task in an available thread. 

You can also specify that a task should run in one specific thread. (There are two operators, subscribeOn() and observeOn(), which can be used to specify on which thread from the Scheduler thread pool the task should be executed.)

As you know, in Android, long-running processes or CPU-intensive tasks should not be run on the main thread. If a subscription by an Observer to an Observable is conducted on the main thread, any associated operator will run on the main thread also. In the case of a long-running task (e.g. performing a network request) or a CPU-intensive task (e.g. image transformation), this will block the UI until the task is finished, leading to the awful ANR (Application Not Responding) dialog and the app crashing. These operators can instead be switched over to another thread with the observeOn() operator. 

In the next section, we are going to explore the different kinds of Schedulers and their uses.

Types of Schedulers

Here are some of the types of Schedulers available in RxJava and RxAndroid to indicate the kind of thread to execute tasks on. 

  • Schedulers.immediate(): returns a Scheduler which executes the work instantly in the current thread. Be aware that this will block the current thread, so it should be used with caution. 
  • Schedulers.trampoline(): schedules tasks in the current thread. These tasks are not executed immediately but instead are executed after the thread has finished its current tasks. This is different from Schedulers.immediate() because instead of executing a task immediately, it waits for the current tasks to complete. 
  • Schedulers.newThread(): fires up a new thread and returns a Scheduler to execute the task in the new thread for each Observer. You should be careful using this because the new thread is not reused afterwards but instead is destroyed. 
  • Schedulers.computation(): this gives us a Scheduler that is intended for computationally intensive work such as image transformation, complex calculations, etc. This operation fully employs the CPU cores. This Scheduler uses a fixed thread pool size which is dependent on the CPU cores for optimal usage. You should be careful not to create more threads than the available CPU cores because this can reduce performance. 
  • Schedulers.io(): creates and returns a Scheduler designated for I/O-bound work such as performing asynchronous network calls or reading and writing to the database. These tasks are not CPU-intensive or else make use of Schedulers.computation().
  • Schedulers.single(): creates and returns a Scheduler and executes several tasks sequentially in a single thread. 
  • Schedulers.from(Executor executor): this will create a Scheduler that will execute a task or unit of work on the given Executor
  • AndroidSchedulers.mainThread(): this will create a Scheduler that executes the task on the Android application main thread. This scheduler type is provided by the RxAndroid library. 

The subscribeOn() Operator

By using the subscribeOn() concurrency operator, you specify that the Scheduler should perform the operation in the Observable upstream. It will then push the values to the Observers using the same thread. Now let's see a practical example:

In the code above, we have a static ArrayList which contains some states in Nigeria. We also have a field which is of type Disposable. We get the Disposable instance by calling Observable.subscribe(), and we'll use it later when we call the dispose() method to release any resources that were used. This helps to prevent memory leaks. Our dataSource() method (which can return data from a remote or local database source) will return ObservableOnSubscribe<T>: this is required for us to create our own Observable later using the method Observable.create()

Inside the dataSource() method, we loop through the array, emitting each element to the Observers by calling emitter.onNext(). After each value is emitted, we sleep the thread so as to simulate intensive work being performed. Finally, we call the onComplete() method to signal to the Observers that we are done passing values and they shouldn't expect any more. 

Now, our dataSource() method should not be executed on the main UI thread. But how is this specified? In the example above, we provided Schedulers.newThread() as an argument to subscribeOn(). This means that the dataSource() operation will be run in a new thread. Note also that in the example above, we have just one Observer. If we had multiple Observers, each of them would get its own thread. 

So that we can see this working, our Observer prints out the values it gets in its onNext() method from the Observable

When we run this and view our logcat on Android Studio, you can see that the emissions from the dataSource() method to the Observer happened on the same thread—RxNewThreadScheduler-1—in which the Observer received them. 

Android Studio logcat result showing execution logs on a single thread

If you don't specify the .subscribeOn() method after the Observable.create() method, it will be executed on the current thread—which in our case is the main thread, thereby blocking the app UI. 

Android Studio Logcat showing execution logs on main thread

There are some important details you should be aware of concerning the subscribeOn() operator. You should only have one subscribeOn() in the Observable chain; adding another one anywhere in the chain will have no effect at all. The recommended place to put this operator is as close to the source as possible for the sake of clarity. In other words, place it first in the operator chain. 

The observeOn() Operator

As we saw, the subscribeOn() concurrency operator will instruct the Observable which Scheduler to use to push emissions forward along the Observable chain to the Observers

The job of the observeOn() concurrency operator, on the other hand, is to switch the subsequent emissions over to another thread or Scheduler. We use this operator to control on what thread downstream consumers will receive the emissions. Let's see a practical example. 

In the code above, we used the observeOn() operator and then passed the AndroidSchedulers.mainThread() to it. What we have done is to switch the thread from Schedulers.newThread() to the Android main thread. This is necessary because we want to update the TextView widget, and can only do that from the main UI thread. Note that if you don't switch over to the main thread when you try to update the TextView widget, the app will crash and throw a CalledFromWrongThreadException

Unlike the subscribeOn() operator, the observeOn() operator can be applied multiple times in the operator chain, thereby changing the Scheduler more than once. 

This code has two observeOn() operators. The first one uses the Schedulers.io(), which means that the saveToCache() method will be executed on the Schedulers.io() thread. After that, it then switches over to the AndroidSchedulers.mainThread() where Observers will receive the emissions from the upstream. 

Android Studio logcat result showing logs

Concurrency With the flatMap() Operator

The flatMap() operator is another very powerful and important operator that can be used to achieve concurrency. The definition according to the official documentation is as follows:

Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable.

FlatMap operator diagram

Let's take a look at a practical example that uses this operator: 

This will print the following on Android Studio logcat:

From the result above, you can see that the results we got were in the same order as in the array. Also, the getPopulation() method for each state was processed on the same thread—the main thread. This makes the output result slow because they were processed sequentially on the main thread. 

Now, in order for us to achieve concurrency with this operator, we want the getPopulation() method for each state (emissions from the statesObservable) to be processed on different threads. Doing this will lead to faster processing. We'll use the flatMap() operator to do this because it creates a new Observable for each emission. We then apply the subscribeOn() concurrency operator to each one, passing a Scheduler to it. 

As each emission produces an Observable, the flatMap() operator's job is to merge them together and then send them out as a single stream. 

In the result above, we can observe that each state's getPopulation() method was processed on different threads. This makes the processing much faster, but also observe that the emissions from the flatMap() operator which were received by the Observer are not in the same order as the original emissions upstream. 

Conclusion

In this tutorial, you learned about handling concurrency using RxJava 2: what it is, the different Schedulers available, and how to use the subscribeOn() and observeOn() concurrency operators. I also showed you how to use the flatMap() operator to achieve concurrency. 

In the meantime, check out some of our other courses and tutorials on the Java language and Android app development!

2017-09-26T10:00:00.000Z2017-09-26T10:00:00.000ZChike Mgbemena

New Course: Code a Swift App With Realm Mobile Database

$
0
0

If you're building a mobile app, you'll almost certainly need to store and retrieve data. And you can't always rely on the user's connectivity, so your app still needs to work even if the user isn't online. 

To find out how to tackle this problem, check out our new course, Code a Swift App With Realm Mobile Database.

What You’ll Learn

In this course, Derek Jensen will show you why the Realm Mobile Database can make your life as an iOS app developer simpler by solving the problem of seamless, always-available, cloud-based data storage. 

Realm Browser with Swift

The Realm Mobile Database is fast and powerful enough to handle your largest applications, while still being easy enough for beginners to pick up without much trouble. Follow along and you'll learn the basics of getting up and running quickly. In a few short lessons, you'll learn how to build an app with Realm Mobile Database.

Watch the Introduction

 

Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 320,000+ photos and 36,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

2017-10-02T07:54:53.000Z2017-10-02T07:54:53.000ZAndrew Blackman

New Course: Code a Swift App With Realm Mobile Database

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-29645

If you're building a mobile app, you'll almost certainly need to store and retrieve data. And you can't always rely on the user's connectivity, so your app still needs to work even if the user isn't online. 

To find out how to tackle this problem, check out our new course, Code a Swift App With Realm Mobile Database.

What You’ll Learn

In this course, Derek Jensen will show you why the Realm Mobile Database can make your life as an iOS app developer simpler by solving the problem of seamless, always-available, cloud-based data storage. 

Realm Browser with Swift

The Realm Mobile Database is fast and powerful enough to handle your largest applications, while still being easy enough for beginners to pick up without much trouble. Follow along and you'll learn the basics of getting up and running quickly. In a few short lessons, you'll learn how to build an app with Realm Mobile Database.

Watch the Introduction

 

Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 320,000+ photos and 36,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

2017-10-02T07:54:53.000Z2017-10-02T07:54:53.000ZAndrew Blackman

How to Pass Data Between Activities With Android Parcelable

$
0
0

Introduction

We often need to pass data between Activities of an Android app. An easy way to do this is with Intent.putExtra(), but if you have a lot of structured data to pass, Parcelable may be a better solution. In this post I'll show you how Parcelable makes it easy to serialize classes for sharing between Activities.

Why Parcelable?

Parcelable is an Android-only Interface. It allows developers to serialize a class so its properties are easily transferred from one activity to another. This is done by reading and writing of objects from Parcels, which can contain flattened data inside message containers. 

Creating the Main Activity and Layout

Our main Activity will handle the collection of the book details. Let's start by setting up our onCreate method.

Next, open activity_main.xml to set up the view's layout and appearance. You will need two text entry fields and a button for submission.

It should look like this:

Now open your main Activity and link the view fields to your activity. You'll have to do it inside your onCreate() method, like this:

To finish off MainActivity, you need to set up an onClickListener. This will be called whenever the Submit button is pressed. When that happens, the details entered are to be collected and sent to the next activity.

Here, you add an onClickListener to the Button instance you retrieved from your Activity layout. This code will be run whenever the Submit button is clicked. 

Note that we simply pass the Book instance to putExtra(). As we'll see later, Parcelable takes care of serializing the book data to a string so it can be passed via the Intent.

Now that the main Activity is complete, we need to create our BookActivity as well as the Book class to hold book info.

Create the Book Class

Let's create a Book class to hold info about each book.

This class needs to implement Parcelable. This will enable the passing of the data from MainActivity to BookActivity.

We'll also add some standard getter functions and a constructor to quickly create an instance of the class.

Write to the Parcel

The writeToParcel method is where you add all your class data to the parcel. This is done in preparation for transfer. This method will be passed a Parcel instance which has a number of write methods that you can use to add each field to the parcel. Watch out: the order in which you write the data is important!

Here is how you do it.

Read Data Back From the Parcel

Just as the write method handles writing the data to be transferred, the constructor is used to read the transferred data back from the serialized Parcel. This method will be called on the receiving activity to collect the data.

Here's how it should look:

The receiving Activity will get the data as a string, and will then call the getParcelableExtra method to start the process of collecting the data. That will trigger the constructor we defined above, which will deserialize the data and create a new Book instance. 

Parcelable.Creator

To complete your Parcelable class, you need to create a Parcelable.Creator instance and assign it to the CREATOR field. The Parcelable API will look for this field when it needs to deserialize an instance of your class that has been passed to another component.

This binds everything together. Its job is simple—it generates instances of your Parcelable class from a Parcel using the parcel data provided. The creator calls the constructor you defined above, passing it a Parcel object, and the constructor initializes the class attributes.

If your Parcelable class will have child classes, you'll need to take some extra care with the describeContents() method. This will let you identify the specific child class that should be created by the Parcelable.Creator. You can read more about how this works on Stack Overflow.

Book Activity and Layout

Now we can complete our app with the book Activity. Go ahead and create a new empty activity called BookActivity. Make the layout look like what I have below.

In the activity_book.xml, you only need two TextView widgets, which will be used to show the title and author of the books.

Now let's set up our activity. Your activity should already look like this:

In this activity, you want to receive the data that was passed from your main Activity and display it on your views. Thus you will retrieve the instances of your TextView using the id of the TextView set in your layout.

Then, of course, you'll call getIntent() because you will be retrieving data in this activity. The data you will be retrieving are collected from the Book class using getParcelableExtra(). Next, you set the values of the TextViews to the data you collected. Here is how it is done.

Build your application and launch it, and you should see the little beauty you have just built.

The completed app

Conclusion

In this post, you've seen how you can easily move objects from one activity to another. You no longer have to retrieve each data field you passed to the Intent object separately, and you don't have to remember the name that you passed each field under. Not only that, but this process is faster than Java's serialize functionality.

In this tutorial, you have learned how to use Parcelable to pass data from one activity to another. You can dive deeper into Parcelable by checking the official documentation

In the meantime, check out some of our other posts about Android app development!

2017-10-02T15:00:00.000Z2017-10-02T15:00:00.000ZChinedu Izuchukwu
Viewing all 1836 articles
Browse latest View live