Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

August 29 2017

12:00

Set Up a React Environment, Part 3

Throughout the rest of this tutorial series, we'll focus on setting up React locally. The first of these approaches is similar to CodePen, where the React scripts were inserted dynamically into your HTML file, before being rendered in the output window.

The only difference here is that we'll be inserting the scripts manually.

Manual React Setup

Start by creating an index.html document and adding a couple of <script> tags for the React and ReactDOM libraries.

The React scripts added are via a CDN, and the particular URIs are recommended by Facebook. If you want to work completely offline, you could download these scripts locally and change the links to be relative.

An element <div id='app'> was added as the location in the DOM our React app will be rendered to. A blank <script> tag was also added, which will be used to add our React code shortly.

This time, however, we won't be able to use JSX as there is no way to convert it to JavaScript at runtime. It has to be compiled ahead of time via a preprocessor such as Babel. We can't use ES6 classes or modules either as these features don't yet have universal browser support.

Let's use the same React component from the CodePen example in part two of this tutorial series, so we can directly compare the two setup methods.

Starting with the <App /> component only:

This is what a React component looks like without JSX. In fact, this is what the JSX code is actually compiled into by Babel.

Let's now add the definitions for the two child components and add a reference to each of them in the top-level <App /> component. I'll also implement the number props from the CodePen example.

Here's what the whole HTML source code now looks like.

Notice how in the <App /> component we can create as many elements as we like by adding more calls to React.createElement(). Also, props are passed into child components via a props JavaScript object, which can then be accessed inside components via the function parameter props.

Open index.html in a browser to see the React output.

Reacts output

I won't go into more details here about React.createElement(), and other non-JSX topics, as the majority of React users choose to write their components using JSX. We'll be using JSX for our React components for the remainder of this tutorial series.

Clearly, the lack of tools such as Babel restricts how easy it is to write React code completely from scratch. There are many other tools we could take advantage of too, such as a bundler that creates a single JavaScript file from all the required React libraries plus our app code. We'll discover a better approach in the next section that's just as easy to set up.

Create React App

To solve the problem of complex manual React setups, Facebook introduced create-react-app, which is a user-friendly way to get started developing with React. It provides you with full build setup but requires no manual configuration at all.

Let's go ahead and install create-react-app. Type the following code in a command-line window.

npm install -g create-react-app

This will install create-react-app globally so you can access it from any directory.

You'll need npm installed to run this command, and Node.js to run create-react-app. As npm comes bundled with Node.js, simply download and install the latest version of Node.js from the official website.

We'll now create a new React app called my-first-components. Note that create-react-app creates the containing folder for your app automatically, so you only need to make sure you're in the directory you want your app folder created in.

Run these commands to create your app and run the start script.

It might take a minute or two for create-react-app to complete installing everything. Once done, enter the npm start command and a new browser window will open and, after a few seconds, your React app will be displayed.

The initial display of the React app

The nice thing about create-react-app is that it includes a mini web server and also watches the files in your app for changes. Whenever a change is made, your app is rebuilt, and the browser window automatically reloads to display your updated app.

During the automated setup process, create-react-app generates several files as well as the following three folders:

  • node_modules
  • public
  • src

A React apps organization

To get a feel for how we create components and connect them together inside a create-react-app generated app, we'll create the same components that we have been working with so far.

The default output of the app suggests we edit App.js as a starting point, so open this file and remove the import calls for the logo and CSS files as we won't be needing these. We can also simplify the <App /> component, and add in our two child components from before.

Your App.js file should now look like this:

Save your changes and create-react-app will automatically update your app in the browser. This results in the same output as before. (Notice it's loaded in the browser via the local web server this time, though.)

Your first React component

Let's make this more modular, though, to be in line with modern best practices for creating React apps. Create two new files inside the src folder named MyFirstComponent.js and MySecondComponent.js.

Inside MyFirstComponent.js, add the following code:

And inside MySecondComponent.js, add similar code:

Finally, we need to update App.js to import both child components as they're now located in separate files:

This approach to structuring your React app is much more modular and portable. It also allows for easier debugging as each component is self-contained inside its own module.

Conclusion

In this tutorial, we've covered two methods for setting up React locally: the manual approach, and using the create-react-app tool from Facebook.

Creating a React app manually from scratch and inserting the script dependencies directly inside the index.html file is pretty inefficient. As your app scales, and as different versions of your scripts are released, manually updating the scripts will quickly become unmanageable. On top of that, we can't use ES6 features, or write our components in JSX!

Using create-react-app, on the other hand, is a very smooth process. It's installed and initialized with a couple of commands. Once running, create-react-app rebuilds your app and updates the browser window every time you edit any project files. This is a really nice workflow when making a lot of minor changes, as it helps to speed up app development.

In the next tutorial, we'll create a React app from scratch that uses Webpack and Babel to bundle and process our app into a single JavaScript file. Unlike create-react-app, where everything is done for you, we'll be manually configuring all the setup files, and we'll discuss why you'd choose this approach.

11:08

New Course: Get Started With Phoenix

If you want to learn about a rising web framework, you should check out Phoenix, a new framework for the Elixir language. With a server-side MVC pattern, it's similar to other web frameworks like Ruby on Rails or the Python framework Django, but it also contains powerful new ideas to make web development easier and more effective.

Our new course, Get Started With Phoenix, is the perfect introduction to this exciting framework. In this post, you'll get a quick introduction to the course and be able to view some free sample lessons.

Get Started With Phoenix

What You’ll Learn

In this course, instructor Markus Mühlberger will show you how to use the Phoenix framework and give you an in-depth introduction to its key architectural concepts. 

You'll build a web app right through to deployment, and along the way you'll learn about how Phoenix handles template rendering, asset compilation, database integration, WebSockets, testing, and more!

Here are some free lessons from this course, as a preview of what you can expect:

The Phoenix 1.3 Architecture

With version 1.3, the architecture of the Phoenix framework has changed quite a bit. Whether this is your first look at Phoenix or you're updating your knowledge from a previous version, in this video you'll get a look at the core principles of the framework architecture. You'll also learn about some differences from earlier versions.

 

Endpoints, Routing, and Pipelines

In this video, you'll learn about the entry points to your application, "endpoints", and what it takes to get a request through to the controller that will process it.

 

Working With Controllers

Controllers handle requests. In this video, you'll learn you how controllers work and what functionality they bring with them.

 

Take the Course

The full course contains 12 more videos taking you through every aspect of the Phoenix framework. 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 200,000+ photos and 26,000+ design assets and templates. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

August 28 2017

15:00

Why MVC Might Not Be the Best Pattern for Cocoa Apps

MVC stands for Model-View-Controller, and it's a widespread architectural pattern for software development. It's the de facto design pattern for Cocoa development, and it has been for many, many years. Most of us can't imagine building applications without it. Both UIKit (iOS) and AppKit (macOS) make frequent use of MVC. It almost seems as if we don't have another option to build applications for iOS, tvOS, macOS, and watchOS.

Even if you're unfamiliar with the Model-View-Controller pattern, if you have the ambition to develop applications for one of Apple's platforms, you need to learn how views (iOS) and windows (macOS) relate to controllers and which role the model plays in a typical Cocoa application. Fortunately, MVC is easy to learn.

In this short series, I explain what MVC is, what it looks like in a typical Cocoa application, and why it may not be the best solution for Cocoa developers.

1. An Example

Let me show you what the MVC pattern looks like in a typical Cocoa application. The example I'll be showing you focuses on iOS, but everything we discuss also applies to tvOS, macOS, and watchOS. Open Xcode and create a new iOS project based on the Single View Application template.

Setting Up the Project

Name the project MVC, and set Language to Swift and Devices to iPhone. I'm using Xcode 8 for this tutorial. The project's configuration options may look a bit different if you're using Xcode 9.

Configuring the Project

As the name implies, the Model-View-Controller pattern defines three components, the model, the view, and the controller. Let me show you where you can find these components in a typical iOS project.

Controllers

The controllers of an iOS application are view controllers, instances of the UIViewController class or a subclass thereof. The UIViewController class is defined in the UIKit framework. Because we chose the Single View Application template when we set up the project, Xcode created a controller for us to start with, the ViewController class, defined in ViewController.Swift. It inherits from the UIViewController class.

As the name implies, a UIViewController instance is responsible for controlling a view, an instance of the UIView class. Every view controller in an iOS project keeps a strong reference to a view, another component of the Model-View-Controller pattern. The UIView class is also defined in the UIKit framework.

Views

We can find the view component in the main storyboard of the project. Open Main.storyboard in the Project Navigator on the left and inspect the View Controller Scene. The scene contains a view controller, an instance of the ViewController class, and it manages a UIView instance.

Exploring the Main Storyboard of the Project

Select View in the storyboard on the left and open the Identity Inspector on the right. The Class field of the view is set to UIView. In an iOS application, views are typically instances of UIKit's UIView class or a subclass thereof.

View Is Instance of UIView Class

Models

Thus far we've explored the controller layer and the view layer. But where can we find the model layer of the project? The model is almost always specific to the project you're working on, and it's up to you to define, implement, and use the model of the project. I write model, but you usually have multiple models, depending on the complexity of your project.

Let's add the final piece of the MVC puzzle by creating a model. Create a new Swift file and name it Person.swift.

Create a New Swift File

Select Person.swift in the Project Navigator on the left and define a structure named Person. We define three properties: 

  • firstName of type String
  • lastName of type String
  • age of type Int

You now have a model you can use in your project. Let's keep it simple and define a property, person, of type Person? in the ViewController class. We create a Person instance in the view controller's viewDidLoad() method and assign it to the person property.

What we see in this example is very common in Cocoa applications powered by the Model-View-Controller pattern. The view controller owns and manages the model, and it uses the model to populate its view. In a more complex application, you load the model's data from a persistent store or fetch it from a remote back end.

Let's define an outlet for a UILabel instance in the view controller and, in the main storyboard, add a label to the View Controller Scene.

Adding a Label to the View Controller Scene

In the view controller's viewDidLoad() method, we safely unwrap the value stored in the person property and use its data to set the text property of the UILabel instance.

The result isn't very surprising if you're familiar with Cocoa development. This is what we end up with.

MVC in Action

2. What Is Model-View-Controller?

The Model-View-Controller pattern is easy to understand and pick up. Despite its simplicity, you can find a wide range of flavors of the MVC pattern. MVC only offers a basic blueprint that can be modified to the platform it is used on. 

The Model-View-Controller pattern you're familiar with on iOS, tvOS, macOS, and watchOS differs in subtle ways from the original definition. While the differences compared with the original definition are subtle, they have a significant impact on the code you write as well as on the maintainability of the project.

Smalltalk

The Model-View-Controller pattern is an old design pattern. It made its first appearance in the 1970s in Smalltalk. The pattern was conceived by Trygve Reenskaug. Over the years, the Model-View-Controller pattern made its way into many languages and frameworks, including Java, Rails, and Django.

I mentioned earlier that the MVC pattern breaks applications up into three distinct components: model, view, and controller. The original implementation of the pattern defines that the view is responsible for displaying the model's data to the user. The user interacts with the application through the view layer. The controller is in charge of handling user interaction and manipulating the model's data as a result. The view visualizes these changes to the user. As illustrated in the below diagram, the model plays a key role in the MVC pattern as it was designed by Reenskaug.

MVC as Defined by Trygve Reenskaug

MVC and Cocoa

The implementation we use in Cocoa development differs from Reenskaug's original design. Take a look at the below diagram to better understand what these differences entail.

MVC Cocoa Implementation

As I mentioned earlier, the view and the controller share a close relationship. In a typical iOS application, a controller holds a strong reference to the view it manages. The view is a dumb object that knows how to display data and respond to user interaction. The result is a highly reusable component.

The controller plays a vital role in Cocoa applications powered by the Model-View-Controller pattern. It takes over some of the tasks of the model in Reenskaug's original MVC implementation. The view and the model don't communicate directly with one another. Instead, the model is usually owned by the controller, which it uses to configure and populate the view it manages.

I hope you can see the subtle differences between Reenskaug's original implementation in Smalltalk and the Cocoa implementation we have become accustomed to. The differences are minor, but, as I'll discuss in a moment, the impact they have is important.

3. The Good: Separation of Concerns and Reusability

Before we take a look at the problems MVC introduces, I'd like to show you why the Model-View-Controller pattern has become such a popular and widespread pattern in software development. The Model-View-Controller pattern we use in Cocoa development has a number of clear benefits it inherited from Reenskaug's original implementation.

The most obvious advantage of the Model-View-Controller pattern is a separation of concerns. The view layer, for example, is responsible for presenting data to the user. The model and controller layers are not concerned with data presentation. But if you've been using MVC in a Cocoa project, then you know that this isn't always true. I'll talk more about that in a moment.

A direct benefit of this separation of concerns is reusability. Each of the components of the Model-View-Controller pattern is focused on a specific task, which means that the building blocks of an MVC application are often easy to reuse. It also allows for these components to be loosely coupled, increasing their reusability. This isn't true for every component, though. In a Cocoa project, for example, controllers are often specific to the application and not good candidates for reuse.

The views and models of a project, however, are highly reusable if designed correctly. Table and collection views, for example, are UIView subclasses that are used in millions of applications. Because a table view delegates user interaction to another object and asks a data source for the data it needs to display, it can focus exclusively on data presentation and user interaction.

4. The Bad: Massive View Controllers

Most developers quickly grasp what the Model-View-Controller pattern brings to the table and how it should be implemented. Unfortunately, the Model-View-Controller pattern also has an ugly side. I already wrote about reusability and separation of concerns. I'm sure I don't need to convince you of these benefits. A table view is highly reusable and incredibly performant. Developers can use standard UIKit components in their applications without any need for subclassing or customization.

Hitting the Limits of MVC

But that's only part of the story. You know when you're starting to hit the limits of MVC when massive view controllers have sneaked into your project. It's time for change when you're ploughing through hundreds or thousands of lines of code to find that one method you're looking for. 

Dumping It in the Controller

Most developers know what goes into the view and model layers of a typical Cocoa application powered by the Model-View-Controller pattern. But which component is responsible for formatting the data that's displayed to the user? Remember that views are supposed to be dumb and reusable. The view shouldn't need to format data. Right? It should only know how to present data and respond to user interaction. Should the model be concerned with data formatting?

And what about networking? That's certainly not the task of the view. Should it be delegated to the model? That doesn't sound right. Why don't we slip that piece of code into the controller. It doesn't feel right, but it'll do for now.

After many lines of code, you end up with a controller that is ready to burst and a nightmare to test. Testing? I hear you. I wouldn't want to test a view controller suffering from massive view controller syndrome either.

5. A Better Solution

You started with good intentions, but you ended up with a project that has a collection of overweight controllers that are difficult to manage and maintain. You're not looking forward to adding new features to the project you're working on because opening up those view controllers makes you sick in your stomach. Does this sound familiar?

It's important to realize that this is a common scenario. Many developers hit the limits of the Model-View-Controller pattern and realize they need something better. Chances are that you've already been looking at several alternatives, such as MVP (Model-View-Presenter) or MVVM (Model-View-ViewModel).

In the next installment of this series, I'll zoom in on the Model-View-ViewModel pattern. It will feel strangely familiar if you've already worked with the Model-View-Controller pattern. But the Model-View-ViewModel pattern brings a few improvements to the table that work very well for Cocoa development.

And while you're waiting, check out some of our other posts on Cocoa app development!

  • Swift
    What's New in Swift 4
    Patrick Balestra
  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz
  • iOS SDK
    Faster Logins With Password AutoFill in iOS 11
    Patrick Balestra

13:00

Set Up a React Environment, Part 2

If you are new to React then, understandably, you just want to get coding, and play around with some simple components to see how React works. You really don't want to have to wade through a lengthy setup process in the first instance.

In this tutorial I'll show you how to begin coding with React in seconds, almost completely removing the setup process! You'll be using CodePen, an online code editor, that enables you to begin writing React code instantly.

A useful side effect of using online code editors is that you can easily share your work with others via a unique URL. Anything you create can also be searched for by other developers looking for React-based examples.

Let's take a look at CodePen and see just how easy it is to set up React and start coding your first app!

CodePen

CodePen gives you access to three windows to edit HTML, CSS, and JavaScript, plus another window to render output. You can use CodePen completely for free, and don't even need to register for an account to share your work. However, if you use the service regularly, you might want to consider opening an account so you can fill out a profile and begin to build up a portfolio.

Every new creation in CodePen is called a 'pen'. Go to the homepage and click the large Create button at the top right of the screen, and then New Pen from the dropdown menu.

Create a new CodePen

Depending on your default settings, the three editors will either be on the left/right side of the main window or laid out across the top in a single row.

The main window

The CodePen output window is updated automatically every time you type in any one of the editor windows. This is optional and can be disabled via the pen's settings.

Configuring Settings

Before we can write any React code, we need to import the necessary library scripts and set up our JavaScript processor. We'll be using JSX inside our React components, as well as some features of ES6, so to be sure the CodePen JavaScript editor can interpret our code, we need a tool that will take our JSX and ES6 code and compile it down to standard JavaScript that all browsers can run.

We'll be using Babel as our JavaScript compiler, so you'll be able to safely use all the latest features of JavaScript without having to worry about browser compatibility. The added support for JSX compilation is a real bonus as it means we only need to use one tool.

To enable Babel in CodePen, we need to configure our pen's settings. Click the Settings button in the top right menu, and then on JavaScript in the Pen Settings dialog box that appears. We can also add the required React libraries here too.

Click on the Quick-add dropdown and select React from the list. Notice that React is added to the first input box with the full path to the library specified. Click the drop down again to add React DOM. This is needed as we're rendering our React components to the browser DOM.

Finally, under the JavaScript Preprocessor dropdown, select Babel. Your Pen Settings dialog should now look similar to this:

Pen Settings Dialog

The exact versions of React, and React DOM scripts, may be slightly different on your screen as CodePen will inevitably update to the latest version from time to time.

Click Close to return to the main CodePen interface. Notice that next to the JS label in the JavaScript editor window, an additional (Babel) label has been added as a reminder that the JavaScript will be passed through the Babel compiler before it is executed in the browser.

Our First React App

In the HTML CodePen editor window, add a single <div id="app"> element. This serves as an empty placeholder our React app can use to render out our component.

We don't need to add much HTML manually as React handles adding and updating DOM elements for us. We won't be adding any CSS to our pen either, so feel free to rearrange the windows so that the JavaScript editor and output window have more space available.

CodePen Editor

In the JavaScript editor window, enter the following code to add our first component.

This is pretty much the most basic version of a component possible in React. We used an ES6 class to extend the core React component class, which implements a render() method and returns a HTML element.

To display our component, we need to call the ReactDOM.render() method:

The first argument is the React component you want to render, and the second specifies which DOM element to render to.

Creating a React Component

Let's now create another couple of React components. First, add this snippet to the HTML window:

Now add another component definition to the JavaScript window:

The second component is very similar to the first one, and we render it out to the div element with id of app2 with another call to ReactDOM.render().

However, it's not very efficient to render out individual components this way. The currently accepted approach is to define a top-level component such as <App />, which contains all other components in your React app. Then, all you need is a single call to RenderDOM.render(), rather than a separate call for each component.

So let's refactor our very simple React app to make use of this top-level component approach.

Firstly, remove the <div id="app2> element as we only need a single element to 'mount' our React app to. Then, add an <App /> component definition:

Now, our React app is entirely self-contained via a single top-level component. Notice that it's comprised of HTML elements and React components. This makes it very easy to structure your app however you want.

Finally, remove all ReactDOM.render() methods and replace with a single call:

Replacing ReactDOMrender Methods

Now, what if we wanted to add some information to <MyFirstComponent /> and <MySecondComponent /> but didn't want to necessarily specify it inside the component definitions? We can do this by passing down information to child components from parent components using HTML attribute like syntax. This is know as props in React.

Let's demonstrate this by passing down numbering information to our two nested components. Change the <App /> definition to be:

We've added two number props which will be passed down to each child component and made available via a JavaScript object. Inside the component definitions, we can access the props via the props object as follows:

The final state of the code

Let's quickly recap on how easy it was to start coding with React using CodePen.

Firstly, we opened a new pen and configured the settings to add the React and ReactDOM script dependencies. We also added the JavaScript Babel preprocessor to compile our JSX and ES6 code down to standard JavaScript.

Then, it was just a simple case of adding our React components to the JavaScript editor. Finally, to get our components to display in the output window, we inserted a <div> element as a mounting point for our React app in the HTML editor window.

Conclusion

Using CodePen, you can get a React component outputted to the screen within just a couple of minutes! However, it does have some limitations.

Modern React best practices for React development recommend a modular approach, with each component in a separate file. You can't do this with the basic version of CodePen.

Also, because the CodePen output window is embedded inside an iframe element, you don't have access to the browser React developer tools, which is an important consideration as your apps get more complex.

For beginners, though, and for quickly testing out new ideas for simple apps, CodePen is a great tool for React development. You could also use it to create an online portfolio, or as your own mini-library of React components ready to paste into other projects. There are plenty of other online code editors similar to CodePen such as JSFiddle, JS Bin, and many others.

In the next tutorial, we'll focus on setting up React apps locally.

12:00

Set Up a React Environment, Part 1

React is a JavaScript library for building user interfaces (UI). It's maintained and developed by Facebook, and is one of the most popular tools for creating web apps today.

However, it's had a bit of a reputation for not being very user friendly to set up a React app, particularly for beginners. The problem stems from when React first became popular, and the standard method of creating a React app involved complex manual configuration of a whole host of setup files.

A lot of tutorials intended to help beginners get started with React introduced different approaches, and tools, to set up a working app. Even with subtle differences between suggested build methods, confusion was inevitable.

To be able to successfully set up a React app via manual configuration requires a good understanding of multiple different technologies.

The technologies used with React

This flexibility in setup is actually a great thing. You have complete freedom to choose the specific tools you want to build your React app, and configure them exactly as required.

Once comfortable with these tools, you'll have the confidence to use them to their full potential and create in-depth complex apps. Until then, there still remains an entry barrier to a lot of developers who haven't necessarily got experience with the command-line tools needed to create React apps.

To help alleviate this frustration, this tutorial series focuses on various methods for setting up React apps. We'll start with the most basic approach and then build up to more complex setups. Let's kick things off, though, by clarifying in more detail the types of React setup we'll be covering.

What We'll Be Covering

By the end of this tutorial series, you'll be able to set up React apps in four main ways:

  • using an online code editor (CodePen)
  • basic manual setup, without Node.js or npm
  • using create-react-app
  • full manual setup and configuration

The first method demonstrates how to use an online code editor such as CodePen to set up a React app very quickly. Using this method, you'll be coding your first app literally in seconds!

Then, we'll move on to setting up React in a local development environment, starting with directly adding scripts to an HTML file using no build tools whatsoever. The next two setup methods focus on how you'd set up a typical React app in your day-to-day development.

As you'll see, using the create-react-app tool makes it extremely easy to spin up React apps with just a single command! Finally, we cover how to set up a React app via the command line completely from scratch, the old-school way.

Each setup method has its place, and there's no single 'better' approach, just alternatives depending on your needs.

React is a fantastic library to build web apps with, and it's a lot of fun too! Let's take a look now at the tutorial prerequisites to make sure you're up to speed.

Prerequisites

The simplest method for setting up a React app requires nothing more than an internet connection. However, as we progress to more complex setups, we'll be moving towards setting up a React app completely from scratch. Therefore, some knowledge of the following topics is recommended.

Command Line

Windows, macOS, and Linux all provide access to command-line tools. These are used heavily in modern web development for completing complex tasks quickly and efficiently. If you don't have any experience working with the command line to perform operations such as managing files/folders, installing tools, running scripts, and so on, then it would be worth your time at least learning the basics.

Node.js and NPM

If you've been doing web development for any amount of time then chances are you've at least heard of Node.js and npm. Node.js was originally created to run JavaScript on the server but is also now widely used for developing web apps, simplifying and automating common tasks, all under a single environment.

There are literally hundreds of thousands of Node.js modules available, and npm was introduced as a dedicated package manager to help install, organize, and manage all the various modules in your web app. Since npm is bundled with Node.js, all you need to do is install the latest version of Node.js on your system to make it available via your command line.

JavaScript

A reasonable level of JavaScript is required to set up and develop React apps. Otherwise, you'll most certainly struggle at some point to create React apps of any depth or complexity. This includes some features of ES6 such as arrow functions, classes, and modules. I recommend brushing up on your JavaScript skills if necessary before attempting to develop a React app.

React

This tutorial series focuses on setting up React apps rather than developing them, and so we won't be delving too deeply into React specific topics such as components, props, and state. It's a good idea, though, to have some basic knowledge of what these are, so in the next section we'll be covering the basic features of React and exploring how all the parts fit together to form a working app.

Structure of a React App

Before we dive into our first setup method, let's take a quick tour of React itself.

At its core there are three fundamental features of React that most apps are comprised of. These are:

  • components
  • props
  • state

These are the key features you need to master in order to write effective React apps. Once you've reached that stage, you'll be very well prepared to dive much deeper into React and develop more complex apps.

You might be pleasantly surprised to find that React components, props, and state are not that difficult to get your head around. My personal experience was that the React setup process was more difficult than learning React itself!

Components

The building blocks of any React app are components. Think of them as reusable blocks of code which encapsulate markup, behaviour, and styles. They can also be nested inside each other, which makes them highly reusable. For example, you might have a <Book /> component which represents data and UI associated with a single book. You could then also have a <BookIndex /> component which renders out multiple <Book /> components, and so on.

To make constructing components easier, JSX was created to give components an HTML-like structure. If you're familiar with HTML or XML then you'll be right at home using JSX to build components. It's worth noting that you are not required to use JSX at all in React, but it's now become the accepted standard way to define components.

Props

Props allow you to pass information between components. And in React, information can only be passed via props from parent components to child components.

If you choose to use JSX in your component definitions (and I highly recommend you do) then defining props on a component is remarkably similar to adding HTML attributes. This is one of the reasons JSX is so popular! Being able to use HTML-like syntax for React components and props makes it very easy to quickly scaffold out your app.

Let's take a closer look at our <BookIndex /> React component example and see how we can define it with multiple nested child <Book /> components. At the same time, we'll pass down information to each individual <Book /> component from <BookIndex />.

First, here's the <BookIndex /> component definition:

Then, inside each <Book /> component, we can access passed-in props like this:

If the above syntax for creating React components looks strange, don't worry—it's pretty straightforward. An ES6 class extends the base component class, and then a (required) render method handles the output of the component.

State

State enables us to keep track of all the data in a React app. We need to be able to update the UI whenever something changes, and state handles this for us. Whenever state is changed, React is smart enough to know which parts of your app need updating. This makes React very fast as it will only update the parts that have changed.

State is typically applied to the top-level component in your React app, so that it's available to every child component to consume state data as necessary.

That's it for our whirlwind tour of React. It's by no means comprehensive, and there's a lot more you need to learn before you can create fully fledged complex apps, but understanding components, props, and state will give you a solid head-start.

Conclusion

In this tutorial, we laid the groundwork for learning how to set up a React environment. The rest of this tutorial series focuses on the specific methods needed to do this. We'll cover setup methods ranging from very simple to more complex methods requiring manual configuration.

In the next tutorial, we'll start by taking a look at using CodePen, an online code editor, to set up a React app in just a few mouse clicks. This is by far the simplest and quickest way to get coding in React!

August 25 2017

18:00

Kotlin From Scratch: Ranges and Collections

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 in this series, you learned about nullability, loops, and conditions in Kotlin. In this tutorial, we'll continue to learn the language by looking at the ranges and collections API in Kotlin.

1. Ranges

A Range in Kotlin is a unique type that defines a start value and an end value. In other words, it is an interval between a start and an end value. Ranges in Kotlin are closed, meaning that the start value and end value are included in the range. 

We'll now look at the different ways of creating ranges in Kotlin.

The .. Operator

In the code above, we have created a closed range. This variable oneToFive will include the following values: 1, 2, 3, 4, 5. We can loop over it using the for loop construct.

The code above can be shortened to:

We can also create a range of characters:

The variable aToZ will have all the letters in the English alphabet.

The rangeTo() Function

The .. operator can be replaced with the rangeTo() extension function to create a range. For example, we can also do this 1.rangeTo(5) and it would still have the same results as using the .. operator as discussed earlier. 

The downTo() Function

This is another extension function that will create a range starting from a given number down to another one.

We can modify the range using the step() function. This will modify the delta between each element in the range.

The code above will contain odd numbers between 1 and 10.

The in Operator

The in operator is used to ascertain whether a value is present in a given range.

In the code above, we checked to see if 5 is in the range 1..10 using the in operator. We can also do the opposite by using !n to check if 5 is not in the range.

2. Collections

Collections are used to store groups of related objects in memory. In a collection, we can retrieve, store or organize the objects. Kotlin provides its collections API as a standard library built on top of the Java Collections API. (We'll discuss interfaces in Kotlin in a future post.) 

You should note that these interfaces are linked to their implementation at compile time. You can't see the implementation source code in Kotlin, because the collections are actually implemented by the standard Java Collections such as ArrayListMapsHashMapSetsHashSetList and so on. To really understand the collections API in Kotlin, you'll need to be familiar with these basic classes and interfaces in Java.

In this section, we'll learn about the List, Set and Map collections in Kotlin. (If you want a refresher on arrays in Kotlin, kindly visit the first tutorial in this series.) 

Kotlin's collections give us the ability to achieve a lot with just a little code—unlike in Java, which seems to need a lot of code to achieve a little! Kotlin has two variants of collections: mutable and immutable. A mutable collection provides us with the ability to modify a collection by either adding, removing or replacing an element. Immutable collections cannot be modified and don't have these helper methods. 

Note that the addition, removal or replacement of an element in an immutable collection is possible via operator functions (we'll get to that shortly), but these will end up creating a new collection.

The Iterable Interface

The Kotlin Iterable interface is at the top of the collections class hierarchy. This interface enables collections to be represented as a sequence of elements (which can be iterated over, naturally). 

The Collection Interface

The Kotlin Collection interface extends the Iterable interface. The Collection interface is immutable. In other words, you have read-only access to collections. The Set and List interfaces (more about these shortly) in Kotlin extend this interface. 

Some of the functions and properties available in the Collection interface are:

  • size: this property returns the size of the collection.
  • isEmpty(): returns true if the collection is empty or false otherwise. 
  • contains(element: E): returns true if the element specified in the argument is present in the collection.
  • containsAll(element: Collection<E>): returns true if the element in the collection passed as argument is present in the collection.  

The MutableIterable Interface

This interface in Kotlin gives us a specialized mutable iterator from the parent Iterable interface.

The MutableCollection Interface

The MutableCollection interface in Kotlin is a specialized interface that enables collections to be mutable. In other words, add and remove operations can be performed on a given collection. This interface extends both the Collection interface and the MutableIterable interface already discussed above. The MutableSet and MutableList interfaces (we'll get to them shortly) in Kotlin extend this interface. The functions available in this interface—apart from the ones available in its parents—are:

  • add(element: E): adds the element passed as an argument to the collection and returns true if successful or false if the collection does not support duplicates and the element is already present.
  • remove(element: E): removes the element passed as an argument from the collection. Returns true if successful or false if it was not present in the collection.
  • addAll(elements: Collection<E>): adds all the elements in the collection passed as arguments to the collection. Returns true if successful or false if nothing was added.
  • removeAll(elements: Collection<E>): removes all of the elements present in the collection passed as arguments. Returns true if successful or false if nothing was removed.
  • retainAll(elements: Collection<E>): retains only the elements present in the collections passed as arguments. Returns true if successful or false if nothing was retained. 
  • clear(): removes all elements from this collection.

Now you have learned about the top interfaces in the collection class hierarchy in Kotlin, let's now look into how Kotlin handles collections such as Lists, Sets and Maps in the remaining part of the tutorial.

Lists

A list is an ordered collection of elements. This is a popular collection that is widely used. Let's look at different ways of creating a list in Kotlin.

Using the listOf() Function

In Kotlin, we can create an immutable (read-only) list using the listOf() helper function from the Kotlin standard library. This function returns a Kotlin List interface type.

Running the code above will print: 

Moreover, we can pass values of different types into the listOf() as arguments and the result will still work—it will be a list of mixed type. 

Using the emptyList() Function

This function just creates an empty immutable list and returns a Kotlin List interface type.

Using the listOfNotNull() Function

This function creates a new immutable list containing only elements that are not null. Notice that this function returns a Kotlin List interface type also.

The List interface from the Kotlin standard library extends only the Collection interface. In other words, its only parent is the Collection interface. It overrides all the functions in the parent interface to cater for its special needs and also defines its own functions, such as:

  • get(index: Int): a function operator that returns the element at the specified index. 
  • indexOf(element: E): returns the index of the first occurrence of the element passed as an argument in the list, or -1 if none is found.
  • lastIndexOf(element: E): returns the index of the last occurrence of the element passed as an argument in the list, or -1 if none is found. 
  • listIterator(): returns a list iterator over the elements in the list.
  • subList(fromIndex: Int, toIndex: Int): returns a list that contains the portion of the list between the specified start and end indices. 

Using the arrayListOf() Function

This creates a mutable list and returns a Java ArrayList type.

Using the mutableListOf() Function

To add, remove or replace values in a list, we need to make the list a mutable one. We can convert an immutable list to a mutable one by calling the function toMutableList() on the list. However, note that this method will create a new list.

To create a mutable list of a certain type from scratch, e.g. String, we use mutableListOf<String>(), while for mixed types we can just use the mutableListOf() function instead.

Any of these functions will return a MutableList Kotlin interface type. This interface extends both the MutableCollection and List interfaces discussed earlier in this section. The MutableList interface adds methods for the retrieval or substitution of an item based upon its position: 

  • set(index: Int, element: E): substitutes an element in the list with another element. This returns the element previously at the specified position.
  • add(index: Int, element: E): inserts an element at the specified index. 
  • removeAt(index: Int): gets rid of the element at a particular index. 

Running the code above, we produce the following result:

Note that all these functions create a Java ArrayList behind the scenes.

Sets

A set is an unordered collection of unique elements. In other words, it can't have any duplicates! Let's look at some of the different ways of creating a set in Kotlin. Each of these creates a different data structure, each of which is optimized for a certain kind of task. 

Using the setOf() Function

To create an immutable (read-only) set in Kotlin, we can use the function setOf(), which returns a Kotlin Set interface type. 

Note that the Kotlin Set interface extends only the Kotlin Collection interface and overrides all the properties available in its parent.

Using the hashSetOf() Function 

Using the hashSetOf() function creates a Java HashSet collection which stores elements in a hash table. Because this function returns a Java HashSet type, we can add, remove, or clear elements in the set. In other words, it's mutable. 

Using the sortedSetOf() Function

Using the sortedSetOf() function creates a Java TreeSet collection behind the scenes, which orders elements based on their natural ordering or by a comparator. This set is also mutable.

Using the linkedSetOf() Function

This function returns a Java LinkedHashSet type. This mutable set maintains a linked list of the entries in the set, in the order in which they were inserted. 

Using the mutableSetOf() Function

We can use mutableSetOf() to create a mutable set. This function returns a Kotlin MutableSet interface type. Behind the scenes, this function simply creates a Java LinkedHashSet.  

The MutableSet interface extends both the MutableCollection and the Set interfaces. 

Maps

Maps associate keys to values. The keys must be unique, but the associated values don't need to be. That way, each key can be used to uniquely identify the associated value, since the map makes sure that you can't have duplicate keys in the collection. Behind the scenes, Kotlin uses the Java Map collection to implement its map collection type.

Using the mapOf() Function

To create an immutable or read-only Map collection in Kotlin, we use the mapOf() function. We create a map with this function by giving it a list of pairs—the first value is the key, and the second is the value. Calling this function returns a Kotlin Map interface type.

Running the code above will produce the result: 

Unlike the List and Set interfaces in Kotlin that extend the Collection interface, the Map interface doesn't extend any at all. Some of the properties and functions available in this interface are:

  • size: this property returns the size of map collection.
  • isEmpty(): returns true if the map is empty or false otherwise.
  • containsKey(key: K): returns true if the map contains the key in the argument. 
  • containsValue(value: V): returns true if the map maps one or more keys to the value passed as an argument.
  • get(key: K): returns the value matching the given key or 'null' if none is found. 
  • keys: this property returns an immutable Set of all the keys in the map.
  • values: returns an immutable Collection of all the values in the map.

Using the mutableMapOf() Function

The mutableMapOf() function creates a mutable map for us so that we can add and remove elements in the map. This returns a Kotlin MutableMap interface type.

The MutableMap interface doesn't extend the MutableCollection interface; it's only parent is the Map interface. It overrides the keysentries and values properties from the parent interface in order to redefine them. Here are some of the extra functions available in the MutableMap interface:

  • put(key: K, value: V): inserts the key, value pair into the map. This will return the previous value linked with the key or null if the key was not previously used. 
  • remove(key: K): removes the key and its linked value from the map. 
  • putAll(from: Map<out K, V>): updates the map with all the data from the given map. New keys will be added, and existing keys will be updated with new values. 
  • clear(): removes all elements from the map. 

We can get the value for a key using the get() function. We can also use square bracket notation as a shortcut for get()

Using the hashMapOf() Function

Using this function returns a Java HashMap type that is mutable. The HashMap class uses a hash table to implement the Java Map interface.  

Using the linkedHashMap() Function

This function returns a Java LinkedHashMap type that is mutable. The LinkedHashMap class extends Java HashMap and maintains a linked list of the entries in the map in the order in which they were inserted. 

Using the sortedMapOf() Function

This function returns a Java SortedMap type which is mutable. The Java SortedMap class sees that the entries in the map are maintained in an ascending key order.

Remember, implementation of these collection interfaces in Kotlin happens at compile time.

Collections Operation Functions

Kotlin provides us with many useful operator functions called extension functions that can be invoked on collections. Let's take a look at some of the most useful.

The last() Function

This operator function returns the last element in a collection such as a list or set. We can also supply a predicate to search within a subset of elements.

The first() Function

This operator function returns the first element when invoked on a collection such as a list or set. If a predicate is given, it then uses the predicate to restrict the operation to a subset of elements.

The max() Function

Invoking this operator function on a collection such as a list or set returns the largest element, or null if no largest element is found.

The drop() Function

Calling this operator function returns a new list or set containing all elements except the first n elements.

The plus() Function

This operator function returns a collection containing all elements of the original and then the given element if it isn't already in the collection. This will end up creating a new list instead of modifying the list.

The minus() Function

The opposite of the plus() function is the minus() function. It returns a collection containing all elements of the original set except the given element. This also ends up creating a new list instead of altering the list.

The average() Function

Calling this operator function will return an average number of elements in the collection.

Most of these extension functions are available in the Kotlin collections standard library. You are advised to check out the documentation to learn about the others.

Conclusion

In this tutorial, you learned about the range and collections API in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you'll be introduced to functions 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!

  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali
  • Machine Learning
    Create Chatbots on Android With IBM Watson
    Ashraff Hathibelagal
  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby
  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal
  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena
12:00

How CodeIgniter's Hook System Works

As a CodeIgniter developer, sometimes you end up in a situation that requires you to alter the core of the framework or the execution flow to fulfill your custom requirements. Of course, it's never recommended to modify the core files as it makes the upgrade process cumbersome. Luckily, the CodeIgniter framework comes with the hooks system, which allows you deal with this scenario.

In this article, we'll start with an introduction to the hooks system in the CodeIgniter framework. Then, we'll discuss the different types of hooks available. And finally, we'll grab this opportunity to explore the creation of custom hooks.

Hooks: A System to Override the Core Framework

Let's have a quick look at what the official CodeIgniter documentation says about the hooks system:

CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.

Sounds pretty self-explanatory, doesn't it? In your day-to-day application development, if you ever find yourself tempted to modify the core CodeIgniter files, you should first consider the hooks system to see if it fulfills your requirements.

Let's assume that you want to build a custom performance benchmark system to monitor the application execution. You realize that the core files need to be modified in order to achieve the desired output. In that case, you could use the pre_system and the post_system hooks to get into the execution flow and collect the statistics as needed.

If you're aware of the event observer pattern, the concept is similar in that you listen for the system generated events, and the corresponding observer code gets executed when the observed event is triggered.

So that was a basic introduction to the hooks system in CodeIgniter. In the next section, we'll have a close look at the different hooks available for you to plug into the system.

Go Through the Different Hooks

The CodeIgniter hook system provides different hook points that you can use while implementing your custom hooks. The hook point is basically a certain state in the request execution workflow at a given time.

For example, when you implement the pre_system hook, you know that you’re at the very beginning of the bootstrapping phase. On the other hand, if you’ve chosen the post_system hook, you can be sure that the execution is completed and the response is already sent to the client.

In this section, we’ll go through the different hook points that are provisioned by the CodeIgniter hook system.

System Hooks

The pre_system and the post_system hooks fall under this category as the former one is called very early during the bootstrapping phase while the latter one is called after the page execution is completed.

I can think of a few use cases that could be achieved with system hooks:

  • Benchmark
  • Logging
  • Rule-based redirection
  • And more

Controller Hooks

There are three hooks that fall under this category, so let's go through each of them.

Pre Controller Hook

The pre_controller hook is called just prior to the controller class being instantiated. So, if you would like to do any further checks before the controller gets called, this is the hook you're looking for.

Post Controller Constructor Hook

As the name suggests, the post_controller_constructor hook is called immediately after the controller object is instantiated and prior to the actual method call.

At this point, you're sure that the controller is instantiated and the method is going to be called soon, so you could load any controller specific libraries here, or you could implement the controller-specific custom validation as well.

Post Controller Hook

The post_controller hook is called after the execution of the controller method. So the stuff that you want to execute after execution of the controller should be implemented with this hook.

So that was the story of the controller specific hooks.

Overrides Hooks

Display Override Hook

According to the CodeIgniter documentation, the display_override hook overrides the core _display method. The core _display method is used to send the output to the client, and thus by using the display_override hook you could alter the way the output is sent to the user.

In fact, we'll explore this hook in detail as we move on to the next section, in which we'll discuss how to create a custom hook.

Cache Override Hook

The cache_override hook overrides the core _display_cache method of the Output class. The _display_cache method is responsible for serving the cached output, so you could use this hook should you wish to serve the page output from the different cached location just in case you've implemented a different caching mechanism.

That ends the story of different hook points in the CodeIgniter hook system. In the next section, we'll see how exactly you could take an advantage of the hook system by implementing a real-world example.

How to Create a Custom Hook

I'm sure that you've had enough theory so far, so let's get back to some practical development! In this section, we'll create a custom hook to demonstrate the concepts discussed so far in this article.

In our case, we'll use the display_override hook that'll be responsible for the token replacement. To be more precise, we'll replace all the occurrences of [DATETIME] with the current date. Of course, that sounds like a pretty simple use case, but you could easily extend it to be more specific as per your requirements.

By default, the hook system is disabled in the core framework, so the first thing you need to do is to enable the hook system.

Go ahead and open the configuration file application/config/config.php.

Look for the following snippet and turn it on by changing FALSE to TRUE.

Now, we're ready to define our hooks. In fact, CodeIgniter already comes with the file application/config/hooks.php that you could use should you wish to define hooks.

By default, the hooks.php file is empty, so let's add our custom hook code to make it more meaningful.

The syntax of defining a custom hook is pretty simple. It's the $hook array that holds all the hooks that need to be executed.

The key of each array entry is the name of the hook itself you're defining. When you're defining a hook, you're telling the system to execute a certain piece of code when something happens. That's exactly what needs to be supplied as a value of any hook. Let's go through each key quickly.

  • The class key holds the name of a class that holds the code that needs to be executed.
  • The function key holds the name of the method that'll be called upon the hook execution.
  • The filename key points to the file that defines the complete hook code.
  • The filepath defines the directory path of the file declared under the filename key, and it's relative to the application directory. Generally, it's set to hooks, thus resulting in an application/hooks structure. Of course, there's nothing stopping you from defining a completely different path if you wish to do so.

As a side note, if you don't want to create a class file, you could also supply a closure function that'll be executed when the hook is triggered.

In our case, we'll create a file ReplaceToken.php and according to the hook definition it must be placed under the application/hooks directory.

Go ahead and create a file application/hooks/ReplaceToken.php with the following contents.

The object of our hook is to replace the [DATETIME] placeholder with the actual date before the output of any page in our application is sent to the client.

As we've discussed earlier, the output of the page is already built by the time the display_override hook is called. So the first thing that we would like to do is to fetch the output that's ready to be sent to the user.

The get_instance method is used to instantiate the application instance, and it's assigned to $this->CI. Next, we use the get_output method of the Output class to fetch the response contents.

The rest is pretty simple. The [DATETIME] placeholder needs to be replaced with the actual date. To make things easier, the date helper is used to carry out the desired operation, and we're almost done as far as our hook logic is concerned.

Finally, you need to echo the output as the display_override overrides the _display method that is used to send the output to the client. So we need to do it ourselves in this case; otherwise, it would have been handled by the core _display method.

In fact, that ends the story of our custom hook!

Now, let's go ahead and make a new CodeIgniter page so that we can test our custom hook. Create a controller file application/controllers/TokenExample.php with the following contents.

And here's how the associated view file application/views/token_content.php should look.

And that's pretty much it. Point your browser to http://your-code-igniter-site-url/TokenExample/index and you should see the expected output!

So that's the hook system at your disposal should you wish to get into the typical workflow of the CodeIgniter application. I hope that you've enjoyed the article and that it helps you in your day-to-day CodeIgniter application development.

Conclusion

Today, we went through one of the exciting built-in CodeIgniter feature—hooks. Hooks allow you to intervene in the typical request execution workflow of your CodeIgniter application.

At the beginning of the article, we discussed the basic concept of Hooks in CodeIgniter, and then we discussed the different hooks available in the system. Finally, in the last section we explored how to create a custom hook and its inner workings.

Don't hesitate to express your thoughts using the feed below. Also, if you want me to come up with any specific topics, please just let me know.

August 24 2017

15:00

What Are Android Intents?

Intents are a fundamental topic for Android developers. It is impossible to build Android applications without coming in contact with intents. In this tutorial, I'll teach you about intents from A to Z.

What Are Intents?

In a football match, teammates pass the ball around the field with the aim of sending it into the goal of their opponent. The ball is passed from the team's goalkeeper to their defenders. Next, it finds its way to the midfielders, and if things work out as planned, one of the strikers sends it into the net of the opponent. That's assuming the goalkeeper of the other side was not able to keep it away!

In Android, the ability to send messages around is made possible by the Intent object. With the help of intents, Android components can request functionality from other Android components. When you open up the Instagram app on your phone and use it to take a picture, you just made use of an intent. Intents also help communicate between parts of an app; the movement from one screen (activity) to another is made possible by intents.

Look at it this way: all components (applications and screens) of the Android device are isolated. The only way they communicate with each other is through intents.

Starting Activities With Intents

As mentioned earlier, you can use intents to start different components: activities, services, and broadcast receivers.

To start an activity, you will make use of the method startActivity(intent).

Here is a code snippet that demonstrates how to start another activity from an intent.

First, we create a new Intent object and pass it the NumbersActivity class. Then we start a new activity using that intent.

Types of Intents

Android supports two types of intents: explicit and implicit. When an application defines its target component in an intent, that it is an explicit intent. When the application does not name a target component, that it is an implicit intent.

Explicit Intent Example

The code snippet of code above is an example of explicit intent. Have a look at it again.

Here, NumbersActivity is the target component from our MainActivity. This means that NumbersActivity is the defined component that will be called by the Android system. It is important to note (as in the example above), that explicit intents are typically used within an application, because that gives the developer the most control over which class will be launched.

Implicit Intent Example

Here's an implicit intent:

If you have the above code in your codebase, your application can start a browser component for a certain URL via an intent. But how does the Android system identify the components which can react to a certain intent?

A component can be registered via an intent filter for a specific action. Intent filters can be registered for components statically in the AndroidManifest.xml. Here is an example that registers a component as a web viewer:

Using Intents in an App

Let's write some code to see how it works out. In this section, you'll build a tiny app to try out both styles of intent. The app will have a little form to enter a first name and last name. When the Submit button is clicked, both of the entered values will be passed to another activity. There will also be a button to launch a browser of your choice. The chosen browser will open up http://code.tutsplus.com.

Open up Android Studio and generate your MainActivity. You can set the name of the package to com.tutsplus.code.android.droidintent.

Your MainActivity will start with some imports and the class declaration:

Then you'll override the onCreate() method to initialize the activity with any saved state and the activity layout (we'll create this later).

Next you'll get references to each of the buttons defined in the layout and attach a click listener to each of them.

For the Submit button, you set an OnClickListener to trigger an action whenever the button is clicked. When a click occurs, we grab the first and last name from the view, and send them to the next activity: ShowActivity. The target component is explicitly defined in the intent, making this an example of explicit intent.

For the browser button, the OnClickListener will create a new intent to launch any application that matches the filter: an ACTION_VIEW which should handle a web URL. In other words, it launches a web browser. If you have more than one browser application installed on your device, you will be asked to select one to perform the action of opening the web site. This is an example of an implicit intent.

MainActivity Layout

The layout for MainActivity will be very simple for the purpose of this tutorial.

Here you have two TextView and two EditText indicating First Name and Last Name respectively. There is also a button to submit the names, and another to launch your browser.

Create the ShowActivity

To complete our app, we need to create an activity to handle the explicit intent defined above. Create a new activity called ShowActivity. This is the activity where the result of entering the first name and last name will be shown. Here is what it should look like:

In this activity, you start by getting the strings passed from the MainActivity. You can get a reference to the intent that triggered the launch of this activity with the getIntent() function. Then you can access the strings that were passed to it using getExtras().getString(). Finally, after getting the TextView instances from the layout, you display the values you obtained. 

ShowActivity Layout

The layout for this activity is simple:

Testing the App

Now you can build your app and try it out on your Android device!

Passing Data Using Bundles

You can also make use of Bundles when passing data via intents.

The Bundle class allows you store complex data and supports data types such as strings, chars, boolean, integer and so on. Here is an example of how part of MainActivity.java would look if you used Bundle.

Conclusion

In this tutorial, we got a brief introduction to using intents to create activities in Android. We looked at the difference between explicit and implicit intents, and coded a simple example that used each type. 

You can read more about intents in the Android documentation. Understanding how they work is very important. As you build more apps, you will encounter lots of different kinds of Intents and ways of using them.

And in the meantime, check out some of our other posts on Android app development!

  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali
  • Java
    Android Design Patterns: The Observer Pattern
    Chike Mgbemena
  • Android
    Android From Scratch: Building Your First Android Application
    Gianluca Segato

12:00

How to Create a Real-Time Feed Using Phoenix and React

Final product image What You'll Be Creating

In this tutorial, I'll show you how we can use the power of React and Phoenix to create a feed application which will update itself in real time as we add new feeds to our database.

Introduction

Elixir is known for its stability and real-time features, and Phoenix leverages the Erlang VM ability to handle millions of connections alongside Elixir's beautiful syntax and productive tooling. This will help us in generating the real-time updating of data through APIs which would be consumed by our React application to show the data on the user interface.

Getting Started

You should have Elixir, Erlang, and Phoenix installed. More about that can be found on the Phoenix framework's website. Apart from that, we will be using a bare-bones React boilerplate since it's well-maintained and properly documented.

Making the APIs Ready

In this section, we will bootstrap our Phoenix API-only application and add channels to update the APIs in real time. We will just be working with a feed (it will contain a title and a description), and once its value is changed in the database, the API will send the updated value to our front-end application.

Bootstrap the App

Let's first bootstrap the Phoenix application.

mix phoenix.new  realtime_feed_api --no-html --no-brunch

This will create a bare-bones Phoenix application inside a folder named realtime_feed_api. The --no-html option won't create all the static files (which is useful if you're creating an API-only application), and the --no-brunch option won't include Phoenix's static bundler, Brunch. Please make sure you install the dependencies when it prompts.

Let's go inside the folder and create our database.

cd realtime_feed_api

We will have to remove the username and password fields from our config/dev.exs file since we will be creating our database without any username or password. This is just to keep things simple for this post. For your application, make sure that you create a database first, with a username and password.

mix ecto.create

The above command will create our database. Now, we can run our Phoenix server and test if everything is fine at this point.

mix phoenix.server

The above command will fire our Phoenix server, and we can go to http://localhost:4000 to see it running. Currently, it will throw a no route found error since we haven't created any routes yet!

Feel free to verify your changes with my commit.

Add the Feed Model

In this step, we will add our Feed model to our Phoenix app. The Feeds model will consist of a title and a description.

mix phoenix.gen.json Feed feeds title:string description:string

The above command will generate our Feed model and controller. It will also generate the specs (which we won't be modifying in this tutorial, just to keep it short).

You need to add the /feeds route in your web/router.ex file inside the api scope:

resources "/feeds", FeedController, except: [:new, :edit]

We would also need to run the migration to create the feeds table in our database:

mix ecto.migrate

Now, if we go to http://localhost:4000/api/feeds, we will see that the API is sending us a blank response since there is no data in our feeds table.

You can check my commit for reference.

Add the Feed Channel

In this step, we will add our Feed channel to our Phoenix app. Channels provide a means for bidirectional communication from clients that integrate with the Phoenix.PubSub layer for soft real-time functionality.

mix phoenix.gen.channel feed

The above command will generate a feed_channel.ex file inside the web/channels folder. Through this file, our React application will exchange the updated data from the database using sockets.

We need to add the new channel to our web/channels/user_socket.ex file:

channel "feeds", RealtimeFeedApi.FeedChannel

Since we are not doing any authentication for this application, we can modify our web/channels/feed_channel.ex file. We will need one join method for our React application to join our feed channel, one handle_out method to push the payload through a socket connection, and one broadcast_create method which will broadcast a payload whenever a new feed is created in the database.

The three methods are defined above. In the broadcast_create method, we are using app/FeedsPage/HAS_NEW_FEEDS since we will be using that as a constant for our Redux state container, which will be responsible for letting the front-end application know that there are new feeds in the database. We will discuss that when we build our front-end application.

In the end, we will only need to call the broadcast_change method through our feed_controller.ex file whenever new data is inserted in our create method. Our create method will look something like:

The create method is responsible for inserting a new data in the database. You can check my commit for reference.

Add CORS Support for the API

We need to implement this support since, in our case, the API is served from http://localhost:4000 but our front-end application will be running on http://localhost:3000. Adding CORS support is easy. We will just need to add cors_plug to our mix.exs file:

Now, we stop our Phoenix server using Control-C and fetch the dependency using the following command:

mix deps.get

We will need to add the following line to our lib/realtime_feed_api/endpoint.ex file:

plug CORSPlug

You can check my commit. We are done with all our back-end changes. Let's now focus on the front-end application.

Update the Front-End Data in Real Time

As mentioned earlier, we will use react-boilerplate to get started with our front-end application. We will use Redux saga which will listen to our dispatched actions, and based on that, the user interface will update the data. 

Since everything is already configured in the boilerplate, we don't have to configure it. However, we will make use of the commands available in the boilerplate to scaffold our application. Let's first clone the repository:

git clone  https://github.com/react-boilerplate/react-boilerplate.git realtime_feed_ui

Bootstrap the App

Now, we will need to go inside the realtime_feed_ui folder and install the dependencies.

cd realtime_feed_ui && npm run setup

This initializes a new project with this boilerplate, deletes the react-boilerplate git history, installs the dependencies, and initializes a new repository.

Now, let's delete the example app which is provided by the boilerplate, and replace it with the smallest amount of boilerplate code necessary to start writing our app:

npm run clean

We can now start our application using npm run start and see it running at http://localhost:3000/.

You can refer to my commit.

Add the Necessary Containers

In this step, we will add two new containers, FeedsPage and AddFeedPage, to our app. The FeedsPage container will show a list of feeds, and the AddFeedPage container will allow us to add a new feed to our database. We will use the react-boilerplate generators to create our containers.

npm run generate container

The above command is used to scaffold a container in our app. After you type this command, it will ask for the name of the component, which will be FeedsPage in this case, and we will use the Component option in the next step. We won't be needing headers, but we will need actions/constants/selectors/reducer as well as sagas for our asynchronous flows. We don't need i18n messages for our application. We will also need to follow a similar approach to create our AddFeedPage container.

Now, we have a bunch of new files to work with. This saves us a lot of time. Otherwise, we would have to create and configure all these files by ourselves. Also, the generator creates test files, which are very useful, but we won't be writing tests as part of this tutorial.

Let's just quickly add our containers to our routes.js file:

This will add our FeedsPage container to our /feeds route. We can verify this by visiting http://localhost:3000/feeds. Currently, it will be totally blank since we don't have anything in our containers, but there won't be any errors in the console of our browser.

We will do the same for our AddFeedPage container.

You can refer to my commit for all the changes.

Build the Feeds Listing Page

In this step we will build the FeedsPage which will list all our feeds. For the sake of keeping this tutorial small, we won't be adding any styles here, but at the end of our application, I'll make a separate commit which will add some designs to our application.

Let's start by adding our constants in our app/containers/FeedsPage/constants.js file:

We will need these four constants:

  • The FETCH_FEEDS_REQUEST constant will be used to initialize our fetching request.
  • The FETCH_FEEDS_SUCCESS constant will be used when the fetching request is successful.
  • The FETCH_FEEDS_ERROR constant will be used when the fetching request is unsuccessful.
  • The HAS_NEW_FEEDS constant will be used when there is a new feed in our database.

Let's add our actions in our app/containers/FeedsPage/actions.js file:

All these actions are self-explanatory. Now, we will structure the initialState of our application and add a reducer in our app/containers/FeedsPage/reducer.js file:

This will be the initialState of our application (the state before the fetching of the data starts). Since we are using ImmutableJS, we can use its List data structure to store our immutable data. Our reducer function will be something like the following:

Basically, what we are doing here is changing our state based on the constant from our actions. We can show loaders and error messages very easily in this manner. It will be much clearer when we use this in our user interface.

It's time to create our selectors using reselect, which is a selector library for Redux. We can extract complex state values very easily using reselect. Let's add the following selectors to our app/containers/FeedsPage/selectors.js file:

As you can see here, we are using the structure of our initialState to extract data from our state. You just need to remember the syntax of reselect.

It's time to add our sagas using redux-saga. Here, the basic idea is that we need to create a function to fetch data and another function to watch the initial function so that whenever any specific action is dispatched, we need to call the initial function. Let's add the function which will fetch our list of feeds from the back-end application in our app/containers/FeedsPage/sagas.js file:

Here, request is just a util function which does our API call to our back end. The whole file is available at react-boilerplate. We will make a slight change in it after we complete our sagas.js file.

We also need to create one more function to watch the getFeeds function:

As we can see here, the getFeeds function will be called when we dispatch the action which contains the FETCH_FEEDS_REQUEST constant.

Now, let's copy the request.js file from react-boilerplate into our application inside the app/utils folder and then modify the request function:

I've just added a few defaults which will help us in reducing the code later on since we don't need to pass the method and headers every time. Now, we need to create another util file inside the app/utils folder. We will call this file socketSagas.js. It will contain four functions: connectToSocketjoinChannelcreateSocketChannel, and handleUpdatedData

The connectToSocket function will be responsible for connecting to our back-end API socket. We will use the phoenix npm package. So we will have to install it:

npm install phoenix --save

This will install the phoenix npm package and save it to our package.json file. Our connectToSocket function will look something like the following:

Next, we define our joinChannel function, which will be responsible for joining a particular channel from our back end. The joinChannel function will have the following contents:

If the joining is successful, we will log 'Joined successfully' just for testing. If there was an error during the joining phase, we will also log that just for debugging purposes.

The createSocketChannel will be responsible for creating an event channel from a given socket.

This function will also be useful if we want to unsubscribe from a particular channel.

The handleUpdatedData will just call an action passed to it as an argument.

Now, let's add the rest of the sagas in our app/containers/FeedsPage/sagas.js file. We will create two more functions here: connectWithFeedsSocketForNewFeeds and watchConnectWithFeedsSocketForNewFeeds

The connectWithFeedsSocketForNewFeeds function will be responsible for connecting with the back-end socket and checking for new feeds. If there are any new feeds, it will call the createSocketChannel function from the utils/socketSagas.js file, which will create an event channel for that given socket. Our connectWithFeedsSocketForNewFeeds function will contain the following:

And the watchConnectWithFeedsSocketForNewFeeds will have the following:

Now, we will tie everything with our app/containers/FeedsPage/index.js file. This file will contain all our user interface elements. Let's start by calling the prop which will fetch the data from the back end in our componentDidMount:

This will fetch all the feeds. Now, we need to call the fetchFeedsRequest prop again whenever the hasNewFeeds prop is true (you can refer to our reducer's initialState for the structure of our app):

After this, we just render the feeds in our render function. We will create a feedsNode function with the following contents:

And then, we can call this method in our render method:

If we now go to http://localhost:3000/feeds, we will see the following logged in our console:

Joined successfully Joined feeds

This means that our feeds API is working fine, and we have successfully connected our front end with our back-end application. Now, we just need to create a form through which we can enter a new feed.

Feel free to refer to my commit since a lot of stuff went in this commit!

Build the Form to Add a New Feed

In this step, we will be creating a form through which we can add a new feed to our database.

Let's start by adding the constants to our app/containers/AddFeedPage/constants.js file:

The UPDATE_ATTRIBUTES constant will be used when we add some text to the input box. All the other constants will be used for saving the feed title and description to our database.

The AddFeedPage container will use four actions: updateAttributessaveFeedRequestsaveFeed, and saveFeedError. The updateAttributes function will update the attributes of our new feed. It means whenever we type something in the input box of the feed title and description, the updateAttributes function will update our Redux state. These four actions will look something like the following:

Next, let's add our reducer functions in app/containers/AddFeedPage/reducer.js file. The initialState will look like the following:

And the reducer function will look something like:

Next, we will be configuring our app/containers/AddFeedPage/selectors.js file. It will have four selectors: titledescriptionerror, and saving. As the name suggests, these selectors will extract these states from the Redux state and make it available in our container as props.

These four functions will look like the following:

Next, let's configure our sagas for AddFeedPage container. It will have two functions: saveFeed and watchSaveFeed. The saveFeed function will be responsible for doing the POST request to our API, and it will have the following:

The watchSaveFeed function will be similar to our previous watch functions:

Next, we just need to render the form in our container. To keep things modularized, let's create a sub-component for the form. Create a new file form.js inside our app/containers/AddFeedPage/sub-components folder (the sub-components folder is a new folder which you will have to create). It will contain the form with one input box for the title of the feed and one textarea for the description of the feed. The render method will have the following contents:

We will create two more functions: handleChange and handleSubmit. The handleChange function is responsible for updating our Redux state whenever we add some text, and the handleSubmit function calls our API to save the data in our Redux state.

The handleChange function has the following:

And the handleSubmit function will contain the following:

Here, we are saving the data and then clearing the form values.

Now, back to our app/containers/AddFeedPage/index.js file, we will just render the form we just created.

Now, all our coding is complete. Feel free to check my commit if you have any doubts.

Finalizing

We have completed building our application. Now, we can visit http://localhost:3000/feeds/new and add new feeds which will be rendered in real time on http://localhost:3000/feeds. We don't need to refresh the page to see the new feeds. You can also try this by opening http://localhost:3000/feeds on two tabs side by side and test it!

Conclusion

This will be just a sample application to show the real powers of combining Phoenix with React. We use real-time data in most places now, and this might just help you get a feel for developing something like that. I hope that you found this tutorial useful.

August 23 2017

13:02

Welcome to a Week of Discounts in Envato's Birthday Sale!

It's Envato's 11th birthday this week, but it's OK—you don't have to buy us a gift. In fact, we're celebrating by giving you some gifts. Read on for news of some huge discounts and freebies available this week only. Or visit Envato's birthday sale page to access the discounts right away.

Envato birthday sale

8 Free Items on Envato Elements

The premium creative assets on Envato Elements are usually available via monthly subscription only, but this week you can download eight items absolutely free. 

Among the items in this curated bundle of freebies are an elegant travel magazine template, a set of social media banners for a blog, a corporate presentation template, and more. Check out the full set of Envato Elements freebies, and download them to use in any personal or commercial project.

Envato Elements birthday sale

50% Off Popular Envato Market Items

Over on Envato Market, some of the popular items are half price this week. The 50% discount applies to a collection of top themes, plugins, audio, video and graphic assets from the most popular categories.

As long as you buy before 12 pm on 29 August AEST (Australian Eastern Standard Time), you can take advantage of these special sale prices. Find out more about the Envato Market 50% birthday sale.

Envato Market discounts

20% Off Everything at Envato Studio

Do you need to get some custom design work done by skilled freelancers? How about having an app developed, or getting video and audio services? 

You can have all of that done by expert providers on Envato Studio, and this week it's even cheaper. Between now and 29 August, you can get 20% off any Envato Studio service. 

View more details of the 20% sale at Envato Studio.

Envato Studio birthday sale

Thank You!

Envato has come a long way in the 11 years since it first opened its doors back in 2006, and the community has been a big part of that. That's why the company's core value is:

"When the Community Succeeds, We Succeed."

Whether you're an Envato Elements subscriber, a buyer on Envato Market and Envato Studio, an contributor to our libraries of content, or a reader here on Envato Tuts+, you're a part of that community. So thank you for helping us reach the ripe old age of 11. Don't forget to lock in your birthday discounts before they expire!

12:39

How to Add Multiple Instant App Features to Your App

In this three-part series we’ve been exploring Android instant apps, a new feature that provides an entirely new way of reaching users who don’t currently have your app installed on their device. It works by making your app discoverable and accessible from any location that supports URLs, including emails, Google search results, posts on social media platforms, YouTube comments, and forums.

In the first post, we looked at what instant apps are, how they work, and the major benefits they have to offer both Android developers and Android app users. We even got some hands-on experience with instant apps, by using Android Studio’s project creation wizard to quickly and easily generate a project that was pre-configured to support Android instant apps.

In the second post, I used the downloadable MyLocation sample app to demonstrate how you’d update an existing Android project to support the instant apps feature. If you’ve been following along since the beginning, then by this point you’ll have successfully reconfigured the MyLocation project to include a single feature module that can run on any Android Virtual Device (AVD) without you having to install the full MyLocation app. 

However, MyLocation currently only consists of a single base feature module, and when it comes to real-life Android projects, you’ll often want to offer multiple features in instant app form. In this final instalment, I’m going to show you how to add multiple feature modules to your Android projects by walking you through the process of adding a second feature module to MyLocation and then mapping this module to a different URL.

Finally, to make sure you’re getting the most out of instant apps, we’ll be rounding off this series by taking a look at some instant app best practices.

 Creating a Multi-Feature Instant App

If you’ve completed the second instalment, then your version of the MyLocation project should currently be divided into the following modules:  

  • mylocation-app. The project’s installable app module, also known as the APK module. 
  • mylocation-base. The base feature module, which contains all the common code and resources that are used across all the project’s modules. This module contains a MapsActivity that can run independently of the installable app, and will launch on the user’s device whenever they try to access the www.example.com/maps URL.
  • mylocation-instantapp. The instant app module, which is responsible for transforming each of your project’s feature modules into an Instant App APK. 

If this isn’t how your version of MyLocation currently looks, then you can download this version from GitHub

Before we start the process of adding a second feature module to MyLocation, there are a few things you need to be aware of. 

Firstly, at the time of writing, it was only possible to develop instant apps using the Android Studio 3.0 Preview and Canary builds. Whenever you work with early access builds, you should be prepared to encounter bugs, missing functionality, and other generally strange behaviour that will (hopefully!) be addressed way before the stable release. However, working with multiple instant app feature modules seems to be particularly temperamental in the Android Studio 3.0 Canary builds.

To reduce your risk of encountering any issues, you should double-check that you have the very latest Canary build installed before trying to add a second feature module to the MyLocation project. However, if your project does suddenly start throwing errors or refusing to compile, then towards the end of this article you’ll find a Troubleshooting section that contains workarounds and possible fixes for all the issues you’re likely to encounter when adding extra feature modules to your project. 

Also note that in this tutorial we’re going to be creating an additional feature module, mapping this module to a unique URL, and then testing the module on an Android Virtual Device (AVD). This is already a lot of ground to cover, so to keep this post from getting too long, we’re going to create a module that simply displays a user interface and doesn’t contain any real functionality. However, there’s no reason why you couldn't expand on this module with your own code and resources, if you wanted a more authentic instant apps experience. 

Create Your Feature Module

The first step to turning MyLocation into a multi-feature instant app is to create our feature module: 

  • Open the MyLocation project in Android Studio. 
  • Select New > New Module… from the Android Studio toolbar.
  • Select Feature Module, and click Next.
  • In the Module name field, enter mylocation-directions.
  • Check that the minimumSDK is the same value you’ve used elsewhere in your project, and then click Next.

We may not be implementing any real functionality in our mylocation-directions module, but we still need visual confirmation that this module has loaded correctly, so select the template of your choice (I’m opting for Basic Activity) and then click Next. I’m going to map this feature module to www.example.com/directions, so start by entering example.com in the Instant App URL Host field. Open the Instant App URL Route Type dropdown and select either PathpathPrefix, or pathPattern. Since I want this module to respond to www.example.com/directions only, I’m going to select Path

In the Instant App URL Route, enter /directions. This gives us our complete URL: example.com/directions. Change the Activity Name to DirectionsActivity. Make sure the Layout Name is set to activity_directions, and then click Finish.

Create a second feature module using Android Studios built-in module creation wizard

Declaring Your Dependencies 

As you may have already noticed, a project that supports the instant apps feature is inevitably going to consist of multiple modules. If these modules are going to work together to create multiple different Instant App APKs, plus your “regular” installable APK, then they need to be aware of one another, which means you need to add the necessary dependencies to each module’s build.gradle file.

When you create a feature module via the New > New module… menu, Android Studio actually generates a few of these dependencies for you, but it doesn’t generate them all. And, to further complicate matters, you need to use different expressions, depending on the type of module(s) you’re working with.

To give you an overview, every time you create a feature module, you need to let your project know that:

  • This feature module depends on your project’s base feature module, using the implementation project expression. 
  • Your project’s base feature module depends on this feature module, using the feature project expression.
  • Your project’s instant app module depends on this feature module, using the implementation project expression. 

In this section, we’re going to look at each of these dependencies, so let’s start by running through the dependencies that Android Studio helpfully auto-generates for you.  

implementation project(':mylocation-base')

Your project’s base feature module contains all the common code and resources that are used in your project, so any additional feature modules you create will all depend on this single base feature module. 

If you open your feature module’s (mylocation-directions) build.gradle file, then you’ll see that Android Studio has already added the base feature module (mylocation-base) as a dependency:

No matter how many additional feature modules you create, all of their build.gradle files will contain this same declaration: implementation project(':mylocation-base').

feature project(":mylocation-directions")

Your base feature module also needs to be aware of all your additional feature modules.

If you open your mylocation-base module’s build.gradle file, then you’ll see that once again Android Studio has done the work for you, and declared mylocation-directions as a dependency:

Any additional feature modules you create will also be added to this section automatically, for example:

What Android Studio Doesn’t Add….

There are a few dependencies that Android Studio currently doesn’t auto-generate, so you’ll need to add them manually.

implementation project(':mylocation-directions')

Instant apps are stand-alone components that can function independently of the installable app. In the context of our MyLocation app, this means that mylocation-directions can function without mylocation-app. However, the opposite isn’t true: mylocation-app cannot function without mylocation-directions

The installable APK must contain all of your project’s modules, including all your instant app feature modules. Therefore, we need to give the APK module (mylocation-app) a heads-up about our new feature module (mylocation-directions). 

Open the mylocation-app build.gradle file, and point it to the mylocation-directions module:

You’ll need to repeat this step for every feature module you create, so if you continued to add feature modules then the mylocation-app build.gradle file might wind up looking something like this:

The instant app module is responsible for transforming each of your project’s feature modules into an Instant App APK, so it needs to know about every feature module you create. 

Open your mylocation-instantapp module’s build.gradle file, and declare mylocation-base as a dependency using the implementation project expression:

And One Additional Dependency

While we’re on the subject of project dependencies, there’s one important dependency we still need to add. 

A project that supports instant apps only needs to declare its applicationId attribute once, in the APK (app) module. However, to make sure this single applicationId attribute is properly propagated across all your feature modules, you need to add the APK module as a dependency of the base feature module. 

Open your mylocation-base module’s build.gradle file and add mylocation-app as a dependency, using the application project expression:

Unlike all the other dependencies we’ve discussed, you only need to declare a dependency on the APK module once per project, and not every time you create a feature module. 

Delete Unwanted Files and Resources

Although this step isn’t mandatory, currently our feature module does contain some unnecessary files and directories, so let’s follow best practices and streamline our mylocation-directions module:

  • Switch to Android Studio’s Project view.
  • Open the mylocation-directions module. 
  • Delete the src/androidTest directory.
  • Delete the src/test directory. 

Finish Mapping Your URL

When we created this feature module, we entered some information about the URL we ultimately want to map this module to. However, currently Android Studio’s module creation wizard cannot create a complete URL mapping, so you’ll need to open the App Links Assistant and finish this process manually:

  • Select Tools > App Links Assistant from the Android Studio toolbar.
  • Click the Open URL Mapping Editor button. 
  • In the table that appears, select the DirectionsActivity row, and then click the little pencil icon. 
In the URL-to-Activity mappings editor select your DirectionsActivity
  • Select the http radio button.
  • Make sure Path is selected in the dropdown menu, and then enter /directions in the accompanying text field. 
  • Make sure DirectionsActivity is selected in the Activity dropdown, and then click OK
  • Back in the App Links Assistant panel, click the Select Activity button.
  • When prompted, select DirectionsActivity and then click Insert Code.

You now have two feature modules that are mapped to different URLs. 

Test Your mylocation-directions Module

Currently, our run configuration is set to simulate the user tapping the www.example.com/maps link, which will launch MapsActivity, and by extension our mylocation-base module. However, if we’re going to test our additional feature module then we’ll need to simulate the user tapping www.example.com/directions, which will launch our DirectionsActivity. This requires us to update our runtime configuration: 

  • Launch the AVD you’ve been using to test your mylocation project, and make sure you’re logged in to a Google account. If you aren’t logged in to an account, then open the AVD’s launcher, select the Google app, and then enter your Gmail address and password.
  • Double-check that the MyLocation app isn’t installed on this device. If it is, then uninstall it by dragging it onto the device’s Uninstall icon.
  • Switch back to the main Android Studio window and select Run > Edit configurations…
  • In the left-hand menu, select mylocation-instantapp.
  • In the URL field, enter the URL you want to test, which in this instance is http://www.example.com/directions.
  • Click Apply, followed by OK.
  • In the Android Studio toolbar, click Run…
  • Select mylocation-instantapp.
  • Choose your target device, and then click OK.

Your DirectionsActivity should now appear on your AVD. Congratulations, you’ve just built a multi-featured instant app! 

Troubleshooting

Having to wrestle with bugs and other strange behaviour is all part of the fun of working with early access builds of Android Studio. 

If your Android Studio build does go haywire, and you can’t spot anything wrong with your project, then it’s possible the error may lie with Android Studio itself. 

In this section I’m going to share some workarounds for all the most common Android Studio errors and quirks you may encounter when creating a multi-feature instant app. 

And, just in case you encounter a problem that isn’t listed here, I’ll also be sharing a list of general fixes that can help you smooth out whatever issues you’re currently experiencing with Android Studio. 

Instant App Deployment Fails on API Levels 24 and 25

The first time you try to test your instant app on an AVD that’s running Nougat, it's possible the app may fail to deploy. If this occurs, then: 

  • Select Run > Run mylocation-instantapp from the Android Studio toolbar.
  • Before Android Studio has a chance to finish deploying your app, select Run > Stop.
  • Select Run > Run mylocation-instantapp once again, but this time let the operation complete. Your instant app should now deploy without any problems.  

Reliability Issue With Instant App Provisioning Cache

If you encounter the Reliability issue with instant app provisioning cache error message when trying to deploy your app, then this means you need to clear your cache: 

  • Select Run > Edit configurations… from the Android Studio toolbar.
  • Select mylocation-instantapp from the left-hand menu.
  • Select Instant app provision (towards the bottom of this window).
  • Click the little pencil icon.
  • Select Clear provisioned devices cache.
  • Click OK, followed by Apply and OK once more. 

AAPT2 Issues

If Android Studio complains about any AAPT2-related issues (such as displaying an AAPT2 link failed error message) then you can typically resolve these problems by disabling AAPT.

To disable AAPT, open your project’s Gradle scripts/gradle.properties file and add the following text: 

Error:(85) attribute 'android:splitName' not found

This is easily the most frustrating, and the strangest issue you may encounter when developing instant apps. 

In some builds of Android Studio 3.0, using the - character in your module names can suddenly become an issue once you start adding more feature modules to your project. This error is particularly odd, as the - character features in many of Google’s instant app samples, including the instant app Codelabs. 

If Android Studio does start complaining about the android:splitName attribute, then double-check that you’re running the latest release of Android Studio 3.0. You may also be able to resolve this issue by cleaning and then rebuilding your project.

If the problem persists, then as a last resort you may have to spend some time going through each of your modules and removing the - character.  

And If All Else Fails:

  • Clean and rebuild your project. Select Build > Clean Project from the Android Studio toolbar, followed by Clean > Rebuild project.
  • Try a different AVD. If you encounter an error whenever you try to deploy your instant app to an AVD, then you should test whether this problem persists when you’re using an AVD that has different specifications. While abandoning an AVD without at least verifying why your project is refusing to run on this device isn’t something you’ll want to carry through to your production apps, you can generally get away with bending the rules a bit when you’re experimenting with a new feature on an early access version of Android Studio. In particular, you may have more success when testing your instant app on an AVD that’s running Android O, compared with AVDs that are running an earlier version of Android. 
  • Check that you haven’t missed an update. At the time of writing, the Android Studio team are releasing a new Canary build on a weekly basis, so it’s always worth double-checking that you have the very latest version of Android Studio installed. In theory, each new release should fix all the issues discovered in the previous build, so if you aren’t running the latest version then it’s possible the problem you're experiencing has already been fixed in a more recent build. 

Distributing Your Instant App

Once you’ve finished testing your instant app project, the next steps are arranging some alpha and beta testing, and then you’re ready to unleash your app on the public! 

You can complete all these tasks via the Google Play Console, and if you’ve ever released a “regular” installable app, then this process should feel very familiar: 

  • Navigate to the Play Console.
  • Upload your application, if you haven’t already.
  • Open the Play Console’s side-menu and select All applications.
  • Select the application you want to test or publish. 
  • Select Android Instant Apps from the left-hand menu. 

Setup testing and distribution for your instant app components by selecting Android Instant Apps from the Play Consoles left-hand menu

You can then choose from the following track types, depending on whether you want to test or publish your app: 

  • Instant app pre-release. This section contains all the settings you need to send pre-release candidates to your testers. Note that in order to use these settings, you’ll need to have created at least one list of testers; if you haven’t completed this step then you can create a list by selecting Settings > Manage testers > Create list from the Play Console’s side menu. 
  • Instant app development. This section allows you to deploy your application to your testers. Again, you’ll need to have created at least one list of testers in order to use the settings in this section.  
  • Instant app production. Once you’re happy with your app, this section contains everything you need to prepare, review and publish your application to the Google Play store. 

Troubleshooting

When you try to publish a project that has instant app support, it’s possible that you may encounter the following error: 

Your site ' www.example.com ” has not been linked through the Digital Assets Link protocol to your app.

If this occurs, then check that:

  • Your Digital Asset Links file (assetlinks.json) is publicly available, and isn’t protected by any form of authentication, internal IP, or firewall. 
  • All the URLs that are mapped to your feature modules are accessible externally. If your app uses any URLs that are only available internally, then you won’t be able to upload your app to the Google Play Console. 
  • The domain you’re using isn’t already associated with another application, as currently multiple instant apps cannot use the same domain. 
  • Your server has a valid SSL certificate from a public or trusted certificate authority. 

Best Practices

Instant apps are an entirely new way of consuming Android applications, so it’s no surprise that they have their own best practices.

In this section, we’re going to ensure you’re getting the most out of this new feature, by taking a look at some instant app best practices. 

Provide as Much Functionality as Possible Before Asking the User to Log In

It’s not all that unusual for installable apps to ask the user to create an account on the very first screen—after all, if the user has already committed to installing an app, then they’re unlikely to be scared off by that app asking for their email address!

However, instant apps are a completely different story, as it’s possible for a user to launch an instant app module without knowing anything about the related application. Imagine a friend has sent you a link with zero explanation, and tapping that link launches an instant app. You have no idea what this app has to offer or who created it, but it immediately asks for your email address—how likely are you to hand over this information?

If your instant app includes a login experience, then you should try to delay this login dialog for as long as possible. Giving the user more time to experience your app’s content and functionality will increase the chances of them creating an account when prompted. 

Even if your installable app revolves around the user creating an account, you should still try and design your instant app modules so users can complete the task that prompted them to launch this module, before you ask them to create an account.

Consider Your Entry Points

Most installable apps only have a few entry points—typically, these are limited to the first Activity the user sees when they launch your app, and any Activities that can be started by implicit or explicit intents. 

Instant apps have far more entry points, as each feature module must have at least one entry point, and can potentially have multiple entry points.

When you add instant app support to your app, one of the most important decisions you need to make is which Activity (or Activities) would serve as the best entry point for each module. You should select your entry points carefully, as ideally each entry point should:

  1. Allow the user to complete the task that prompted them to launch this module in the first place.
  2. Make the best possible first impression on users who may be experiencing your app for the first time.
  3. Provide all the context the user needs to understand what your app has to offer, just in case someone launches this module with zero background information about your app. 

Provide a Seamless Experience for Users Who Migrate From Instant to Installable 

Your app’s user interface, navigation, functionality, and overall look and feel should be constant across all your instant app modules and your installable APK. If you handed someone a device with your application already running, they should be unable to tell whether they’re looking at your app’s instant or its installable form. 

In addition, any instant app user who takes the plunge and installs your app should be able to pick up exactly where they left off. For example, you could transfer the stored app state from your instant app to your installable app using either cookies or local storage. 

Create Small, Lightweight Modules

Since instant apps are loaded on demand, the size of the instant app binary has a huge impact on how easily users can access your app.  

The Android team have imposed a 4 MB limit on each instant app component (that’s the size of the feature module plus your project’s base feature module), but you should aim to make your modules even more lightweight if possible. 

If you’re struggling to streamline a particular module, then take a critical look at what you’ve included in that module, as it may be possible to rework a single module into several smaller, self-contained modules. 

Never Use Instant Apps as an Advert for Your Installable App

Although you should never design an instant app solely to drive traffic to your installable app, there are two kinds of installation prompts that you can use in your instant apps: 

  • implicit installation prompts
  • explicit installation prompts

Implicit installation prompts are UI elements that the user interacts with expecting to trigger a certain feature, only to encounter an installation prompt instead.

This approach is reminiscent of Android’s runtime permissions model, as it allows you to issue installation prompts in context. Get the context right, and you should never have to explain why you’re displaying a particular installation prompt. For example, if the user encounters an installation prompt after tapping a Share this route with others button, then the message is clear: if you want to access this functionality, then you need to install the app. 

Just don’t get carried away, to the point where your instant app starts to feel like an advert for your installable app. Your users will quickly get frustrated if your app is constantly teasing them with functionality that they can’t access, so limit yourself to a maximum of three implicit installation prompts per instant app module. You should also carefully consider where you place these installation prompts, to avoid the user encountering multiple prompts in quick succession. 

Explicit installation prompts are UI elements that are clearly going to display an installation dialog when the user interacts with them, for example a button with “Install app” emblazoned across the front. 

All explicit installation prompts should use the Material Design "get app" icon, and if you include any supporting text then choose your words carefully to avoid creating the impression that your instant app is in any way an incomplete or lesser version of your “real” app—so avoid saying things like upgrade now or install the full application

Consider the Metrics You Want to Track

Traditionally, looking at the total number of installs has been one of the most effective ways of gauging an app’s success. However, when you add instant app support to a project, you remove the need for users to install that app, which requires you to rethink how you measure this app’s performance.

Instead of counting installations, you may want to measure metrics that relate to levels of user engagement, such as how much time users are investing in your app, the total number of tasks they complete, or how many users pay repeat visits to your instant app modules. 

It’s also important to remember that even though instant app APKs and installable APKs are built from the same project, they represent two entirely different ways of consuming your application. To get the most accurate insight into your app’s performance, you’ll need a way of differentiating between the metrics gathered from your instant app component(s) and the metrics gathered from your installable app. 

Conclusion

In this three-part series, we looked at how to add instant app support to your Android applications. If you’ve been following along from the beginning, then you’ll have successfully created a project consisting of two instant apps, which are triggered by different URLs. 

If you want to get more experience with instant apps, then you could continue adding features modules to this project, or work on expanding the mylocation-directions module so that it offers some real functionality. 

In the meantime, check out some of our other posts on Android app development!

  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali
  • Machine Learning
    Create Chatbots on Android With IBM Watson
    Ashraff Hathibelagal
  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby
  • Kotlin
    Kotlin From Scratch: Variables, Basic Types, and Arrays
    Chike Mgbemena
  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal
  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena

12:00

Context-Based Programming in Go

Go programs that run multiple concurrent computations in goroutines need to manage their lifetime. Runaway goroutines can get into infinite loops, deadlock other waiting goroutines, or just take too long. Ideally, you should be able to cancel goroutines or have them time out after a fashion. 

Enter content-based programming. Go 1.7 introduced the context package, which provides exactly those capabilities as well as the ability to associate arbitrary values with a context that travels with the execution of requests and allows out-of-band communication and information passing. 

In this tutorial, you'll learn the ins and outs of contexts in Go, when and how to use them, and how to avoid abusing them. 

Who Needs a Context?

The context is a very useful abstraction. It allows you to encapsulate information that is not relevant to the core computation like request id, authorization token, and timeout. There are several benefits of this encapsulation:

  • It separates the core computation parameters from the operational parameters.
  • It codifies common operational aspects and how to communicate them across boundaries.
  • It provides a standard mechanism to add out-of-band information without changing signatures.

The Context Interface

Here is the entire Context interface:

The following sections explain the purpose of each method.

The Deadline() Method

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

The Done() Method

Done() returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done() return the same value.

  • The context.WithCancel() function arranges for the Done channel to be closed when cancel is called. 
  • The context.WithDeadline() function arranges for the Done channel to be closed when the deadline expires.
  • The context.WithTimeout() function arranges for the Done channel to be closed when the timeout elapses.

Done can be used in select statements:

See this article from the Go blog for more examples of how to use a Done channel for cancelation.

The Err() Method

Err() returns nil as long as the Done channel is open. It returns Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed or the timeout expired. After Done is closed, successive calls to Err() return the same value. Here are the definitions:

The Value() Method

Value returns the value associated with this context for a key, or nil if no value is associated with the key. Successive calls to Value with the same key return the same result.

Use context values only for request-scoped data that transitions processes and API boundaries, not for passing optional parameters to functions.

A key identifies a specific value in a Context. Functions that wish to store values in Context typically allocate a key in a global variable and use that key as the argument to context.WithValue() and Context.Value(). A key can be any type that supports equality.

Context Scope

Contexts have scopes. You can derive scopes from other scopes, and the parent scope has no access to values in derived scopes, but derived scopes have access to the parent's scopes values. 

The contexts form a hierarchy. You start with context.Background() or context.TODO(). Whenever you call WithCancel(), WithDeadline(), or WithTimeout(), you create a derived context and receive a cancel func. The important thing is that when a parent context is cancelled or expired, all its derived contexts.

You should use context.Background() in the main() function, init() functions, and tests. You should use context.TODO() if you're not sure what context to use.

Note that Background and TODO are not cancellable.

Deadlines, Timeouts, and Cancellations

As you recall, WithDeadline() and WithTimeout() return contexts that get cancelled automatically, while WithCancel() returns a context and must be cancelled explicitly. All of them return a cancel function, so even if the timeout/deadline didn't expire yet, you may still cancel any derived context. 

Let's examine an example. First, here is the contextDemo() function with a name and a context. It runs in an infinite loop, printing to the console its name and its context's deadline if any. Then it just sleeps for a second.

The main function creates three contexts: 

  • timeoutContext with a three-second timeout
  • a non-expiring cancelContext
  • deadlineContext, which is derived from cancelContext, with a deadline four hours from now

Then, it launches the contextDemo function as three goroutines. All run concurrently and print their message every second. 

The main function then waits for the goroutine with the timeoutCancel to be cancelled by reading from its Done() channel (will block until it's closed). Once the timeout expires after three seconds, main() calls the cancelFunc() that cancels the goroutine with the cancelContext as well as the last goroutine with the derived four hours deadline context.

Here is the output:

Passing Values in the Context

You can attach values to a context using the WithValue() function. Note that the original context is returned, not a derived context. You can read the values from the context using the Value() method. Let's modify our demo function to get its name from the context instead of passing it as a parameter:

And let's modify the main function to attach the name via WithValue():

The output remains the same. See the best practices section for some guidelines about using context values appropriately.

Best Practices

Several best practices have emerged around context values:

  • Avoid passing function arguments in context values.
  • Functions that wish to store values in Context typically allocate a key in a global variable.
  • Packages should define keys as an unexported type to avoid collisions.
  • Packages that define a Context key should provide type-safe accessors for the values stored using that key.

The HTTP Request Context

One of the most useful use cases for contexts is passing information along with an HTTP request. That information may include a request id, authentication credentials, and more. In Go 1.7, the standard net/http package took advantage of the context package getting "standardized" and added context support directly to the request object:

Now it's possible to attach a request id from the headers all the way to the final handler in a standard way. The WithRequestID() handler function extracts a request ID from the "X-Request-ID" header and generates a new context with the request id from an existing context that it uses. It then passes it to the next handler in the chain. The GetRequestID() public function provides access to handlers that may be defined in other packages.

Conclusion

Context-based programming provides a standard and well-supported way to address two common problems: managing the lifetime of goroutines and passing out-of-band information across a chain of functions. 

Follow the best practices and use contexts in the right context (see what I did there?) and your code will improve considerably.

August 22 2017

23:02

Milton Glaser in conversation with Debbie Millman

A great conversation between two of my favourite designers, Milton Glaser and Debbie Millman.

The piece at the end rings particularly true at this stage of my life, getting to watch the joy and excitement of kids while they play the simplest of games, and thinking about how all of us were like that.

12:00

Image Filtering in Python

Have you ever come across a noisy image? I mean an image that was not that clear when viewing it? I think we do come across such images very often, especially when many images nowadays are taken by our mobile phone cameras or low-resolution digital cameras.

If you had only that noisy image which means something to you, but the issue is that it cannot be viewed properly, would there be a solution to recover from such noise?

This is where image filtering comes into play, and this is what I will be describing in this tutorial. Let's get started!

Image Filtering

Image filtering is a popular tool used in image processing. At the end of the day, we use image filtering to remove noise and any undesired features from an image, creating a better and an enhanced version of that image. Two types of filters exist: linear and non-linear. Examples of linear filters are mean and Laplacian filters. Non-linear filters constitute filters like median, minimum, maximum, and Sobel filters.

Each of those filters has a specific purpose, and is designed to either remove noise or improve some aspects in the image. But how is filtering carried out? This is what we will see in the next section.

How Do We Perform Image Filtering?

In order to carry out an image filtering process, we need a filter, also called a mask. This filter is usually a two-dimensional square window, that is a window with equal dimensions (width and height). 

The filter will include numbers. Those numbers are called coefficients, and they are what actually determines the effect of the filter and what the output image will look like. The figure below shows an example of a 3x3 filter, having nine values (coefficients).

An example 3x3-filter

To apply the filter, the 3x3 window is slid over the image. This process of sliding a filter window over an image is called convolution in the spatial domain. The window will be placed on each pixel (i.e. think of it as a cell in a matrix) in the image, where the center of the filter should overlap that pixel. 

Once this overlap happens, the pixels in the sub-image that the filter is on top of will be multiplied with the corresponding coefficients of the filter. In this case, we will have a new matrix with new values similar to the size of the filter (i.e. 3x3). Finally, the central pixel value will be replaced by a new value using a specific mathematical equation depending on the type of filter used (i.e. median filter).

I know the above paragraph is a bit wordy. Let's take an example to show how an image filter is applied in action. Suppose we have the following sub-image where our filter overlapped (i and j refer to the pixel location in the sub-image, and I refers to the image):

An example sub-image

The convolution of our filter shown in the first figure with the above sub-image will look as shown below, where I_new(i,j) represents the result at location (i,j).

The process is repeated for each pixel in the image, including the pixels at the boundary of the image. But, as you can guess, part of the filter will reside outside the image when placing the filter at the boundary pixels. In this case, we perform padding

This process simply means that we insert new pixel values in the sub-image under the part of the filter that comes outside of the image before the convolution process, since that part apparently does not contain any pixel values. It is outside of the image! Those padded pixels could be zeros or a constant value. There are other methods for setting the padding values, but these are outside the scope of this tutorial.

I think that's enough theory for now, so let's go ahead and get our hands dirty with coding! In this tutorial, I will be explaining the median filter (i.e. non-linear) and the mean filter (i.e. linear) and how we can implement them in Python. 

Median Filter

In the median filter, we choose a sliding window that will move across all the image pixels. What we do here is that we collect the pixel values that come under the filter and take the median of those values. The result will be assigned to the center pixel. 

Say our 3x3 filter had the following values after placing it on a sub-image:

An example median-filter

Let's see how to calculate the median. The median, in its essence, is the middle number of a sorted list of numbers. Thus, to find the median for the above filter, we simply sort the numbers from lowest to highest, and the middle of those numbers will be our median value. Sorting the values in our 3x3 window will give us the following:

To find the middle number (median), we simply count the number of values we have, add 1 to that number, and divide by 2. This will give us the location of the middle value in the window, which is our median value. So the median value will be at location 9+1/2 = 5, which is 59. This value will be the new value of the pixel under the center of our 3x3 window.

This type of filter is used for removing noise, and works best with images suffering from salt and pepper noise. The image below shows an example of a picture suffering from such noise:

An example of salt-and-pepper noise

Now, let's write a Python script that will apply the median filter to the above image. For this example, we will be using the OpenCV library. Kindly check Install OpenCV-Python in Windows and Install OpenCV 3.0 and Python 2.7+ on Ubuntu to install OpenCV.

To apply the median filter, we simply use OpenCV's cv2.medianBlur() function. Our script can thus look as follows:

Notice that I have used argparse, as it is a good practice to be flexible here, and use the command-line to pass the image we want to apply the median filter on as an argument to our program. 

After passing our image as a command-line argument, we read that image using the cv2.imread() function. We then apply the median filter using the medianBlur() function, passing our image and filter size as parameters. The image is displayed using the cv2.imshow() function, and is saved to the disk using cv2.imwrite().

The result of the above script is as follows:

The result of the processed image

Well, what do you think? Very beautiful—a nice and clean image without noise.

You can download the above code from my median-filter repository on GitHub.

Mean Filter

The mean filter is an example of a linear filter. It basically replaces each pixel in the output image with the mean (average) value of the neighborhood. This has the effect of smoothing the image (reducing the amount of intensity variations between a pixel and the next), removing noise from the image, and brightening the image.

Thus, in mean filtering, each pixel of the image will be replaced with the mean value of its neighbors, including the pixel itself. The 3x3 kernel used for mean filtering is as shown in the figure below, although other kernel sizes could be used (i.e. 5x5):

An example of the Mean Filter

What the above kernel is actually trying to tell us is that we sum all the elements under the kernel and take the mean (average) of the total.

An important point to mention here is that all the elements of the mean kernel should:

  • sum to 1
  • be the same

Let's take an example to make things more clear. Say we have the following sub-image:

An example of the sub-image mean filter

When applying the mean filter, we would do the following:

The exact result is 44.3, but I rounded the result to 44. So the new value for the center pixel is 44 instead of 91.

Now to the coding part. Let's say we have the following noisy image:

Another noisy image

What we want to do at this point is apply the mean filter on the above image and see the effects of applying such a filter.

The code for doing this operation is as follows:

Notice from the code that we have used a 3x3 kernel for our mean filter. We have also used the filter2D() function to apply the mean filter. The first parameter of this function is our input image, the second is the desired depth of the output image ddepth, and the third parameter is our kernel. Assigning -1 for the ddepth parameter means that the output image will have the same depth as the input image.

After running the code on our noisy image, this was the result I obtained:

A result of the noisy image after a filter

If you observe the output image, we can see that it is smoother than the noisy image. Mission done!

You can download the above code from my mean filter repository on GitHub.

Conclusion

As we have seen in this tutorial, Python allows us to carry out advanced tasks like image filtering, especially through its OpenCV library, in a simple manner.

Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

02:00

Expired: Join Envato Elements for Just $19!

This Promotion is Now Expired

Unfortunately this promotion has now come to an end. You can read about the other promotions that are happening for Envato's birthday though. There's still lots to explore!

What is Envato Elements?

To celebrate Envato's 11th birthday, we're excited to share a one-day promotion for Envato Elements. Usually $29, for one day only you can lock in a lifetime price of just $19 per month!

Envato Elements provides inspiring and ready-to-use photos, templates, fonts, assets, icons, and much more. For a single monthly fee, you get unlimited downloads to use in your projects and design work.

Now with over 33,000 beautiful design templates and assets (and over 300,000 photos), it's the only design subscription you'll ever need.

Not only that, Envato Elements now includes access to every Tuts+ course and eBook. That's over 1,000 courses on web design, code, and graphic design, as well as the entire A Book Apart and Smashing Magazine eBook libraries!

Head over to Envato Elements any time today, and you can take advantage of a one-off discount, for the lifetime of your membership. Join today for $19 and you lock that price in for all future months.

Act fast, though. The promotion ends tomorrow, at 12pm Wednesday 23rd August, AEST (Australian time). You can see the end time of the promotion in other time zones, to make sure you don't miss out!

What Else is Happening?

There's lots more planned for Envato's birthday over the coming weeks. Keep an eye out for another post this week with all the details, but you can visit Envato's birthday landing page to find out more about:

  • Special free files from our marketplaces
  • 50% discounts on over 300 Envato Market files
  • A 20% discount on Envato Studio services

Thanks for celebrating our birthday with us, and we hope you'll enjoy this fantastic, one-off Envato Elements discount!

August 21 2017

12:55

3 Terrible Mistakes of iOS Developers

Coding an iOS app is hard work, so it makes sense that devs want to cut corners and find ways to get their app online as quickly as possible. But a successful app will be around for a long time—that means years of bug fixing, feature enhancements, and working with other coders. 

In this article, I'll share three things to steer clear of during iOS development that will make your apps easier to build and easier to maintain.

1. Don't Be Afraid of Constants

While it seems that variables are more versatile than constants, it still isn't a good idea to default to variables when you can use a constant instead. So what's so great about constants? A number of things, actually!

Readability

One of the best things about constants is their readability. Let's look at an example: you are writing an e-commerce type app. You may want to add a local sales tax rate of 8.75%, but other developers wouldn't know what that number means. Let's look at an example: 

A developer named Steven comes aboard your team, and he is a coding ninja, but he lives in a country overseas. In this country, there is no such thing as sales tax (lucky Steven), and therefore, he doesn't know anything about it. 

If you were to use a variable for your sales tax rate, he could change it in just one line of code, and the results of that could seriously harm your app. Just changing the keyword from var to let would have the compiler telling him that the value cannot be changed, and he would realize that you intended it to be immutable.

Value Reference

Another way that let is useful is to refer to a value in your code. If you are making an app, you may want a certain color scheme. Instead of copy-pasting your colors wherever they are needed, you can use a constant to refer to that specific color.

This way, if you were to change the color, you would just need to change it in one place instead of finding every single reference to the color and changing it multiple times.

Class or Struct Instantiation 

When you create a singleton, you also need to create a shared instance of the class. You would usually do this by declaring a static let inside of the class declaration. After that, you would name the constant and assign it to an instance of the class and use it throughout your app.

Adding to that, if you needed to instantiate (create an instance of) a regular class, perhaps in ViewController.swift, you would create a constant and assign it to an instance of your desired class, leaving you with a reference that you can easily take advantage of throughout the file. This is another great use of constants.

As you can see, there are many reasons that constants are great. They increase code readability, they are useful for storing immutable values, and clearly, they are not as useless as you think. Do yourself a favor by getting in the habit of using constants whenever possible, and only changing them into variables if you absolutely need to mutate their values—it will make you a better programmer.

2. Don't Force Unwrap Optionals

Optionals are a very powerful feature of Swift. They are just types like int and String, annotated by a question mark after the type declaration. If you want to declare a variable as an optional string, you would just write:

This tells the compiler that there either can be a value or there might be no value at all. String? and String are considered to be two different types.

Think of optionals as a gift box. As I mentioned, this gift box may or may not have a value, and if you want to find out, you must unwrap the optional first. There are many ways of doing this:

The Wrong Way

Forced Unwrapping

This operation (performed by using an exclamation mark) is called the Bang Operator. Don't use it! Force unwrapping your variables is never a good idea. If the value of the optional you are trying to unwrap is nil (nothing), your app will crash, and who wants that? Anyway, let's look at the following block of code:

In this example, the app would crash because we never defined a value for someVariable, and we are trying to assign it to a variable of type String. This defeats the whole purpose of optionals, which are there to help protect us from errors like this! 

Let's look at some of the correct ways of handling this same situation.

The Right Way

Optional Binding 

This is one of the most popular methods of dealing with optionals. In this method, you simply assign an optional value to a constant using an if statement. If the optional can be unwrapped, the compiler enters the closure, and you can use the constant that was created. Otherwise, you fall into an else statement and pretend that nothing happened. Let's look at an example of this:

Using the same example as last time, but with optional binding instead, we can see that instead of crashing, the compiler enters the else statement and prints "error."

Optional Chaining

Another common way to safely unwrap optionals is optional chaining. This is a great way to avoid nil values cleanly, and in one line of code. When you use this method and come across a nil value, that line of code simply ceases to execute. Here's an example of this:

Basically, if someClass is nil, the entire line will not execute, and the value of somethingElse will become nil. If there is a value, like the example above, it will be assigned to the variable somethingElse. In either case, the app will not crash.

Nil Coalescing

This method handles optionals with a single line, but unlike the method above, you need to provide a default or "else" case (in case the optional turns out to be nil). Let's look at an example:

Although this may seem a little cryptic, it simply means that if the left-hand statement has a value (in other words is not nil), it will be used. If it is nil, then the default statement will be used—in this case, a hard-coded string. It is worth noting that the right-hand statement needs to be of a non-nil and non-optional type (otherwise, the purpose of this would be defeated).

3. Don't Ignore Architecture

Another common mistake is failing to structure your code in a way that it is sustainable, maintainable, and efficient. Many people cram all of their code into their ViewController classes, and this can make your code hard to change and debug.

As cliché as this may sound, this really is the foundation of how you program your app. Let's say you are building a house, your dream home. This house is five stories high, so if you don't build a strong foundation and follow the blueprints, it will probably just topple over.

The foundation of an iOS app is the design pattern that you choose. Let's look at two of the most commonly used patterns.

MVC (Model-View-Controller)

The Model-View-Controller or MVC design pattern separates each part of your code into three parts: the model, the view, and the controller. 

  • Model: The model is essentially the data of the app. This handles things like reusable structures and classes that deal only with the data of the app. The model does not handle anything relating to the view or how the information will be shown to the user.
  • View: The view is responsible for only the visual representation of the data, and it also handles user interaction. It does not handle anything regarding data, nor does it deal with specific views. It is simply a reusable class which can be used multiple times without repeating code.
  • Controller: The controller is the boss. It brings data from the model, and then sends it to the view to finally display it to the user. This is typically in ViewController.swift, and it listens to input and changes the model as needed.

There are many variations of this, such as MVVM and MVP. It's worth reading up on them, but the principle is similar to MVC, so we won't be covering them here. These are all called design patterns, and they make our code modular. 

Let's look at another design pattern which can complement the app pattern you choose to use.

Singletons

A singleton is a single instance of a class that is present at all times in memory. So why do we care about this? Well, let's say that you are building an app that connects to a database. You need a place to put all of your data service connections. This would be a perfect place to use singletons. Look at the code below; it will show you how to construct a singleton:

If you follow these simple tips, your app will be easier to maintain, and bugs will be more obvious to find before your customers do.

Conclusion

In this article, we saw three mistakes that iOS app developers make that might seem to make coding easier, but actually cost a lot more work in the long term. 

Remember, building an app is only part of the challenge—you also need to fix bugs, add features, and share the code with other developers. Following best practices like using constants, handling optionals correctly, and using architectural patterns will make your app easier to build and easier to maintain.

While you're here, check out some of our other posts on iOS app development!

  • Swift
    What's New in Swift 4
    Patrick Balestra
  • Android SDK
    Google I/O 2017 Aftermath: What's New in Android Studio 3?
    Jessica Thornsby
  • iOS SDK
    Faster Logins With Password AutoFill in iOS 11
    Patrick Balestra

12:00

Asynchronous I/O With Python 3

In this tutorial you'll go through a whirlwind tour of the asynchronous I/O facilities introduced in Python 3.4 and improved further in Python 3.5 and 3.6. 

Python previously had few great options for asynchronous programming. The new Async I/O support finally brings first-class support that includes both high-level APIs and standard support that aims to unify multiple third-party solutions (Twisted, Gevent, Tornado, asyncore, etc.).

It's important to understand that learning Python's async IO is not trivial due to the rapid iteration, the scope, and the need to provide a migration path to existing async frameworks. I'll focus on the latest and greatest to simplify a little.

There are many moving parts that interact in interesting ways across thread boundaries, process boundaries, and remote machines. There are platform-specific differences and limitations. Let's jump right in. 

Pluggable Event Loops

The core concept of async IO is the event loop. In a program, there may be multiple event loops. Each thread will have at most one active event loop. The event loop provides the following facilities:

  • Registering, executing and cancelling delayed calls (with timeouts).
  • Creating client and server transports for various kinds of communication.
  • Launching subprocesses and the associated transports for communication with an external program.
  • Delegating costly function calls to a pool of threads. 

Quick Example

Here is a little example that starts two coroutines and calls a function in delay. It shows how to use an event loop to power your program:

The AbstractEventLoop class provides the basic contract for event loops. There are many things an event loop needs to support:

  • Scheduling functions and coroutines for execution
  • Creating futures and tasks
  • Managing TCP servers
  • Handling signals (on Unix)
  • Working with pipes and subprocesses

Here are the methods related to running and stopping the event as well as scheduling functions and coroutines:

Plugging in a new Event Loop

Asyncio is designed to support multiple implementations of event loops that adhere to its API. The key is the EventLoopPolicy class that configures asyncio and allows the controlling of every aspect of the event loop. Here is an example of a custom event loop called uvloop based on the libuv, which is supposed to be much faster that the alternatives (I haven't benchmarked it myself):

That's it. Now, whenever you use any asyncio function, it's uvloop under the covers.

Coroutines, Futures, and Tasks

A coroutine is a loaded term. It is both a function that executes asynchronously and an object that needs to be scheduled. You define them by adding the async keyword before the definition:

If you call such a function, it doesn't run. Instead, it returns a coroutine object, and if you don't schedule it for execution then you'll get a warning too:

To actually execute the coroutine, we need an event loop:

That's direct scheduling. You can also chain coroutines. Note that you have to call await when invoking coroutines:

The asyncio Future class is similar to the concurrent.future.Future class. It is not threadsafe and supports the following features:

  • adding and removing done callbacks
  • cancelling
  • setting results and exceptions

Here is how to use a future with the event loop. The take_your_time() coroutine accepts a future and sets its result after sleeping for a second.

The ensure_future() function schedules the coroutine, and wait_until_complete() waits for the future to be done. Behind the curtain, it adds a done callback to the future.

This is pretty cumbersome. Asyncio provides tasks to make working with futures and coroutines more pleasant. A Task is a subclass of Future that wraps a coroutine and that you can cancel. 

The coroutine doesn't have to accept an explicit future and set its result or exception. Here is how to perform the same operations with a task:

Transports, Protocols, and Streams

A transport is an abstraction of a communication channel. A transport always supports a particular protocol. Asyncio provides built-in implementations for TCP, UDP, SSL, and subprocess pipes.

If you're familiar with socket-based network programming then you'll feel right at home with transports and protocols. With Asyncio, you get asynchronous network programming in a standard way. Let's look at the infamous echo server and client (the "hello world" of networking). 

First, the echo client implements a class called EchoClient that is derived from the asyncio.Protocol. It keeps its event loop and a message it will send to the server upon connection. 

In the connection_made() callback, it writes its message to the transport. In the data_received() method, it just prints the server's response, and in the connection_lost() method it stops the event loop. When passing an instance of the EchoClient class to the loop's create_connection() method, the result is a coroutine that the loop runs until it completes. 

The server is similar except that it runs forever, waiting for clients to connect. After it sends an echo response, it also closes the connection to the client and is ready for the next client to connect. 

A new instance of the EchoServer is created for each connection, so even if multiple clients connect at the same time, there will be no problem of conflicts with the transport attribute.

Here is the output after two clients connected:

Streams provide a high-level API that is based on coroutines and provides Reader and Writer abstractions. The protocols and the transports are hidden, there is no need to define your own classes, and there are no callbacks. You just await events like connection and data received. 

The client calls the open_connection() function that returns the reader and writer objects used naturally. To close the connection, it closes the writer. 

The server is also much simplified.

Working With Sub-Processes

Asyncio covers interactions with sub-processes too. The following program launches another Python process and executes the code "import this". It is one of Python's famous Easter eggs, and it prints the "Zen of Python". Check out the output below. 

The Python process is launched in the zen() coroutine using the create_subprocess_exec() function and binds the standard output to a pipe. Then it iterates over the standard output line by line using await to give other processes or coroutines a chance to execute if output is not ready yet. 

Note that on Windows you have to set the event loop to the ProactorEventLoop because the standard SelectorEventLoop doesn't support pipes. 

Conclusion

Don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

Python's asyncio is a comprehensive framework for asynchronous programming. It has a huge scope and supports both low-level as well as high-level APIs. It is still relatively young and not well understood by the community. 

I'm confident that over time best practices will emerge, and more examples will surface and make it easier to use this powerful library.

August 17 2017

13:48

One Brand, Many Stories: Understanding Color Schemes In Site Design

Color scheme is an important part of web design and can help distinguish your brand and attach emotional content to your message before users read a single word. And though color psychology is not universal, understanding the basic emotional valence of different color stories and how they relate to your brand can help you make smart design stories.

Is your color story cohering with your brand message or is it turning potential customers off? These tips can help you better understand why color isn’t purely aesthetic when it comes to branding.

What’s The Story?

Many graphic designers come to the job with limited experience of the client brand. At the beginning of each job, then, they have to spend time studying the brand’s history, overall narrative, and their customer base. This information forms the backbone of decisions about color scheme, as well as format and other structural design choices.

Platform Conflicts

One common mistake that graphic designers make when developing a brand’s color story is the failure to account for today’s mobile culture. The fact is that most people have unlimited data plans and surf the web largely on their cell phones, even doing most of their online shopping on mobile devices. For graphic designers, that means it’s especially important to consider how colors show up on cell phone screens.

Similarly important when considering the role of platforms in web accessibility is color contrasts. On a larger screen, a complex, monochromatic design may be appealing, but on a small cell screen, increased contrast enables easy navigation, makes text readable, and reduces user bounce rate. Your colors should tell a story but the rest of the brand messaging needs to come through.

From Theory To Practice

Most children learn basic color theory in grade school with the introduction of color wheels and complementary and contrasting colors; graphic designers, even those without formal training, often have a deep sense of how colors work together. But what does color theory’s application to a brand story look like in practice? Let’s consider T-Mobile’s cell phone plan page.

Across the board, T-Mobile embraces pink and black as the core of its color scheme, an interesting choice in a culture where pink is associated with very feminine traits. At the same time, black is typically associated with edginess and sophistication, adding a twist to the color story.

Considering that T-Mobile pushes a narrative of reliability based on their extensive network, it could be argued that the pink is meant to suggest an almost maternal support structure to the brand. They’ll take care of you. Simultaneously, the black base reminds customers that T-Mobile is still on the cutting edge. The color story plays both sides of the field.

Ultimately, making the right color choices for your brand is a sink or swim proposition. Customers form an opinion of a brand or product within 90 seconds, and as much as 90% of product interaction is based on color. Get it right and you’re set, but miss the mark and you’ll never get customers past the landing page.

The post One Brand, Many Stories: Understanding Color Schemes In Site Design appeared first on Devlounge.

August 15 2017

08:00

User-Centered Design Is Everyone’s Responsibility: A Launch Checklist

I cannot count how many large-scale projects my team has been a part of where we’re scrambling last-minute to take care of some seemingly small but integral task necessary for launch. I’ve talked to others in the web design and marketing industry; my team is not alone in this launch frenzy. But does that make this odd ritual okay or even acceptable?

The risk when things are missed prior to launch

The worst case scenario? Once live, a project stakeholder notices the missteps and calls out the project team, damaging trust, credibility, and ultimately the relationship.

Scratch that.

The worst case scenario for missed items prior to a project launch are when the end user stumbles upon them. This can result in a lost purchase, a drop in satisfaction, and a big impact on the bottom line and perception of the product and/or company. And only 21% of internet users give a brand another chance after a negative experience (Harris Poll, 2017). We cannot afford to get it wrong the first time.

Only 21% of Internet users give a brand another chance after a negative experience (Harris Poll, 2017)

If launch tasks are integral, then why are they commonly overlooked?

What we need is accountability, but accountability cannot exist when there is not a great grasp of what is needed. Many launch tasks are missed not because of their importance but for a myriad of reasons that, when combined, make them hard to spot.

  • Minimal, small in duration
  • The task was not accounted for in the project plan, project estimate, or project scope
  • Lack of ownership
  • Crunched for time

Save the day with a project launch checklist

A project launch checklist is a document that brings greater visibility to small but important tasks that are often overlooked by project teams. Many of these items are crucial to the project launch strategy but are never formally documented.

This checklist can help mitigate the aches and pains of prior-launch anxiety by assigning ownership and distributing responsibility to the team instead of leaving the burden on the shoulders of one or few.

Screen shot of the web site launch list

The checklist

  • Identifies all relevant tasks
  • Assigns ownership
  • Sets due dates

But the work isn’t over

In the user-centered design process, it is EVERYONE’s responsibility to ensure a successful launch, not just the project manager or user experience resource. Don’t wait until the last minute to tackle these integral tasks for launching a project.

It’s also important to note that, once the site is launched, our work is not done: There are maintenance tasks and necessary items that need to be checked post-launch as well. Account for pre- and post-launch tasks in all projects for a smooth transition, happy team members, and satisfied clients.

Great resources exist but none that I have found are easily reusable lists. I’ve taken some of these lists—along with my experience—and put together a list that you can copy and make your own. Go ahead, no strings attached! Happy to share it with you.

Helpful resources

I drew inspiration for this checklist from many launch resource articles, some of the most influential are listed below.

 

August 13 2017

19:59

Tadao Ando’s Hill of Buddha

Tadao Ando Hill of Buddha

For 15 years, the Makomanai Takino cemetery was home to a stone Buddha that sat alone in a field, before the owners decided they wanted to do something to give visitors a more serene appreciation of the figure.

Makomanai Takino Buddha

As it sat (above) before the architectural and landscaping project.

Tadao Ando Hill of Buddha

Cue self-taught architect Tadao Ando and his striking idea: hide the statue.

Tadao Ando Hill of Buddha

The hill is planted with 150,000 lavenders — green in spring, purple in summer, and white with snow in winter.

Tadao Ando Hill of Buddha

“The design intention was to create a vivid spatial sequence, beginning with the long approach through the tunnel in order to heighten anticipation of the statue, which is invisible from the outside.”
— Tadao Ando

Tadao Ando Hill of Buddha Tadao Ando Hill of Buddha Tadao Ando Hill of Buddha

When the hall is reached at the end of the 40-metre approach tunnel, visitors look up at the 1,500 ton Buddha, whose head is framed by a halo of sky.

Tadao Ando Hill of Buddha Tadao Ando Hill of Buddha

Stunning.

Makomanai Takino cemetery was established in 1982, and is open all year. It’s about a 30-minute drive from central Sapporo, or you can take a subway from Sapporo Station to Makomanai Station and then catch the #2 or #3 bus. Visitor information here.

Via Spoon & Tamago.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl