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

Get Started With Firebase Authentication for iOS

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

Firebase is a cross-platform real-time mobile database platform that allows coders to focus on what they do best—coding their apps—without having to worry about DevOps concerns like server infrastructure and database modeling.  Backed by Google, Firebase takes the complexities out of dealing with back-end real-time databases, authenticating users, and working with offline synchronization workflows. 

While there are many solutions out there for BaaS, such as Realm (check out my Realm.io tutorial here on Envato Tuts+) Firebase doesn’t require any prior infrastructure server configuration, as the platform takes care of hosting and in return exposes an SDK.

Beyond a NoSQL real-time database, with Firebase you get analytics, crash-reporting, user authentication, cloud messaging, push notifications and more. The associated costs also scale with your project—as you grow, you move from a freemium model to a per-usage model.

In this tutorial, I'll show you how to set up Firebase on iOS using CocoaPods, and how to authenticate users using two popular methods: email and password or via the phone with SMS. 

To learn about Firebase for Android, check out some of our other tutorials here on Envato Tuts+. 

Your First Firebase App

Prerequisites

You will need the following:

Assumed Knowledge

This tutorial assumes you have a working knowledge of iOS and Swift, as well as some basic experience with CocoaPods. If you need to learn more, check out our Swift tutorials and CocoaPods tutorials.

Objectives of This Tutorial

By the end of this tutorial, you'll have started on a simple Firebase-powered app that makes use of the Firebase SDK to authenticate users, using email and password as well as by SMS. Along the way, you'll learn about:

  1. setting up Firebase with CocoaPods
  2. setting up the App Delegate to connect to Firebase
  3. setting up the provisioning entitlements for Text/SMS user authentication
  4. using FirebaseUI to authenticate users easily

In future tutorials in this series, you will learn to work with other aspects of the Firebase platform, such as using the real-time database to store app data.

Set Up the Project

In this series, we're going to build a to-do app called FirebaseDo. Let’s start by cloning the project from GitHub:

Next we are going to initialize the project to generate a new PodFile, as follows:

pod init

You should see a new file named Podfile located in the root directory of your project. This file basically sets out the libraries we want to use in our project. Open it and add the following Firebase declaration lines:

Save and then enter the following in your terminal to build the pods:

pod install

We will be using FirebaseDo.xcworkspace instead of FirebaseDo.xccodeproj, allowing us to work with the dependency libraries we set up on CocoaPods, so go ahead and open the workspace and then switch to your browser.

Now go to the Firebase panel and create a new project:

Creating a new project in Firebase

Next, click on Add Firebase to your iOS app, which will then walk you step by step through the process of registering your app on Firebase.

Adding Firebase to your iOS app

At some point, it will instruct you to add the GoogleService-info.plist file into your Xcode project:

 Adding GoogleService plist file to your iOS project

You've already added the libraries via CocoaPods, so you can skip the remaining instructions and return to the Firebase console. 

Authenticating Users

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.  (source: Firebase Authentication)

Before we demonstrate how to use FirebaseUI to automate the authenticating your users, we are going to first explore the SDK methods that Firebase exposes as part of the FirebaseAuth Framework Reference API for handling the creation and sign-in of users manually.

Sign Up, Sign In, and Sign Out Users

To create a new user, you would use the Auth.auth().createUser() method block, as follows:

Assuming the errorobject is nil, the user will not only be signed up successfully but will also be signed in. To sign in an existing user explicitly, you would call:

Signing out a user is as easy as calling try! FirebaseAuth.signOut():

We want to be able to handle various potential errors gracefully, in case the authentication calls go astray, and when the error object is not nil (or inversely, the user object is nil), an error has occurred. Consult the Firebase documentation for a list of all common error codes. In our code, we'll only handle a few general errors.

Managing Authentication State Changes

Throughout the app lifecycle, the authentication state will change, so being able to detect when a user has authenticated, or a session has expired, is important in ensuring users don't have access to parts of your app that they shouldn't be accessing.

By creating a handler, .addStateDidChangeListener, you are now able to detect what state the user is in and trigger a specific call, based on that.

Managing Users

After the user has authenticated, you are able to access the user object and obtain user information such as the user’s ID, email address, and photo avatar (if provided). The following method will also assert that the user is indeed currently authenticated with the user object not being nil:

Emailing Users

Firebase provides excellent support for sending users email verifications or a password reset request email.

Anonymous Users

Firebase also has a way to manage the anonymous authentication workflow, which essentially is a temporary account that can be used to authenticate users and provide them with limited access. The idea is at a certain point in time, anonymous users might opt to sign up, and Firebase can then provide a bridge to link their anonymous accounts to their sign-in credentials without having to lose data persisted during their anonymous states. To sign in an anonymous user, you would call:

To transition the user from an anonymous account to an authenticated account (using email and password), you would call the following method within a registration screen view controller, requesting the email and password, and then call the user.link()  method.

Firebase also supports methods for the other federated authentication mechanisms. 

There you have it—we’ve gone through the important API methods that Firebase have provided to handle and authenticate users. While the code I've shown you isn't complicated by any means, Firebase makes it even easier than this, with the introduction of FirebaseUI. In this second half of this tutorial, we are going to add authentication to our sample to-do app.

Implementing FirebaseUI

FirebaseUI provides a drop-in auth solution that handles the UI flows for signing in users with email addresses and passwords, phone numbers, and with popular federated identity providers, including Google Sign-In and Facebook Login. 

Next, we are going to demonstrate how to implement authentication using FirebaseUI.

In the Firebase Console, go to the Authentication tab and enable the following modes of authentication:

  • Email/Password
  • Phone
Adding EmailPassword and Phone support to app

We just saw how to manage and authenticate users manually using the available Firebase SDKs. We are now going to see how to let FirebaseUI do all the heavy lifting for us. In HomeViewController.swift, import the following libraries:

In the UIViewController.swift declaration, add the FUIAuthDelegate:

Below this class declaration, we are going to declare three private variables that we will be working with. These will let us reference our current authentication object, the AuthUI instance, and our authentication listeners, respectively:

Next, let's wire up our View Controller so that when it loads up the first time, we hook up a listener to detect when the authentication state changes using a handler. When the auth state changes, we'll summon the self.loginAction(sender: self) method to bring up our FirebaseUI authentication controller.

In this method, we also instantiate the private variables we've declared earlier, set the authUI delegate to our own class, and finally set the list of other providers we will be supporting, which in our case will be FUIPhoneAuth.

If we wanted to support Google, Facebook or other third-party providers, we could add them to this list. Also note, we don’t need to explicitly include email and password as it is implicit, provided it is enabled it in the Firebase console.

Showing the Login UI

Next we handle the loginAction() method, which would be called in the case that the event listener determines the user is not currently authenticated. All we need to do in this case is present the authUI.authViewController modal FirebaseUI, and it would include the associated authentication providers we declared earlier.

This is where the magic begins, as FirebaseUI handles everything: asking the user to enter his or her email address, determining if the user exists (in which case the user will be asked for their password), or for a new user, collecting their name and nominating a password.

If we were to implement the authentication methods manually, we would need to handle all these different scenarios, including email password resets and so on.

Handling Auth State Changes

Finally, we implement the required protocol for our FIRAuthUIDelegate delegate, which will allow us to listen and handle authentication states. This method will only proceed if an error has indeed occurred, but we can even handle successful authentications.

Phone Authentication Setup

Before we take the app for a spin, we need to add a few more steps to be able to handle phone-based authentication. Phone authentication lets users enter their phone numbers, and verifies their identity via an SMS message that includes a one-time code.

 To obtain the APNs token needed by the Firebase server, implement the following in the AppDelegate.swift file:

As we have already enabled the phone number sign-in in the Firebase console, our next task is to provision FirebaseDo to receive APNs from Firebase, a task you would also do if you want to support push notifications in general. In this case, however, Firebase will send a silent push notification to the device to verify the phone number sign-in request.

You won’t be able to test this authentication method via Xcode Simulator, rather you will need to connect your iPhone to install and run the app.

In Xcode, go to Capabilities and enable Push Notifications. The app will automatically provision and create a FirebaseDo.entitlements file, as shown in the project navigator.

Adding Push Notifications in Xcode

Next, we are going to create an Apple Push Notification Authentication Key to upload to Firebase. In the Apple Developer Portal, under Keys, fill in the name of your project, making sure to tick APNs. Download the resulting .p8 file and take note of the key ID as we are going to need to enter it shortly.

Creating a new Key in the Developer Portal

Switch back to the Firebase Console, and under Project Settings (the gear icon), select the Cloud Messaging tab.  Under iOS App Configuration and APNs Authentication Key, select the Upload button and upload the .p8 file, along with the key ID and app ID. The resulting settings screen should resemble the following:

Adding APNs key in Firebase

Testing the App

And that’s it—we didn’t have to add very much extra code to our app to set it up for a complete signup and login authentication workflow. Let’s build and run the app in Xcode to see FirebaseUI in action. The first time you run the app, you won't be authenticated, so you will get a generic template with the authentication options you’ve chosen in Firebase console.

Modal FirebaseUI authentication screen

It does look a bit bland, but you can customize almost every aspect of the template

Email sign-in prompt in FirebaseUI

Entering a new user’s email address will push the Create Account screen, asking you for your name and password.

Firebase UI authentication determining the user is new prompting for the rest of the information

Completing this form will register you as a new user (although our app will only display a blank screen). To confirm that a new user has been created, you can go to Authentication > Users in your Firebase Console. 

Test out each of the authentication methods, remembering that you will need to log-out in order to re-trigger the authentication prompt.  Re-trigger auth so by adding the following code as the first line in viewDidLoad() after the super call:

This will force the application back to its initial state so that you can test authenticating via phone SMS. Run the app again, this time choosing Sign in With Phone.

Conclusion

In this tutorial, you got an introduction to using Firebase as a back-end platform for your app, and you saw how to authenticate users using the traditional email and password combination, as well as via phone and SMS, an approach made popular by apps like WhatsApp.

We then started building our simple FirebaseDo app, and although it doesn’t do any of the actual reminder-type functionality yet, we will start working on that in the next tutorial. But in just a few lines, we managed to accomplish the following:

  • integrated Firebase to set up an authentication mechanism for email and password
  • added the ability to authenticate via SMS
  • tracked authentication states
  • handled errors gracefully

In the rest of the series, you will get a look at some of the other components of Firebase.

And while you're here, be sure to check out some of our other posts on iOS app development!

2017-07-26T13:26:52.000Z2017-07-26T13:26:52.000ZDoron Katz

Introduction to Android Architecture Components

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

Android was introduced to the world back in 2005, and during those 12 years of existence the platform has achieved amazing success, becoming the most-installed mobile OS. During that time, 14 different versions of the operating system have been launched, with Android always becoming more mature. However, a very important area of the platform continued to be ignored: a standard architecture pattern, capable of handling the platform peculiarities and simple enough to be understood and adopted by the average developer.

Well, better late than never. At the last Google I/O, the Android team finally decided to address this problem and respond to the feedback from developers all over the world, announcing an official recommendation for an Android Application Architecture and providing the building blocks to implement it: the new Architecture Components. And better yet, they managed to do it without compromising the openness of the system that we all know and love.

Architecture Components

In this tutorial, we'll explore the standardized architecture proposed by the Android team at Google I/O and look at the main elements of the new Architecture Components: Lifecycle, ViewModel, LifeData, and Room. We won't pay too much attention to the code, instead focusing on the concept and logic behind these themes. We'll also take a look at some simple snippets, all of them written using Kotlin, an amazing language that is now officially supported by Android.

1. What Was Android Missing?

If you're just beginning your journey as a developer, it's possible that you don't know exactly what I am talking about. After all, application architecture can be an obscure theme at first. But believe me, you will learn its importance soon enough! As an application grows and becomes more complex, its architecture will become more and more important. It can literally make your work a bliss or a living hell.

Application Architecture

Putting it roughly, an application architecture is a consistent plan that needs to be made before the development process starts. This plan provides a map of how the different application components should be organized and tied together. It presents guidelines that should be followed during the development process and forces some sacrifices (generally related to more classes and boilerplate) that in the end will help you to construct a well-written application that's more testable, expandable, and maintainable.

Software application architecture is the process of defining a structured solution that meets all of the technical and operational requirements, while optimizing common quality attributes such as performance, security, and manageability. It involves a series of decisions based on a wide range of factors, and each of these decisions can have considerable impact on the quality, performance, maintainability, and overall success of the application.
— Microsoft's Software Architecture and Design Guide

Good architecture takes many factors into consideration, especially the system characteristics and limits. There are many different architectural solutions out there, all of them with pros and cons. However, some key concepts are common between all visions.

Old Mistakes

Until the last Google I/O, the Android system didn't recommend any specific Architecture for application development. That means that you were completely free to adopt any model out there: MVP, MVC, MVPP, or even no pattern at all. On top of that, the Android framework didn't even provide native solutions for problems created by the system itself, specifically the component's lifecycle.

Great news at the Google IO 2017

So, if you wanted to adopt a Model View Presenter pattern on your application, you needed to come up with your own solution from scratch, writing a lot of boilerplate code, or adopt a library without official support. And that absence of standards created a lot of poorly written applications, with codebases that were hard to maintain and test. 

As I said, this situation has been criticized for years. In fact, I recently wrote about this problem and how to address it in my How to Adopt Model View Presenter on Android series. But the important thing is that after 12 long years, the Android team finally decided to listen to our complaints and to help us with this problem.

2. Android Architecture

The new Android Architecture Guide defines some key principles that a good Android application should conform to and also proposes a secure path for the developer to create a good app. However, the guide explicitly states that the route presented isn't obligatory, and ultimately the decision is personal; it's the developer who should decide which type of architecture to adopt.

According to the guide, a good Android application should provide a solid separation of concerns and drive the UI from a model. Any code that does not handle a UI or operating system interaction should not be in an Activity or Fragment, because keeping them as clean as possible will allow you to avoid many lifecycle-related problems. After all, the system can destroy Activities or Fragments at any time. Also, the data should be handled by models that are isolated from the UI, and consequently from lifecycle issues.

The New Recommended Architecture

The architecture that Android is recommending cannot be easily labeled among the standard patterns that we know. It looks like a Model View Controller pattern, but it is so closely tied to the system's architecture that it's hard to label each element using the known conventions. This isn't relevant, though, as the important thing is that it relies on the new Architecture Components to create a separation of concerns, with excellent testability and maintainability. And better yet, it is easy to implement.

To understand what the Android team is proposing, we have to know all the elements of the Architecture Components, since they are the ones that will do the heavy lifting for us. There are four components, each with a specific role: Room, ViewModel, LiveData, and Lifecycle. All of those parts have their own responsibilities, and they work together to create a solid architecture. Let's take a look at a simplified diagram of the proposed architecture to understand it better.

Android Architecture

As you can see, we have three main elements, each one with its responsibility. 

  1. The Activity and Fragment represent the View layer, which doesn't deal with business logic and complex operations. It only configures the view, handles the user interaction, and most importantly, observes and exhibits LiveData elements taken from the ViewModel.
  2. The ViewModel automatically observes the Lifecycle state of the view, maintaining consistency during configuration changes and other Android lifecycle events. It is also demanded by the view to fetch data from the Repository, which is provided as observable LiveData. It is important to understand that the ViewModel never references the View directly and that the updates on the data are always done by the LiveData entity.
  3. The Repository isn't a special Android component. It is a simple class, without any particular implementation, which is responsible for fetching data from all available sources, from a database to web services. It handles all this data, generally transforming them to observable LiveData and making them available to the ViewModel.
  4. The Room database is an SQLite mapping library that facilitates the process of dealing with a database. It automatically writes a ton of boilerplate, checks errors at compile time, and best of all, it can directly return queries with observable LiveData.

I'm sure you've noticed that we've talked a lot about observables. The Observer Pattern is one of the bases of the LiveData element and Lifecycle aware components. This pattern allows an object to notify a list of observers about any changes on its state or data. So when an Activity observes a LiveData entity, it will receive updates when that data undergoes any kind of modification.

Another Android recommendation is to consolidate its architecture using a Dependency Injection system, like Google's Dagger 2 or using the Service Locator pattern (which is way simpler than DI, but without many of its advantages). We won't cover DI or Service Locator in this tutorial, but Envato Tuts+ has some excellent tutorials about those themes. However, be advised that there are some particularities of working with Dagger 2 and Android Components that will be explained in the second part of this series.

3. Architecture Components

We must dive deep into the aspects of the new components to be able to really understand and adopt this model of architecture. However, we won't get into all the details in this tutorial. Due to the complexity of each element, in this tutorial, we'll only talk about the general idea behind each one and look at some simplified code snippets. We'll try to cover enough ground to present the components and get you started. But fear not, because future articles in this series will dig deep and cover all the particularities of the Architecture Components.

Lifecycle-Aware Components

Most of the Android app components have lifecycles attached to them, which are managed directly by the system itself. Until recently it was up to the developer to monitor the components' state and act accordingly, initializing and ending tasks at the appropriate time. However, it was really easy to get confused and make mistakes related to this type of operation. But the android.arch.lifecycle package changed all that. 

Now, Activities and Fragments have a Lifecycle object attached to them that can be observed by LifecycleObserver classes, like a ViewModel or any object that implements this interface. That means that the observer will receive updates about the state changes of the object that it is observing, like when an Activity is paused or when it is starting. It can also check the current state of the observed object. So it's much easier now to handle operations that must consider the framework lifecycles.

LifecycleObserver reacts to LifecycleEvents

For now, to create an Activity or Fragment that conforms to this new standard, you have to extend a LifecycleActivity or LifecycleFragment. However, it's possible that this won't always be necessary, since the Android team is aiming to completely integrate these new tools with its framework.

The LifecycleObserver receives Lifecycle events and can react through annotation. No method override is necessary.

The LiveData Component

The LiveData component is a data holder that contains a value that can be observed. Given that the observer has provided a Lifecycle during the LiveData instantiation, LiveData will behave according to Lifecycle state. If the observer's  Lifecycle state is STARTED or RESUMED, the observer is active; otherwise, it is inactive

LiveData knows when the data was changed and also if the observer is active and should receive an update. Another interesting characteristic of the LiveData is that it's capable of removing the observer if it's in a Lifecycle.State.DESTROYED state, avoiding memory leaks when observed by Activities and Fragments.

LiveData value updating process

A LiveData must implement onActive and onInactive methods.

To observe a LiveData component, you must call observer(LifecycleOwner, Observer<T>).

The ViewModel Component

One of the most important classes of the new Architecture Components is the ViewModel, which is designed to hold data that is related to the UI, maintaining its integrity during configuration changes like screen rotations. The ViewModel is able to talk with the Repository, getting LiveData from it and making it available in turn to be observed by the view. ViewModel also won't need to make new calls to the Repository after configuration changes, which optimizes the code a lot.

ViewModel is tight to UI Lifecycle

To create a view model, extend the ViewModel class.

To access from a view, you may call ViewProviders.of(Activity|Fragment).get(ViewModel::class). This factory method will return a new instance of the ViewModel or get the retained one, as appropriate. 

The Room Component

Android supported SQLite from the start; however, to make it work, it was always necessary to write a lot of boilerplate. Also, SQLite didn't save POJOs (plain-old Java objects), and didn't check queries at compile time. Along comes Room to solve these issues! It is an SQLite mapping library, capable of persisting Java POJOs, directly converting queries to objects, checking errors at compile time, and producing LiveData observables from query results. Room is an Object Relational Mapping library with some cool Android extras.

Until now, you could do most of what Room is capable of using other ORM Android libraries. However, none of them are officially supported and, most importantly, they can't produce LifeData results. The Room library fits perfectly as the persistent layer on the proposed Android Architecture.

To create a Room database, you'll need an @Entity to persist, which can be any Java POJO, a @Dao interface to make queries and input/output operations, and a @Database abstract class that must extend RoomDatabase.

Adding Architecture Components to Your Project

For now, to use the new Architecture Components, you'll need to first add the Google repository to your build.gradle file.  For more details, see the official guide.

Conclusion

As you can see, the standardized architecture proposed by Android involves a lot of concepts. Don't expect to have a complete understanding of this topic yet. After all, we're merely introducing the theme. But you certainly have enough knowledge by now to understand the logic behind the architecture and the roles of the different Architecture Components.

We talked about most of the topics related to the proposed Android architecture and its components; however, details about the Components implementation and some extras, like the Repository class and the Dagger 2 system cannot be covered by this first part. We'll explore those themes in the next posts.

See you soon!

2017-07-28T10:41:17.410Z2017-07-28T10:41:17.410ZTin Megali

10 React Applications for You to Use, Study, and Apply

$
0
0

React is an awesome way to create interactive UIs. This open-source JavaScript library “allows developers to create large web applications that use data which can change over time, without reloading the page.”

Created by Jordan Walke, an engineer at Facebook, it was first deployed in 2011 and later became open source a few years later. React is a “learn once, write anywhere” library that has become go-to for many mobile app developers.

Here are 10 React applications from Envato Market for you to use, study, and apply, for both pros and beginners alike.

1. Restaurant App Template - React Native

Developing a React UI for a restaurant may seem simple at first. But when you begin to think about the details and complications of a menu, you can easily see how a React application restaurant template is useful.

The Restaurant App Template - React Native handles all the nuances very well, and like any UI, it looks good.

Restaurant App Template - React Native
“Manage your menu, accept orders, send push notifications.”

Features you'll find:

  • orders management
  • multiple languages
  • push notification
  • and more

This React app pulls data from Google's Firebase Realtime Database, so you can manage your menu and make changes without needing to republish the app.

The Restaurant App Template - React Native is great for learning React and provides some nice features that are worth learning about.

2. BeoStore - Complete React Native Template for E-Commerce

Nothing can be quite as crazy as organizing and presenting eCommerce. There is usually a full taxonomy to handle, and each item requires a fairly high baseline of repetitive data depending on what is being sold: data such as sizes, quality, inventory, color, versions, etc.

With the third version released, the BeoStore - Complete React Native Template for E-Commerce is a beautiful example of a React application for eCommerce.

BeoStore - Complete React Native Template for E-Commerce
“Your products will appear clear and can be zoom without any format error.”

Features include:

  • two product list modes
  • flexible product filter
  • user profiles
  • and more

On its lowest level, the UI presented here is top notch. When you consider the depth of data that is being sorted and presented—not to mention the fundamental feature set—this is a React application worth looking at closely.

The BeoStore - Complete React Native Template for E-Commerce is amazing.

3. Tudu - A React Native Todo-List

What kind of list of React applications for you to use, study, and apply would this be without a good to-do application?

That's why I've included the very beautiful Tudu - A React Native Todo-List React application.

Tudu - A React Native Todo-List
“In this source code you have multiple useful features not only for a to-do list app, but for all kind of projects.”

Features you can use:

  • auto grow text input
  • offline storage
  • swipe actions
  • and more

This is a good example of a React application that makes good use of space. Everything is spaced well for mobile and is designed to feel good to the user. With its simple codebase, you can build out your own to-do application or use these design fundamentals to build something completely different. 

Tudu - A React Native Todo-List is one of my favorites.

4. gikApp - React Native Full Application

Being able to leverage a CMS into your React application is a huge plus. WordPress fuels a large portion of the web, while Shopify is one of the leading eCommerce solutions. Learning how to pull this into a mobile app can be a real game changer.

Enter gikApp - React Native Full Application, a full-featured React application.

gikApp - React Native Full Application
“A truly multipurpose native app for your business.”

You'll find features like:

  • multi-tab screen and multi-level menu
  • Shopify sorting and view options
  • cart and checkout system
  • and more

I am a strong supporter of applications that focus on one thing and do it well. However, having a React application that's a bit of an all-in-one solution certainly has its place.

The gikApp - React Native Full Application is ready to be used for just about anything you're cooking up for a business.

5. BeoNews - React Native Mobile App for WordPress

There's hardly a better example of funneling your WordPress-based website into a React mobile app.

Easily get your WordPress site into mobile app form and onto the AppStore and Google Play with BeoNews - React Native Mobile App for WordPress.

BeoNews - React Native Mobile App for WordPress
“BeoNews is an app that does magic for your website by converting your WordPress website into mobile true native app with customized contents within a fillip.”

Features include:

  • easy Facebook integration
  • swipe and animated UI/UX
  • multiple layouts
  • and more

If you're digging deeper into React or you want to get your WordPress-powered website into a mobile app store, this is an excellent place to start.

The BeoNews - React Native Mobile App for WordPress ticks all the right boxes.

6. Sky Webview - Android & IOS React Native App

As much as I like to get my hands dirty and learn how to build from the ground up, sometimes I find that it helps to use beginner-based tools. Once I can complete a project in “easy mode,” I can then dig deeper and learn the ins and outs more easily.

Sky Webview - Android & IOS React Native App can help you get started with React applications without having to dig deep into code.

Sky Webview - Android  IOS React Native App
“No coding required.”

Features you'll find:

  • online theme edit panel
  • unlimited color options
  • over 670 icons
  • and more

I particularly like the “pull to refresh” feature.

Sky Webview - Android & IOS React Native App is a wonderful first-time React application.

7. OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams

If you haven't already needed to bring video to a mobile device, it's only a matter of time. Present live stream video into a React application using OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams.

OpenTV - React Native App AndroidiOS for TV Channels and Livestreams
“You want a simple but complete application, native, allowing to watch TV channels or livestreams or your mobile? OpenTV is what you need!”

Helpful features include:

  • supports both HTTP live streaming and local files
  • player controls and customizable behaviors
  • multiple formats and languages
  • and more

OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams is your React application answer to mobile video.

8. BeoUI - Complete Mobile UI Template for React Native

This is another beautiful UI with plenty of styles that can be used in many different applications.

The BeoUI - Complete Mobile UI Template for React Native will land you on iOS and Android with only one language.

BeoUI - Complete Mobile UI Template for React Native
“A complete mobile UI template for React Native.”

Features include:

  • flat design mixed with wonderful animation and parallax scrolling
  • multiple menu styles
  • WordPress support
  • and more

This Reactive application template packs plenty of punch. With good looks and flexibility, you can build just about anything with BeoUI - Complete Mobile UI Template for React Native.

9. gikFashion - React Native Full eCommerce UI Theme

The thing about fashion-centric solutions is that they need to:

  1. Look good
  2. Be easy to use
  3. Handle a large number of complex assets

gikFashion - React Native Full eCommerce UI Theme does all three of these.

gikFashion - React Native Full eCommerce UI Theme
“...a complete solution for Ecommerce...”

Includes:

  • supports social media sign up and sign in
  • full featured eCommerce
  • online documentation
  • and more

While this React application focuses on fashion, keep in mind that it can be crafted to do much more or less—while delivering some great UI and functionality.

If gikFashion - React Native Full eCommerce UI Theme was clothing, you'd want to wear it.

10. Currency Converter React Native App

A great example of a mobile app that needs to pack in a lot of information and is highly utilitarian is the Currency Converter React Native App.

Currency Converter React Native App
“It has stunning and attractive design and can easily be modified.”

Features include:

  • converts currency based on the current currency market rate
  • AdMob ready
  • ready for iOS and Android

Complete with flags from all countries, create a fully functional currency converter and deliver yourself straight onto the AppStore and Google Play.

The Currency Converter React Native App is worth every penny.

Conclusion

Using, studying, and applying these React applications and strategies is one of the best ways to become a React pro. Digging into complete work, looking close at UI/UX choices, and doing this while building something of your own is your best teacher.

Of course, I would be remiss if I didn't mention some great resources that can help you along the way. There are the React applications on Envato Market, of course, but I highly recommend these React how-to tutorials, React courses, and React eBooks.

Pairing something you want to build with a good template and resource material is a recipe for React application success.

2017-07-28T12:00:14.000Z2017-07-28T12:00:14.000ZEric Dye

10 React Applications for You to Use, Study, and Apply

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

React is an awesome way to create interactive UIs. This open-source JavaScript library “allows developers to create large web applications that use data which can change over time, without reloading the page.”

Created by Jordan Walke, an engineer at Facebook, it was first deployed in 2011 and later became open source a few years later. React is a “learn once, write anywhere” library that has become go-to for many mobile app developers.

Here are 10 React applications from Envato Market for you to use, study, and apply, for both pros and beginners alike.

1. Restaurant App Template - React Native

Developing a React UI for a restaurant may seem simple at first. But when you begin to think about the details and complications of a menu, you can easily see how a React application restaurant template is useful.

The Restaurant App Template - React Native handles all the nuances very well, and like any UI, it looks good.

Restaurant App Template - React Native
“Manage your menu, accept orders, send push notifications.”

Features you'll find:

  • orders management
  • multiple languages
  • push notification
  • and more

This React app pulls data from Google's Firebase Realtime Database, so you can manage your menu and make changes without needing to republish the app.

The Restaurant App Template - React Native is great for learning React and provides some nice features that are worth learning about.

2. BeoStore - Complete React Native Template for E-Commerce

Nothing can be quite as crazy as organizing and presenting eCommerce. There is usually a full taxonomy to handle, and each item requires a fairly high baseline of repetitive data depending on what is being sold: data such as sizes, quality, inventory, color, versions, etc.

With the third version released, the BeoStore - Complete React Native Template for E-Commerce is a beautiful example of a React application for eCommerce.

BeoStore - Complete React Native Template for E-Commerce
“Your products will appear clear and can be zoom without any format error.”

Features include:

  • two product list modes
  • flexible product filter
  • user profiles
  • and more

On its lowest level, the UI presented here is top notch. When you consider the depth of data that is being sorted and presented—not to mention the fundamental feature set—this is a React application worth looking at closely.

The BeoStore - Complete React Native Template for E-Commerce is amazing.

3. Tudu - A React Native Todo-List

What kind of list of React applications for you to use, study, and apply would this be without a good to-do application?

That's why I've included the very beautiful Tudu - A React Native Todo-List React application.

Tudu - A React Native Todo-List
“In this source code you have multiple useful features not only for a to-do list app, but for all kind of projects.”

Features you can use:

  • auto grow text input
  • offline storage
  • swipe actions
  • and more

This is a good example of a React application that makes good use of space. Everything is spaced well for mobile and is designed to feel good to the user. With its simple codebase, you can build out your own to-do application or use these design fundamentals to build something completely different. 

Tudu - A React Native Todo-List is one of my favorites.

4. gikApp - React Native Full Application

Being able to leverage a CMS into your React application is a huge plus. WordPress fuels a large portion of the web, while Shopify is one of the leading eCommerce solutions. Learning how to pull this into a mobile app can be a real game changer.

Enter gikApp - React Native Full Application, a full-featured React application.

gikApp - React Native Full Application
“A truly multipurpose native app for your business.”

You'll find features like:

  • multi-tab screen and multi-level menu
  • Shopify sorting and view options
  • cart and checkout system
  • and more

I am a strong supporter of applications that focus on one thing and do it well. However, having a React application that's a bit of an all-in-one solution certainly has its place.

The gikApp - React Native Full Application is ready to be used for just about anything you're cooking up for a business.

5. BeoNews - React Native Mobile App for WordPress

There's hardly a better example of funneling your WordPress-based website into a React mobile app.

Easily get your WordPress site into mobile app form and onto the AppStore and Google Play with BeoNews - React Native Mobile App for WordPress.

BeoNews - React Native Mobile App for WordPress
“BeoNews is an app that does magic for your website by converting your WordPress website into mobile true native app with customized contents within a fillip.”

Features include:

  • easy Facebook integration
  • swipe and animated UI/UX
  • multiple layouts
  • and more

If you're digging deeper into React or you want to get your WordPress-powered website into a mobile app store, this is an excellent place to start.

The BeoNews - React Native Mobile App for WordPress ticks all the right boxes.

6. Sky Webview - Android & IOS React Native App

As much as I like to get my hands dirty and learn how to build from the ground up, sometimes I find that it helps to use beginner-based tools. Once I can complete a project in “easy mode,” I can then dig deeper and learn the ins and outs more easily.

Sky Webview - Android & IOS React Native App can help you get started with React applications without having to dig deep into code.

Sky Webview - Android  IOS React Native App
“No coding required.”

Features you'll find:

  • online theme edit panel
  • unlimited color options
  • over 670 icons
  • and more

I particularly like the “pull to refresh” feature.

Sky Webview - Android & IOS React Native App is a wonderful first-time React application.

7. OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams

If you haven't already needed to bring video to a mobile device, it's only a matter of time. Present live stream video into a React application using OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams.

OpenTV - React Native App AndroidiOS for TV Channels and Livestreams
“You want a simple but complete application, native, allowing to watch TV channels or livestreams or your mobile? OpenTV is what you need!”

Helpful features include:

  • supports both HTTP live streaming and local files
  • player controls and customizable behaviors
  • multiple formats and languages
  • and more

OpenTV - React Native App (Android/iOS) for TV Channels and Livestreams is your React application answer to mobile video.

8. BeoUI - Complete Mobile UI Template for React Native

This is another beautiful UI with plenty of styles that can be used in many different applications.

The BeoUI - Complete Mobile UI Template for React Native will land you on iOS and Android with only one language.

BeoUI - Complete Mobile UI Template for React Native
“A complete mobile UI template for React Native.”

Features include:

  • flat design mixed with wonderful animation and parallax scrolling
  • multiple menu styles
  • WordPress support
  • and more

This Reactive application template packs plenty of punch. With good looks and flexibility, you can build just about anything with BeoUI - Complete Mobile UI Template for React Native.

9. gikFashion - React Native Full eCommerce UI Theme

The thing about fashion-centric solutions is that they need to:

  1. Look good
  2. Be easy to use
  3. Handle a large number of complex assets

gikFashion - React Native Full eCommerce UI Theme does all three of these.

gikFashion - React Native Full eCommerce UI Theme
“...a complete solution for Ecommerce...”

Includes:

  • supports social media sign up and sign in
  • full featured eCommerce
  • online documentation
  • and more

While this React application focuses on fashion, keep in mind that it can be crafted to do much more or less—while delivering some great UI and functionality.

If gikFashion - React Native Full eCommerce UI Theme was clothing, you'd want to wear it.

10. Currency Converter React Native App

A great example of a mobile app that needs to pack in a lot of information and is highly utilitarian is the Currency Converter React Native App.

Currency Converter React Native App
“It has stunning and attractive design and can easily be modified.”

Features include:

  • converts currency based on the current currency market rate
  • AdMob ready
  • ready for iOS and Android

Complete with flags from all countries, create a fully functional currency converter and deliver yourself straight onto the AppStore and Google Play.

The Currency Converter React Native App is worth every penny.

Conclusion

Using, studying, and applying these React applications and strategies is one of the best ways to become a React pro. Digging into complete work, looking close at UI/UX choices, and doing this while building something of your own is your best teacher.

Of course, I would be remiss if I didn't mention some great resources that can help you along the way. There are the React applications on Envato Market, of course, but I highly recommend these React how-to tutorials, React courses, and React eBooks.

Pairing something you want to build with a good template and resource material is a recipe for React application success.

2017-07-28T12:00:14.000Z2017-07-28T12:00:14.000ZEric Dye

What Are Android Instant Apps?

$
0
0

Every time you release an Android app, you’ll have at least a rough idea of what you want this app to achieve. 

These goals could be very specific, such as generating a certain amount of ad revenue in the first quarter, or they could be more general, such as getting a high rating on Google Play.

Whatever else is on your wish-list, getting your app in front of as many users as possible is always going to feature somewhere on that list—and Android Instant Apps is a new feature that can help you do just that.

Instant Apps provide you with an entirely new way of reaching users who don’t currently have your app installed on their device, 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.

Essentially, Instant Apps allow you to separate each of your app’s features into a stand-alone module. Users can then load any of these instant app modules on-demand by tapping a URL that you’ve mapped to this specific module, and without having to install your app at any point.

In this three-part series, I’ll be showing you how to add Instant App support to your Android projects. By the end of this series, you’ll have created an application that consists of two separate Instant App feature modules, which you can launch and test on any compatible Android device. 

What We’re Going to Cover

In this first post, I'll focus on what Instant Apps are, how they work, and why you should care about them. To give you some first-hand experience of Instant Apps, we'll use Android Studio’s project creation wizard to generate an app that’s pre-configured with Instant App support, so you’ll be able to see all the different Instant App components, rather than simply reading about them.

While creating an app that’s pre-configured with Instant App support is the quickest and easiest way to use this feature, in reality you’re far more likely to add Instant App support to an existing project—so in part two I’ll show you how to do exactly that. I’ll supply an app that you can download from GitHub, and then take you through the step-by-step process of reconfiguring this project to support Instant Apps.

The final piece of the puzzle is creating a multi-featured Instant App, so in part three I’ll show you how to add a second feature module to your application, and how to use Android App Links to map this module to a different URL. 

What Are Instant Apps?

One of the best ways to describe Instant Apps is to look at an example of when you might use them.  

Imagine a friend has sent you a link to a cat video that they promise you’re going to love, but when you tap the link it becomes clear that you need to download an app before you can watch this particular video.  

Regardless of whether you end up downloading the app, or ignore the link and risk missing out on the best cat video the Internet has to offer, this is a bad user experience—and it’s a scenario that many Android users are familiar with. 

Most of us have had the experience of installing an app just to complete a one-off task. For example, you might download an app just to view an email attachment someone has sent you, to complete a purchase on a specific website, or to track a package that’s currently winging its way to your address.

Now let’s imagine our cat video scenario again, but this time the application’s developer has placed all the code and resources required to play video content inside its own instant app feature module, and mapped this module to the www.example.com/video URL. This time, when you tap www.example.com/video/cat-video, Google Play recognizes that this URL is associated with an instant app module and retrieves all the code and resources that you need to play this video. The end result? You can enjoy 20 seconds of a cat playing in a box without having to install anything, which is a much better user experience.  

Why Should I Start Using the Instant App Feature?

As you’ll see in the next post in this series, adding Instant App support to an existing project can be a daunting process, often requiring you to completely change the way your application is structured.

Since restructuring a project isn’t a decision you should ever take lightly, in this section I’m going to help you decide whether all that time and effort is really worth it, by covering all the major benefits of adding Instant App support to your projects:

  • It removes a barrier between your app and new users. Installing an application via Google Play isn’t a particularly difficult or time-consuming process, but it’s still the biggest barrier between your app and potential new users. No matter how much time you spend crafting a compelling Google Play page that’ll have the majority of users scrambling for that Install button, some people will always drop out at install time. 
  • It helps you reach new users. While you’ve always been able to promote your app on various locations around the web, such as your own website, blog or social media, connecting with new users has previously relied on them visiting your app’s Google Play page at some point (with the rare exception of users who prefer to sideload their apps). Instant apps remove this reliance on your app’s Google Play page, by making your application directly accessible from any location that supports URLs, giving you almost unlimited opportunities to connect with new users. 
  • It ensures that shared content is the best possible advert for your app. A user sharing your app’s content is one of the most effective ways of reaching a new audience, so you’ll want to make a good first impression! Previously, it’s been difficult to provide a consistent experience for users who don’t have your app installed on their device, but instant apps allow you to guarantee a seamless, native experience for everyone.
  • Helps users access your app, even in the face of Internet restrictions. While Internet coverage is improving all the time, you may still occasionally struggle to find a fast and reliable network, or perhaps you’re approaching your monthly data allowance and are worried about incurring additional charges. When you’re struggling with a slow or inconsistent Internet connection, downloading an entire app can be a time-consuming and frustrating process, and when you’re in danger of going over your data allowance, downloading a new app may be enough to incur additional charges. All instant app modules must be 4MB or less, so even if downloading an entire app is out of the question, then accessing an instant app module may still be a viable option. 
  • Increase the appeal of location and time-sensitive apps. While apps that are designed for a specific location or event aren’t a new concept, ask yourself: how likely am I to install an app that I know I’ll only be able to use for a limited period of time, or in a certain location? Instant apps can increase the appeal of time and location-sensitive apps, by allowing the user to access all of your app’s most important functionality at the tap of a URL. 

Restrictions and Limitations

Before we start our instant app journey, it’s worth noting that there are currently a few things that instant apps cannot do:

  • Access device identifiers like IMEI and MAC addresses.
  • Use background services.
  • Perform background notifications. 
  • Access the device’s external storage.
  • Access the list of apps that are installed on the user’s device—unless those applications have specifically made themselves discoverable to instant apps.

In addition, your application must: 

  • Be available to download for free from the Google Play store.
  • Use the new permissions model introduced in Android 6.0 (API level 23). Since the user doesn’t install an instant app, there’s no opportunity to request permissions up front. If your instant app feature module(s) require access to sensitive device capabilities or user information, then you’ll need to request these permissions at runtime. 
  • Support App Links. This is the mechanism that you’ll use to map each of your instant app modules to a specific URL. I’ll cover App Links in detail in the next post. 

Finally, if your app is part of the Designed for Families program, then you cannot offer it as an instant app. 

Setting Up Your Development Environment

Before you can create your first project with instant app support, you’ll need to have the following or higher installed:

  • Android Studio 3.0 Preview
  • Android SDK 6.0
  • Android SDK Build Tools 26.x
  • Android SDK Tools 25.x
  • Android SDK Platform Tools 25.x

You should also make sure you have the latest versions of the Android Support Library and Android Repository, so open Android Studio’s SDK Manager and install any available updates. 

Once you’ve installed all of the above, you’ll be able to download the Instant Apps Development SDK: 

  • Open the SDK Manager, and select the SDK Tools tab. 
  • Select Instant Apps Development SDK.
  • Click Apply.

Currently, you can only test instant apps on a Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher. However, if you don’t own any of these devices then you can create an Android Virtual Device (AVD) that emulates one of these devices, with a few conditions: the AVD must use an x86 image, and it must include the Google APIs.

Since I don’t own any of these devices, I’m going to create an AVD that emulates a Pixel: 

  • Launch the AVD Manager.
  • Click the Create virtual device... button.
  • Select Pixel, and then click Next.
  • Select the x86 Images tab. 
  • Select a system image that’s running Android 6.0 and includes the Google APIs, for example Marshmallow / 23 / x86 / Android 6.0 (Google APIs).
  • Click Next.
  • Give your AVD a name, and click Finish.
  • Launch your AVD.

Finally, you’ll need to sign in to a Google account on your AVD:

  • Switch to your AVD, and open the device’s launcher.
  • Select the Google app.
  • Enter a Gmail address and password. This can either be your real-life account, or an account you’ve created solely for the purposes of testing your Android projects. 

Creating Your First Instant App 

In Android Studio 3.0 Preview 1 and higher, creating a project that has built-in Instant App support is as easy as selecting a checkbox, so rather than just describing Instant App features, we’re going to create an Instant App project and then spend the rest of this article getting some first-hand experience with its various components. 

Just be aware that this project doesn’t feature any App Links, so you won’t be able to test its Instant App components on your AVD (this is something we’ll be exploring in detail in part two).

To create your project:

  • Launch the project creation wizard, either by selecting File > New > New project… from the Android Studio toolbar, or by clicking Start a new Android Studio project from Android Studio’s Welcome screen. 
  • Give your project a name, and click Next
  • Set the Minimum SDK to Android 6.0 (Marshmallow). 
  • Select the Include Android Instant app support checkbox, and click Next
  • To help keep things simple, accept the default module name (feature) and then click Next.
  • Select Basic Activity and then click Next.
  • On the next screen, accept all the default values, and then click Finish.

Immediately, we can see that this project is structured very differently from your typical Android project, and consists of the following modules:

  • App. The installable app module, also known as an APK module. 
  • Base. The base feature module.
  • Feature. Although this particular project only has one, an application can consist of multiple feature modules.
  • Instantapp. The instant app module. 
Projects with instant app support are structured differently to regular installable-only projects

With the exception of the feature module, any project that supports instant apps must have all of the above modules, so let’s explore each of these modules in detail.  

1. Application Module

The concept of an application module may be nothing new, but when your project supports instant apps, the application module’s Manifest looks much emptier than you’re probably used to: 

There’s a reason why this file is so empty: when you build your project, the contents of all the other Manifest files located throughout your base feature and feature modules are merged with this file—so it’s not going to stay this empty forever! 

If you open this module’s build.gradle file, then you’ll notice two new elements: 

Here, we’re declaring that our application module has a dependency on the feature module and base module. 

When you add Instant App support to a project, you separate related code and resources into feature modules that can function independently of the installable application. However, these modules are still parts of your installable app, rather than separate entities, which is why our application module is declaring the feature and base modules as dependencies.

2. Base Feature Module

Every instant app project must include a single base feature module, which contains the code and resources that are used across all your application’s modules. For example, if you open our project’s base/res/mipmap folder, then you’ll see all of the application’s launcher icons, which are clearly going to be used across multiple modules. 

The base feature module includes the ic_launcher drawables

Since it contains common code and resources, all of your project’s feature modules depend on this single base feature module. 

Continuing this theme, the base feature module contains the Manifest entries that are used across your entire project. For example, your project’s base/src/main/AndroidManifest.xml file contains the settings for your application’s icon, theme, and label: 

The other notable element is the base module’s build.gradle file, which contains a few new attributes:

You’ll also notice that this particular build.gradle file is missing an applicationID attribute, and (spoiler alert) you’ll find exactly the same thing when we come to inspect our feature module’s build.gradle file. Our project’s applicationID is declared in the application module’s build.gradle file only.

The application project(:app) line in our base module’s build.gradle file (see above) ensures that the project’s single applicationID attribute is propagated across all of our build.gradle files, which is why this attribute is missing from the rest of our project. 

3. Feature Module

When you eventually come to add Instant App support to an existing project, your biggest task will be extracting each of your application’s features into its own feature module, as each feature module contains the code and resources that are required to deliver this feature only. 

If you open our project’s feature module, then you’ll see that it contains the MainActivity class, plus activity_main and content_main resource files—essentially all the components that are included in the Basic Activity template.  

The projects feature module contains all the code and resources that are specific to this feature

A single feature module can consist of multiple Activities, but each module must have at least one Activity that’s designated as this module’s entry-point Activity. 

Each entry-point Activity is mapped to a specific URL, so that when the user taps this URL it loads the associated Activity and the user has access to this particular feature module. 

You designate a module’s entry-point Activity via that module’s manifest. Essentially, you need to open this file and add the following to the Activity that you want to use as your entry-point: 

  • An intent filter, with the CATEGORY_LAUNCHER and ACTION_MAIN intents.
  • A <data> element containing all the information about the URL that you want to map to this entry-point Activity. 
  • The android:autoVerify attribute. This tells the system to check that your app has permission to act as the default handler for this particular URL. This is an important security mechanism that helps to protect website owners from malicious apps that might try to hijack their URLs.

If you open our feature module’s manifest file, then you’ll see that all of this code has already been added to our MainActivity declaration:

The final file we’re going to look at in this module is the build.gradle file, which contains a few lines of noteworthy code: 

Since all feature modules depend on the base feature module, the first time the user requests any feature from your application, they’ll receive the base feature module plus the feature module they’re actually trying to access. 

Note that although this particular project consists of a base feature module and a feature module, if your app only has one feature that you want to make available as an Instant App, then it’s possible to create a project that consists of a base feature module only. We'll be looking at both "types" of Instant App project throughout this series. 

4. Instant App Module

The Instant App module has a simple purpose: it acts as a container that takes all of your feature modules and turns them into Instant App APKs.

If you open this project’s Instant App module, then you’ll see that it’s pretty much empty apart from a build.gradle file, which simply declares your base feature module and your feature module as dependencies:

Testing Your App

Since this project doesn’t contain any App Links, we won’t be able to test its instant app components, but we can still run this project as an installable app. This might not seem particularly exciting, but bearing in mind that the bulk of our project’s code and resources are located in the instant app feature module, it’s important to test how our project functions as an installable application. 

Launch the AVD we created earlier or connect a compatible physical Android smartphone or tablet to your development machine, and then select Run > Run… > app from the Android Studio toolbar. 

Despite the fact that all of our MainActivity code is located in the feature module, once our app loads you’ll see the MainActivity’s floating action button (FAB) and Hello World message. What we're seeing here is our application module taking code and resources that are located in separate Instant App feature and base feature modules, and combining them into an installable app. 

Conclusion 

In this tutorial we took a high-level look at how Instant Apps work, and explored the various reasons why you might want to add Instant App support to your Android projects. 

In an ideal world, your decision to start exploring Instant Apps would perfectly coincide with the start of a new Android project, but unfortunately, being a developer is rarely this convenient! It’s far more likely that you’ll have to reconfigure an existing project to support Instant Apps, which isn’t quite as straightforward as selecting a checkbox in Android Studio’s project creation wizard! 

In the next post, we'll take an in-depth look at how to add instant app support to an existing project. I’ll also show you how to implement App Links, so by the end of the next post you’ll have created a fully-functioning Instant App that you can launch and test on any compatible AVD or Android device. 

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

2017-07-31T19:27:31.534Z2017-07-31T19:27:31.534ZJessica Thornsby

What Are Android Instant Apps?

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

Every time you release an Android app, you’ll have at least a rough idea of what you want this app to achieve. 

These goals could be very specific, such as generating a certain amount of ad revenue in the first quarter, or they could be more general, such as getting a high rating on Google Play.

Whatever else is on your wish-list, getting your app in front of as many users as possible is always going to feature somewhere on that list—and Android Instant Apps is a new feature that can help you do just that.

Instant Apps provide you with an entirely new way of reaching users who don’t currently have your app installed on their device, 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.

Essentially, Instant Apps allow you to separate each of your app’s features into a stand-alone module. Users can then load any of these instant app modules on-demand by tapping a URL that you’ve mapped to this specific module, and without having to install your app at any point.

In this three-part series, I’ll be showing you how to add Instant App support to your Android projects. By the end of this series, you’ll have created an application that consists of two separate Instant App feature modules, which you can launch and test on any compatible Android device. 

What We’re Going to Cover

In this first post, I'll focus on what Instant Apps are, how they work, and why you should care about them. To give you some first-hand experience of Instant Apps, we'll use Android Studio’s project creation wizard to generate an app that’s pre-configured with Instant App support, so you’ll be able to see all the different Instant App components, rather than simply reading about them.

While creating an app that’s pre-configured with Instant App support is the quickest and easiest way to use this feature, in reality you’re far more likely to add Instant App support to an existing project—so in part two I’ll show you how to do exactly that. I’ll supply an app that you can download from GitHub, and then take you through the step-by-step process of reconfiguring this project to support Instant Apps.

The final piece of the puzzle is creating a multi-featured Instant App, so in part three I’ll show you how to add a second feature module to your application, and how to use Android App Links to map this module to a different URL. 

What Are Instant Apps?

One of the best ways to describe Instant Apps is to look at an example of when you might use them.  

Imagine a friend has sent you a link to a cat video that they promise you’re going to love, but when you tap the link it becomes clear that you need to download an app before you can watch this particular video.  

Regardless of whether you end up downloading the app, or ignore the link and risk missing out on the best cat video the Internet has to offer, this is a bad user experience—and it’s a scenario that many Android users are familiar with. 

Most of us have had the experience of installing an app just to complete a one-off task. For example, you might download an app just to view an email attachment someone has sent you, to complete a purchase on a specific website, or to track a package that’s currently winging its way to your address.

Now let’s imagine our cat video scenario again, but this time the application’s developer has placed all the code and resources required to play video content inside its own instant app feature module, and mapped this module to the www.example.com/video URL. This time, when you tap www.example.com/video/cat-video, Google Play recognizes that this URL is associated with an instant app module and retrieves all the code and resources that you need to play this video. The end result? You can enjoy 20 seconds of a cat playing in a box without having to install anything, which is a much better user experience.  

Why Should I Start Using the Instant App Feature?

As you’ll see in the next post in this series, adding Instant App support to an existing project can be a daunting process, often requiring you to completely change the way your application is structured.

Since restructuring a project isn’t a decision you should ever take lightly, in this section I’m going to help you decide whether all that time and effort is really worth it, by covering all the major benefits of adding Instant App support to your projects:

  • It removes a barrier between your app and new users. Installing an application via Google Play isn’t a particularly difficult or time-consuming process, but it’s still the biggest barrier between your app and potential new users. No matter how much time you spend crafting a compelling Google Play page that’ll have the majority of users scrambling for that Install button, some people will always drop out at install time. 
  • It helps you reach new users. While you’ve always been able to promote your app on various locations around the web, such as your own website, blog or social media, connecting with new users has previously relied on them visiting your app’s Google Play page at some point (with the rare exception of users who prefer to sideload their apps). Instant apps remove this reliance on your app’s Google Play page, by making your application directly accessible from any location that supports URLs, giving you almost unlimited opportunities to connect with new users. 
  • It ensures that shared content is the best possible advert for your app. A user sharing your app’s content is one of the most effective ways of reaching a new audience, so you’ll want to make a good first impression! Previously, it’s been difficult to provide a consistent experience for users who don’t have your app installed on their device, but instant apps allow you to guarantee a seamless, native experience for everyone.
  • Helps users access your app, even in the face of Internet restrictions. While Internet coverage is improving all the time, you may still occasionally struggle to find a fast and reliable network, or perhaps you’re approaching your monthly data allowance and are worried about incurring additional charges. When you’re struggling with a slow or inconsistent Internet connection, downloading an entire app can be a time-consuming and frustrating process, and when you’re in danger of going over your data allowance, downloading a new app may be enough to incur additional charges. All instant app modules must be 4MB or less, so even if downloading an entire app is out of the question, then accessing an instant app module may still be a viable option. 
  • Increase the appeal of location and time-sensitive apps. While apps that are designed for a specific location or event aren’t a new concept, ask yourself: how likely am I to install an app that I know I’ll only be able to use for a limited period of time, or in a certain location? Instant apps can increase the appeal of time and location-sensitive apps, by allowing the user to access all of your app’s most important functionality at the tap of a URL. 

Restrictions and Limitations

Before we start our instant app journey, it’s worth noting that there are currently a few things that instant apps cannot do:

  • Access device identifiers like IMEI and MAC addresses.
  • Use background services.
  • Perform background notifications. 
  • Access the device’s external storage.
  • Access the list of apps that are installed on the user’s device—unless those applications have specifically made themselves discoverable to instant apps.

In addition, your application must: 

  • Be available to download for free from the Google Play store.
  • Use the new permissions model introduced in Android 6.0 (API level 23). Since the user doesn’t install an instant app, there’s no opportunity to request permissions up front. If your instant app feature module(s) require access to sensitive device capabilities or user information, then you’ll need to request these permissions at runtime. 
  • Support App Links. This is the mechanism that you’ll use to map each of your instant app modules to a specific URL. I’ll cover App Links in detail in the next post. 

Finally, if your app is part of the Designed for Families program, then you cannot offer it as an instant app. 

Setting Up Your Development Environment

Before you can create your first project with instant app support, you’ll need to have the following or higher installed:

  • Android Studio 3.0 Preview
  • Android SDK 6.0
  • Android SDK Build Tools 26.x
  • Android SDK Tools 25.x
  • Android SDK Platform Tools 25.x

You should also make sure you have the latest versions of the Android Support Library and Android Repository, so open Android Studio’s SDK Manager and install any available updates. 

Once you’ve installed all of the above, you’ll be able to download the Instant Apps Development SDK: 

  • Open the SDK Manager, and select the SDK Tools tab. 
  • Select Instant Apps Development SDK.
  • Click Apply.

Currently, you can only test instant apps on a Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher. However, if you don’t own any of these devices then you can create an Android Virtual Device (AVD) that emulates one of these devices, with a few conditions: the AVD must use an x86 image, and it must include the Google APIs.

Since I don’t own any of these devices, I’m going to create an AVD that emulates a Pixel: 

  • Launch the AVD Manager.
  • Click the Create virtual device... button.
  • Select Pixel, and then click Next.
  • Select the x86 Images tab. 
  • Select a system image that’s running Android 6.0 and includes the Google APIs, for example Marshmallow / 23 / x86 / Android 6.0 (Google APIs).
  • Click Next.
  • Give your AVD a name, and click Finish.
  • Launch your AVD.

Finally, you’ll need to sign in to a Google account on your AVD:

  • Switch to your AVD, and open the device’s launcher.
  • Select the Google app.
  • Enter a Gmail address and password. This can either be your real-life account, or an account you’ve created solely for the purposes of testing your Android projects. 

Creating Your First Instant App 

In Android Studio 3.0 Preview 1 and higher, creating a project that has built-in Instant App support is as easy as selecting a checkbox, so rather than just describing Instant App features, we’re going to create an Instant App project and then spend the rest of this article getting some first-hand experience with its various components. 

Just be aware that this project doesn’t feature any App Links, so you won’t be able to test its Instant App components on your AVD (this is something we’ll be exploring in detail in part two).

To create your project:

  • Launch the project creation wizard, either by selecting File > New > New project… from the Android Studio toolbar, or by clicking Start a new Android Studio project from Android Studio’s Welcome screen. 
  • Give your project a name, and click Next
  • Set the Minimum SDK to Android 6.0 (Marshmallow). 
  • Select the Include Android Instant app support checkbox, and click Next
  • To help keep things simple, accept the default module name (feature) and then click Next.
  • Select Basic Activity and then click Next.
  • On the next screen, accept all the default values, and then click Finish.

Immediately, we can see that this project is structured very differently from your typical Android project, and consists of the following modules:

  • App. The installable app module, also known as an APK module. 
  • Base. The base feature module.
  • Feature. Although this particular project only has one, an application can consist of multiple feature modules.
  • Instantapp. The instant app module. 
Projects with instant app support are structured differently to regular installable-only projects

With the exception of the feature module, any project that supports instant apps must have all of the above modules, so let’s explore each of these modules in detail.  

1. Application Module

The concept of an application module may be nothing new, but when your project supports instant apps, the application module’s Manifest looks much emptier than you’re probably used to: 

There’s a reason why this file is so empty: when you build your project, the contents of all the other Manifest files located throughout your base feature and feature modules are merged with this file—so it’s not going to stay this empty forever! 

If you open this module’s build.gradle file, then you’ll notice two new elements: 

Here, we’re declaring that our application module has a dependency on the feature module and base module. 

When you add Instant App support to a project, you separate related code and resources into feature modules that can function independently of the installable application. However, these modules are still parts of your installable app, rather than separate entities, which is why our application module is declaring the feature and base modules as dependencies.

2. Base Feature Module

Every instant app project must include a single base feature module, which contains the code and resources that are used across all your application’s modules. For example, if you open our project’s base/res/mipmap folder, then you’ll see all of the application’s launcher icons, which are clearly going to be used across multiple modules. 

The base feature module includes the ic_launcher drawables

Since it contains common code and resources, all of your project’s feature modules depend on this single base feature module. 

Continuing this theme, the base feature module contains the Manifest entries that are used across your entire project. For example, your project’s base/src/main/AndroidManifest.xml file contains the settings for your application’s icon, theme, and label: 

The other notable element is the base module’s build.gradle file, which contains a few new attributes:

You’ll also notice that this particular build.gradle file is missing an applicationID attribute, and (spoiler alert) you’ll find exactly the same thing when we come to inspect our feature module’s build.gradle file. Our project’s applicationID is declared in the application module’s build.gradle file only.

The application project(:app) line in our base module’s build.gradle file (see above) ensures that the project’s single applicationID attribute is propagated across all of our build.gradle files, which is why this attribute is missing from the rest of our project. 

3. Feature Module

When you eventually come to add Instant App support to an existing project, your biggest task will be extracting each of your application’s features into its own feature module, as each feature module contains the code and resources that are required to deliver this feature only. 

If you open our project’s feature module, then you’ll see that it contains the MainActivity class, plus activity_main and content_main resource files—essentially all the components that are included in the Basic Activity template.  

The projects feature module contains all the code and resources that are specific to this feature

A single feature module can consist of multiple Activities, but each module must have at least one Activity that’s designated as this module’s entry-point Activity. 

Each entry-point Activity is mapped to a specific URL, so that when the user taps this URL it loads the associated Activity and the user has access to this particular feature module. 

You designate a module’s entry-point Activity via that module’s manifest. Essentially, you need to open this file and add the following to the Activity that you want to use as your entry-point: 

  • An intent filter, with the CATEGORY_LAUNCHER and ACTION_MAIN intents.
  • A <data> element containing all the information about the URL that you want to map to this entry-point Activity. 
  • The android:autoVerify attribute. This tells the system to check that your app has permission to act as the default handler for this particular URL. This is an important security mechanism that helps to protect website owners from malicious apps that might try to hijack their URLs.

If you open our feature module’s manifest file, then you’ll see that all of this code has already been added to our MainActivity declaration:

The final file we’re going to look at in this module is the build.gradle file, which contains a few lines of noteworthy code: 

Since all feature modules depend on the base feature module, the first time the user requests any feature from your application, they’ll receive the base feature module plus the feature module they’re actually trying to access. 

Note that although this particular project consists of a base feature module and a feature module, if your app only has one feature that you want to make available as an Instant App, then it’s possible to create a project that consists of a base feature module only. We'll be looking at both "types" of Instant App project throughout this series. 

4. Instant App Module

The Instant App module has a simple purpose: it acts as a container that takes all of your feature modules and turns them into Instant App APKs.

If you open this project’s Instant App module, then you’ll see that it’s pretty much empty apart from a build.gradle file, which simply declares your base feature module and your feature module as dependencies:

Testing Your App

Since this project doesn’t contain any App Links, we won’t be able to test its instant app components, but we can still run this project as an installable app. This might not seem particularly exciting, but bearing in mind that the bulk of our project’s code and resources are located in the instant app feature module, it’s important to test how our project functions as an installable application. 

Launch the AVD we created earlier or connect a compatible physical Android smartphone or tablet to your development machine, and then select Run > Run… > app from the Android Studio toolbar. 

Despite the fact that all of our MainActivity code is located in the feature module, once our app loads you’ll see the MainActivity’s floating action button (FAB) and Hello World message. What we're seeing here is our application module taking code and resources that are located in separate Instant App feature and base feature modules, and combining them into an installable app. 

Conclusion 

In this tutorial we took a high-level look at how Instant Apps work, and explored the various reasons why you might want to add Instant App support to your Android projects. 

In an ideal world, your decision to start exploring Instant Apps would perfectly coincide with the start of a new Android project, but unfortunately, being a developer is rarely this convenient! It’s far more likely that you’ll have to reconfigure an existing project to support Instant Apps, which isn’t quite as straightforward as selecting a checkbox in Android Studio’s project creation wizard! 

In the next post, we'll take an in-depth look at how to add instant app support to an existing project. I’ll also show you how to implement App Links, so by the end of the next post you’ll have created a fully-functioning Instant App that you can launch and test on any compatible AVD or Android device. 

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

2017-07-31T19:27:31.534Z2017-07-31T19:27:31.534ZJessica Thornsby

How to Monetize Your Android Apps With AdMob

$
0
0

In this tutorial, you'll learn about how to integrate AdMob so you can make money from that awesome Android app you wrote—come on, who doesn't want that? AdMob is among the biggest mobile advertising platforms in the market, and it is owned by Google.

There are a few different ways to monetize your apps in Android: paid downloads, paid subscriptions, in-app purchases, and by displaying ads. You can combine them, but is recommended you pick a single model. In this tutorial, you'll learn about how to monetize your app by displaying ads. 

The kinds of ads you'll create in this tutorial are banner, interstitial, and native express ads. I'll explain each of them and show you how to implement them in your application. But before that, let's first of all see how to integrate the Mobile Ads SDK and initialize it. 

Create an Android Studio Project

In Android Studio, create a new project named MainActivity.

Android Studio add an activity dialog

Include the Mobile Ads SDK

To begin integration of AdMob with your app, you'll need to first include the Mobile Ads SDK to your app module build.gradle file:

If you are going to integrate Firebase into your app, then you should use the SDK which is part of Firebase:

Check out the some of our Firebase tutorials here on Envato Tuts+ if you need help getting started with Firebase:

Make sure you sync the project after adding it the SDKs so as to pull the libraries from the internet into your application. 

Initialize MobileAds

You need to initialize the Mobile Ads SDK before you can load ads on your Android app, so do this as early as possible. We create a class which extends the Application class, and then we initialize the MobileAds SDK in the onCreate() method of that class, because this method is called only once when the app is launched. 

The second argument supplied to the static method initialize() of the MobileAds class should be your AdMob application ID you got when you signed up for AdMob. In this case, we are using the public application ID provided by Google for demo purposes. 

Modify the Manifest File

We need to add the application class we created to the application tag name attribute in our AndroidManifest.xml file. 

While in this file, also make sure to include the INTERNET permission so that Google mobile ads can run. 

In the code snippet below, we added the AdActivity to our AndroidManifest.xml file within the application tag. 

This activity is provided by the SDK. It is useful in banner ads to fire up the ad to be viewed when the user clicks on the ad, while for an interstitial ad, it is used for displaying the ad when the user clicks on it.

1. Banner Ads

Banner ads cover a part of the currently visible screen. In other words, any content in your app and the ad are displayed together on the screen. This improves the user experience because your users can keep on using your app while the ad is showing, unlike an interstitial ad (just hang on, we'll get to that shortly). Note that a banner ad can be text or an image. 

Let's look at how to implement a banner ad. 

Include a Banner Ad in Your Layout

AdView is a custom ViewGroup that will contain the banner ad, so we need to edit our activity_banner_ad.xml layout file to include this view. 

We are defining the AdView size by using the attribute ads:adSize and setting it to BANNER. Other alternatives available are LARGE_BANNERFULL_BANNERSMART_BANNER, etc. 

The ads:adUnitIdAdView attribute is set to a sample ad unit provided by Google. You'll have to update this with an ad unit associated with your account if you want to actually make money from your ads! 

The ad unit ID identifies an ad placement, and you can find it in the AdMob admin console. This ID will tell AdMob the kind of ad to be displayed on your app and also the display format (image, text, or video).

Load the Ad

For us to finally show the ad, we need to make a request and then show it in the AdView we created above in the BannerAdActivity class. 

We made an ad request by creating an instance of AdRequest using the builder. Then we used the method addTestDevice(), passing in a device id as an argument to receive test ads to the device, which in our case is the emulator. We then finally called the AdView method loadAd() that takes in this AdRequest instance and then loads the ad on a background thread (so as not to block the UI/main thread). 

Test the Ad

At this point, we can run our project and see the result. 

App showing banner ad

From the screenshot above, we can see that our test banner ad is showing below the view. Now interact with the ad by clicking on it. 

Listening for Ad Events With AdListener

Let's now explore the events or callbacks we can observe in an ad. These are the events available: 

  • onAdLoaded(): this method is fired when the ad is retrieved. 
  • onAdOpened(): this method is invoked when the ad is opened. 
  • onAdClosed(): this method is fired when the ad is closed.
  • onAdLeftApplication(): this method is invoked when the user has left the application.
  • onAdFailedToLoad(int errorCode): this is fired when a request for the ad fails. The code can be one of ERROR_CODE_NETWORK_ERRORERROR_CODE_INVALID_REQUESTERROR_CODE_NO_FILL, or ERROR_CODE_INTERNAL_ERROR.

After adding the listener, run the project again and interact with the ad. Observe the events being invoked by watching the toasts we created. 

2. Interstitial Ads

We have seen how easy it is to display a banner ad. Now let's look at how to create interstitial ads. 

Interstitial ads are ads that cover the whole screen of your application, giving no room for other views of your app to show (as we'll see shortly). Since this takes over the entire screen and also takes some time to load if the network is slow, you need to be careful not to irritate your users. So ideally these interstitial ads should be shown during natural breaks in your app, e.g. between levels in a game, and not when users are in the middle of some other task.

In the code above, we declared and initialized an instance of the class InterstitialAd in the InterstitialAdActivity class. We set the add unit id by passing the Google-provided one as the only argument into the method setAdUnitId()

Just like what we did for the banner ad, we want to listen for events on the ad, so we set a listener to fire the overloaded methods onAdLoaded() and onAdFailedToLoad(int i). We make an ad request by creating an instance of the AdRequest class using its builder and then call the method loadAd(), passing this request as an argument to the method. We use the method isLoaded() to determine when the ad has been loaded and then call the method show() to finally display it. 

You can also add an AdListener just like we did for the banner ad. 

Test the Ad

At this point now, we can run the app and see the result. 

App showing interstitial  ad

In the screenshot above, you can see that our test interstitial ad is now showing. 

3. Native Ads Express

Native Ads Express gives you (the publisher) the ability to customize the look and feel of ads so that they can fit naturally with your app. This customization is done by defining CSS templates in which you define your own fonts, colours, sizes, etc. from your AdMob account. You can't change the images, descriptions, and titles, though—these are set by the advertisers. 

The customized ads can be displayed in your app in a NativeExpressAdView

Include NativeExpressAdView in Your Layout

Below, we include the NativeExpressAdView, which is a ViewGroup, in our layout file. We also define the android:layout_height and android:layout_width to be wrap_content. The ads:adSize will be "320x300", and we'll use the Google-provided NativeExpress ad unit id (for demo purposes only). 

Load the Ad

Next, we build our AdRequest and then begin loading the ad to be displayed. We'll also add code to respond to the Activity lifecycle callbacks. You can also add an AdListener if you want, just like we did for the banner ad. 

Test the Ad

That's it! Now you can run the app and see your Native Express ad in action.

App showing NativeExpressAdView

Create Your Own AdMob Account

Now that we have learned about the different types of ads, you can go ahead and integrate them into your application. To begin showing real ads and making money, you'll need an AdMob account—with real ad unit ids that are linked to real ads from advertisers. Just visit the AdMob website to sign up! 

AdMob website home screen

Conclusion

In this tutorial, you learned about AdMob and how to integrate different AdMob ad formats such as banner, interstitial, and native express ads on Android. 

To learn more about AdMob on Android, do refer to the official documentation. And in the meantime, check out some of our other courses and tutorials on Android app development!

2017-08-02T14:11:56.400Z2017-08-02T14:11:56.400ZChike Mgbemena

How to Monetize Your Android Apps With AdMob

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

In this tutorial, you'll learn about how to integrate AdMob so you can make money from that awesome Android app you wrote—come on, who doesn't want that? AdMob is among the biggest mobile advertising platforms in the market, and it is owned by Google.

There are a few different ways to monetize your apps in Android: paid downloads, paid subscriptions, in-app purchases, and by displaying ads. You can combine them, but is recommended you pick a single model. In this tutorial, you'll learn about how to monetize your app by displaying ads. 

The kinds of ads you'll create in this tutorial are banner, interstitial, and native express ads. I'll explain each of them and show you how to implement them in your application. But before that, let's first of all see how to integrate the Mobile Ads SDK and initialize it. 

Create an Android Studio Project

In Android Studio, create a new project named MainActivity.

Android Studio add an activity dialog

Include the Mobile Ads SDK

To begin integration of AdMob with your app, you'll need to first include the Mobile Ads SDK to your app module build.gradle file:

If you are going to integrate Firebase into your app, then you should use the SDK which is part of Firebase:

Check out the some of our Firebase tutorials here on Envato Tuts+ if you need help getting started with Firebase:

Make sure you sync the project after adding it the SDKs so as to pull the libraries from the internet into your application. 

Initialize MobileAds

You need to initialize the Mobile Ads SDK before you can load ads on your Android app, so do this as early as possible. We create a class which extends the Application class, and then we initialize the MobileAds SDK in the onCreate() method of that class, because this method is called only once when the app is launched. 

The second argument supplied to the static method initialize() of the MobileAds class should be your AdMob application ID you got when you signed up for AdMob. In this case, we are using the public application ID provided by Google for demo purposes. 

Modify the Manifest File

We need to add the application class we created to the application tag name attribute in our AndroidManifest.xml file. 

While in this file, also make sure to include the INTERNET permission so that Google mobile ads can run. 

In the code snippet below, we added the AdActivity to our AndroidManifest.xml file within the application tag. 

This activity is provided by the SDK. It is useful in banner ads to fire up the ad to be viewed when the user clicks on the ad, while for an interstitial ad, it is used for displaying the ad when the user clicks on it.

1. Banner Ads

Banner ads cover a part of the currently visible screen. In other words, any content in your app and the ad are displayed together on the screen. This improves the user experience because your users can keep on using your app while the ad is showing, unlike an interstitial ad (just hang on, we'll get to that shortly). Note that a banner ad can be text or an image. 

Let's look at how to implement a banner ad. 

Include a Banner Ad in Your Layout

AdView is a custom ViewGroup that will contain the banner ad, so we need to edit our activity_banner_ad.xml layout file to include this view. 

We are defining the AdView size by using the attribute ads:adSize and setting it to BANNER. Other alternatives available are LARGE_BANNERFULL_BANNERSMART_BANNER, etc. 

The ads:adUnitIdAdView attribute is set to a sample ad unit provided by Google. You'll have to update this with an ad unit associated with your account if you want to actually make money from your ads! 

The ad unit ID identifies an ad placement, and you can find it in the AdMob admin console. This ID will tell AdMob the kind of ad to be displayed on your app and also the display format (image, text, or video).

Load the Ad

For us to finally show the ad, we need to make a request and then show it in the AdView we created above in the BannerAdActivity class. 

We made an ad request by creating an instance of AdRequest using the builder. Then we used the method addTestDevice(), passing in a device id as an argument to receive test ads to the device, which in our case is the emulator. We then finally called the AdView method loadAd() that takes in this AdRequest instance and then loads the ad on a background thread (so as not to block the UI/main thread). 

Test the Ad

At this point, we can run our project and see the result. 

App showing banner ad

From the screenshot above, we can see that our test banner ad is showing below the view. Now interact with the ad by clicking on it. 

Listening for Ad Events With AdListener

Let's now explore the events or callbacks we can observe in an ad. These are the events available: 

  • onAdLoaded(): this method is fired when the ad is retrieved. 
  • onAdOpened(): this method is invoked when the ad is opened. 
  • onAdClosed(): this method is fired when the ad is closed.
  • onAdLeftApplication(): this method is invoked when the user has left the application.
  • onAdFailedToLoad(int errorCode): this is fired when a request for the ad fails. The code can be one of ERROR_CODE_NETWORK_ERRORERROR_CODE_INVALID_REQUESTERROR_CODE_NO_FILL, or ERROR_CODE_INTERNAL_ERROR.

After adding the listener, run the project again and interact with the ad. Observe the events being invoked by watching the toasts we created. 

2. Interstitial Ads

We have seen how easy it is to display a banner ad. Now let's look at how to create interstitial ads. 

Interstitial ads are ads that cover the whole screen of your application, giving no room for other views of your app to show (as we'll see shortly). Since this takes over the entire screen and also takes some time to load if the network is slow, you need to be careful not to irritate your users. So ideally these interstitial ads should be shown during natural breaks in your app, e.g. between levels in a game, and not when users are in the middle of some other task.

In the code above, we declared and initialized an instance of the class InterstitialAd in the InterstitialAdActivity class. We set the add unit id by passing the Google-provided one as the only argument into the method setAdUnitId()

Just like what we did for the banner ad, we want to listen for events on the ad, so we set a listener to fire the overloaded methods onAdLoaded() and onAdFailedToLoad(int i). We make an ad request by creating an instance of the AdRequest class using its builder and then call the method loadAd(), passing this request as an argument to the method. We use the method isLoaded() to determine when the ad has been loaded and then call the method show() to finally display it. 

You can also add an AdListener just like we did for the banner ad. 

Test the Ad

At this point now, we can run the app and see the result. 

App showing interstitial  ad

In the screenshot above, you can see that our test interstitial ad is now showing. 

3. Native Ads Express

Native Ads Express gives you (the publisher) the ability to customize the look and feel of ads so that they can fit naturally with your app. This customization is done by defining CSS templates in which you define your own fonts, colours, sizes, etc. from your AdMob account. You can't change the images, descriptions, and titles, though—these are set by the advertisers. 

The customized ads can be displayed in your app in a NativeExpressAdView

Include NativeExpressAdView in Your Layout

Below, we include the NativeExpressAdView, which is a ViewGroup, in our layout file. We also define the android:layout_height and android:layout_width to be wrap_content. The ads:adSize will be "320x300", and we'll use the Google-provided NativeExpress ad unit id (for demo purposes only). 

Load the Ad

Next, we build our AdRequest and then begin loading the ad to be displayed. We'll also add code to respond to the Activity lifecycle callbacks. You can also add an AdListener if you want, just like we did for the banner ad. 

Test the Ad

That's it! Now you can run the app and see your Native Express ad in action.

App showing NativeExpressAdView

Create Your Own AdMob Account

Now that we have learned about the different types of ads, you can go ahead and integrate them into your application. To begin showing real ads and making money, you'll need an AdMob account—with real ad unit ids that are linked to real ads from advertisers. Just visit the AdMob website to sign up! 

AdMob website home screen

Conclusion

In this tutorial, you learned about AdMob and how to integrate different AdMob ad formats such as banner, interstitial, and native express ads on Android. 

To learn more about AdMob on Android, do refer to the official documentation. And in the meantime, check out some of our other courses and tutorials on Android app development!

2017-08-02T14:11:56.400Z2017-08-02T14:11:56.400ZChike Mgbemena

Quick Tip: Write Cleaner Code With Kotlin SAM Conversions

$
0
0

If you are an experienced Android application developer, you're probably used to the verbosity of Java 7. As a result, you might be finding Kotlin's concise syntax, which is geared towards functional programmers, slightly unsettling.

One common problem beginners encounter while learning Kotlin is understanding how it expects you to work with Java interfaces that contain a single method. Such interfaces are ubiquitous in the Android world and are often referred to as SAM interfaces, where SAM is short for Single Abstract Method.

In this short tutorial, you'll learn everything you need to know to aptly use Java's SAM interfaces in Kotlin code.

1. What Is a SAM Conversion?

When you want to make use of a Java interface containing a single method in your Kotlin code, you don't have to manually create an anonymous class that implements it. Instead, you can use a lambda expression. Thanks to a process called SAM conversion, Kotlin can transparently convert any lambda expression whose signature matches that of the interface's single method into an instance of an anonymous class that implements the interface.

For example, consider the following one-method Java interface:

A naive and Java 7-like approach to using the above interface would involve working with an object expression and would look like this:

That's a lot of unnecessary code, which is also not very readable. By leveraging Kotlin's SAM conversion facility, however, you can write the following equivalent code instead:

As you can see, we've now replaced the anonymous class with a short lambda expression, which is prefixed with the name of the interface. Note that the number of arguments the lambda expression takes is equal to the number of parameters in the signature of the interface's method.

2. SAM Conversions in Function Calls

While working with Java classes having methods that take SAM types as their arguments, you can further simplify the above syntax. For example, consider the following Java class, which contains a method that expects an object implementing the Adder interface:

In your Kotlin code, you can now directly pass a lambda expression to the setAdder() method, without prefixing it with the name of the Adder interface.

It is worth noting that while calling a method that takes a SAM type as its only argument, you are free to skip the parenthesis to make your code even more concise.

3. SAM Conversions Without Lambdas

If you think lambda expressions are confusing, I've got good news for you: SAM conversions work just fine with ordinary functions too. For example, consider the following function whose signature matches that of the Adder interface's method:

Kotlin allows you to directly pass the myCustomAdd() function as an argument to the setAdder() method of the Calculator class. Don't forget to reference the method using the :: operator. Here's how:

4. The it Variable

Many times, SAM interfaces contain one-parameter methods. A one-parameter method, as its name suggests, has only one parameter in its signature. While working with such interfaces, Kotlin allows you to omit the parameter in your lambda expression's signature and use an implicit variable called it in the expression's body. To make things clearer, consider the following Java interface:

While using the Doubler interface in your Kotlin code, you don't have to explicitly mention the number parameter in your lambda expression's signature. Instead, you can simply refer to it as it.

5. SAM Interfaces in Kotlin

As a Java developer, you might be inclined to create SAM interfaces in Kotlin. Doing so, however, is usually not a good idea. If you create a SAM interface in Kotlin, or create a Kotlin method that expects an object implementing a SAM interface as an argument, the SAM conversion facility will not be available to you—SAM conversion is a Java-interoperability feature and is limited to Java classes and interfaces only.

Because Kotlin supports higher-order functions—functions that can take other functions as arguments—you'll never need to create SAM interfaces in it. For example, if the Calculator class is rewritten in Kotlin, its setAdder() method can be written such that it directly takes a function as its argument, instead of an object that implements the Adder interface.

While using the above class, you can set adder to a function or a lambda expression using the = operator. The following code shows you how:

Conclusion

Android's APIs are largely written in Java, and many use SAM interfaces extensively. The same can be said of most third-party libraries too. By using the techniques you learned in this tutorial, you can work with them in your Kotlin code in a concise and easy-to-read way.

To learn more about Kotlin's Java-interoperability features, do refer to the official documentation. And do check out some of our other tutorials on Android app development!

2017-08-07T16:50:44.347Z2017-08-07T16:50:44.347ZAshraff Hathibelagal

Quick Tip: Write Cleaner Code With Kotlin SAM Conversions

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

If you are an experienced Android application developer, you're probably used to the verbosity of Java 7. As a result, you might be finding Kotlin's concise syntax, which is geared towards functional programmers, slightly unsettling.

One common problem beginners encounter while learning Kotlin is understanding how it expects you to work with Java interfaces that contain a single method. Such interfaces are ubiquitous in the Android world and are often referred to as SAM interfaces, where SAM is short for Single Abstract Method.

In this short tutorial, you'll learn everything you need to know to aptly use Java's SAM interfaces in Kotlin code.

1. What Is a SAM Conversion?

When you want to make use of a Java interface containing a single method in your Kotlin code, you don't have to manually create an anonymous class that implements it. Instead, you can use a lambda expression. Thanks to a process called SAM conversion, Kotlin can transparently convert any lambda expression whose signature matches that of the interface's single method into an instance of an anonymous class that implements the interface.

For example, consider the following one-method Java interface:

A naive and Java 7-like approach to using the above interface would involve working with an object expression and would look like this:

That's a lot of unnecessary code, which is also not very readable. By leveraging Kotlin's SAM conversion facility, however, you can write the following equivalent code instead:

As you can see, we've now replaced the anonymous class with a short lambda expression, which is prefixed with the name of the interface. Note that the number of arguments the lambda expression takes is equal to the number of parameters in the signature of the interface's method.

2. SAM Conversions in Function Calls

While working with Java classes having methods that take SAM types as their arguments, you can further simplify the above syntax. For example, consider the following Java class, which contains a method that expects an object implementing the Adder interface:

In your Kotlin code, you can now directly pass a lambda expression to the setAdder() method, without prefixing it with the name of the Adder interface.

It is worth noting that while calling a method that takes a SAM type as its only argument, you are free to skip the parenthesis to make your code even more concise.

3. SAM Conversions Without Lambdas

If you think lambda expressions are confusing, I've got good news for you: SAM conversions work just fine with ordinary functions too. For example, consider the following function whose signature matches that of the Adder interface's method:

Kotlin allows you to directly pass the myCustomAdd() function as an argument to the setAdder() method of the Calculator class. Don't forget to reference the method using the :: operator. Here's how:

4. The it Variable

Many times, SAM interfaces contain one-parameter methods. A one-parameter method, as its name suggests, has only one parameter in its signature. While working with such interfaces, Kotlin allows you to omit the parameter in your lambda expression's signature and use an implicit variable called it in the expression's body. To make things clearer, consider the following Java interface:

While using the Doubler interface in your Kotlin code, you don't have to explicitly mention the number parameter in your lambda expression's signature. Instead, you can simply refer to it as it.

5. SAM Interfaces in Kotlin

As a Java developer, you might be inclined to create SAM interfaces in Kotlin. Doing so, however, is usually not a good idea. If you create a SAM interface in Kotlin, or create a Kotlin method that expects an object implementing a SAM interface as an argument, the SAM conversion facility will not be available to you—SAM conversion is a Java-interoperability feature and is limited to Java classes and interfaces only.

Because Kotlin supports higher-order functions—functions that can take other functions as arguments—you'll never need to create SAM interfaces in it. For example, if the Calculator class is rewritten in Kotlin, its setAdder() method can be written such that it directly takes a function as its argument, instead of an object that implements the Adder interface.

While using the above class, you can set adder to a function or a lambda expression using the = operator. The following code shows you how:

Conclusion

Android's APIs are largely written in Java, and many use SAM interfaces extensively. The same can be said of most third-party libraries too. By using the techniques you learned in this tutorial, you can work with them in your Kotlin code in a concise and easy-to-read way.

To learn more about Kotlin's Java-interoperability features, do refer to the official documentation. And do check out some of our other tutorials on Android app development!

2017-08-07T16:50:44.347Z2017-08-07T16:50:44.347ZAshraff Hathibelagal

How to Create an Instant App Feature

$
0
0

Android instant apps are a powerful new way of getting your app in front of as many users as possible. 

Once you’ve added instant app support to your project, users don’t even need to have your app installed in order to access its contents and features—they’ll be able to load entire sections of your application on-demand, simply by tapping a URL. 

In this three-part series, I’m covering the entire process of adding instant app support to your Android projects, so by the time you’ve finished you’ll know exactly how to create Android applications that are discoverable and accessible for any location that supports URLs. 

In the first post, we looked at what instant apps are and how they work, as well as examining why this new feature is such big news for both Android developers and Android users. Previously, we took a few shortcuts and created an Android project that has instant app support built-in, but we didn’t look at how to add instant app support to an existing project—so this is what we’re going to be focusing on in this post. 

I’ll also be showing you how to implement App Links, so by the end of this article you’ll have created a fully functioning instant app that you can launch and test on any compatible Android device.

Downloading the Sample Project 

Adding instant app support to a project typically requires you to make some pretty drastic changes to how that project is structured. 

Chances are you’re not too keen on the idea of experimenting with a new feature by completely changing the structure of one of your own Android projects, so I’ve provided a sample app that you can download from GitHub. Throughout this article, we’ll be working on updating this specific project to support the instant apps feature. 

Download the MyLocation project from GitHub and open it in Android Studio. You’ll see that this is a pretty straightforward project, made up of a single app module that contains one Activity (MapsActivity). 

The MyLocation project displays your current location on a Google Map

Although you can install and launch this project in its current state, if MapsActivity is going to display any real content, then you’ll need to generate an API key and add it to this project: 

  • Open the project’s res/values/google_maps_api.xml file.
  • Generate your Google Maps API key, by following the instructions in this file.
  • Copy/paste the resulting key into the google_maps_api.xml file:

We’re going to update this project so that its single feature (i.e. the ability to display the user’s current location on a map) is available in instant app form. To achieve this, we’re going to complete the following steps:  

  • Create a base feature module containing all the code and resources that are required to deliver this single feature. 
  • Create an instant app module that’ll serve as the container for our instant app APK. 
  • Use App Links to map a specific URL to this base feature module.

Before we begin, there are also a few things you need to be aware of:

  • We won’t be adding any additional feature modules to this project until the next post. However, as you’ll see when we come to test MyLocation, it’s perfectly possible to add instant app support to a project by creating a base feature module and an instant app module—additional feature modules are an optional extra.
  • Since the MyLocation project consists of a single feature only, we pretty much need to include all of its code and resources in the base feature module. We can make this task much easier by turning this project’s app module into the base feature module, and then creating a new module to serve as a replacement app module. This is a handy shortcut that you may be able to use when adding instant app functionality to your own real-life Android projects. However, if this shortcut isn’t feasible for a particular project, then you’ll need to create a new module to act as your base feature module, and then spend some time moving all the relevant code and resources into this new base feature module. 

Convert the App Module Into a Base Feature Module

Our first task is converting MyLocation’s app module into a base feature module.

When you’re working with multiple modules, it helps to establish a naming convention early on, so throughout this article I’m going to be appending each module’s type (-app, -base, -instantapp, etc.) to the module’s name: 

  • Control-click the app directory and select Refactor > Rename…
Select Refactor  Rename from the context menu
  • In the Rename module window, enter mylocation-base and then click OK
  • Open your newly-renamed mylocation-base module’s build.gradle file. The first line reveals that this module is still using the default com.android.application plugin; however, all feature modules must use the com.android.feature plugin, so you’ll need to change this to apply plugin: 'com.android.feature.'.
  • Make it clear that this module is your project’s one and only base feature module, by adding the baseFeature true attribute to the android block of code. 
  • Any project that supports the instant app feature is inevitably going to consist of multiple modules, but you only need to declare the project’s applicationID once—and that’s in the app module. To avoid conflicts and confusion, you should remove this attribute from the rest of your project, so find the applicationID attribute in the mylocation-basebuild.gradle file, and delete it. 

After completing all these steps, your mylocation-basebuild.gradle file should look something like this:

Create Your Application Module 

At this point, MyLocation is missing an application module, so let’s create a replacement: 

  • Select New > New module… from the Android Studio toolbar.
  • In the window that appears, select Phone and Tablet, and then click Next.
  • Let’s stick to the naming convention we’ve established, and call this module mylocation-app. Click Next
  • This module should contain the code and resources that you want to include in your installable application, but to help keep things as straightforward as possible, click Add No Activity, and then click Finish.
  • Open your mylocation-app module’s Manifest file. If you think back to the project we created in the previous post, you’ll remember that the app module’s Manifest was pretty much empty, because eventually the contents of all the other Manifests scattered throughout this project would be merged with this file. This is exactly what’s going to happen with our MyLocation project, so to avoid any conflicts during the merging process, you should delete this Manifest’s entire application block. 
Delete the application block of code from your Manifest
  • Open the mylocation-app module’s build.gradle file. This module depends on our mylocation-base module, so remove all the code from the dependencies block, and replace it with the following: 
  • Remove all unused files and directories from your application module, by switching to Android Studio’s Project view and deleting the src/androidTest directory. Then, open the main directory and delete the Java, res and test directories. 
Delete the following files and directories srcandroidTest mainJava mainres and maintest

We’ve successfully moved all of MyLocation’s functionality into a shareable base feature module. Since this required us to make some pretty drastic changes to our project structure, you should check that MyLocation is still functioning as an installable app:

  • Launch the AVD (Android Virtual Device) we created in part one, or connect a physical Android device that’s compatible with the instant app feature—at the time of writing, this is limited to the Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher.
  • Select Run > Run… from the Android Studio toolbar.
  • Select the mylocation-app module. 
  • The MyLocation app will appear onscreen and, assuming that you generated a Google Maps API key for this project, it should be displaying some Google Maps content. 

Creating the Instant App Module 

The instant app module fulfils the simple, but essential task of acting as a container for all the Instant App APKs that are generated by your project. To create this module:

  • Select File > New > New Module… from the Android Studio toolbar.
  • In the subsequent window, select Instant App and then click Next
  • Give this module the name mylocation-instantapp and click Finish
  • Since this instant app module exists solely to contain our base feature module, we need to open its build.gradle file and declare mylocation-base as a dependency: 

Adding App Links to Your Project

The user launches an instant app by tapping a URL that’s mapped to a base feature or feature module. This URL could be anywhere—maybe it’s a URL a friend has sent them directly via email or instant message; maybe it’s a URL they’ve spotted in a tweet, forum or in a comment thread, or a URL that’s popped up in their Google search results. 

Regardless of where it appears, when the user taps this link, Google Play will recognise that it’s associated with a base feature or feature module, and retrieves all the code and resources required to run this particular module on the user’s device.

In this section, we’re going to establish this relationship between our base feature module and a URL, using App Links. The Android App Links feature was originally introduced to help users bypass Android’s app selection dialog when they were trying to access content that could be handled by an app that’s already installed on their device. For example, if you tap a link to a YouTube video, then the system may display a dialog asking whether you want to open this link in the YouTube app.

In the context of instant apps, App Links allow you to map a feature module’s entry-point Activity to a specific URL. We explored entry-point Activities in part one, but as a recap, they’re the first Activity the user sees when they launch your base feature or “regular” feature module. 

When you’re adding instant app support to a real-life project, you’ll need to decide which Activity would make the most effective introduction to your instant app component, but since mylocation-base only has a single Activity, this decision has already been made for us! 

Digital Asset Links

In this section, we’re going to use Android Studio’s built-in App Links Assistant to associate MapsActivity with the URL www.example.com/maps, but first, a disclaimer:

Uploading a Digital Asset Links file to the domain you’re working with (in this instance, www.example.com) is a crucial step in the App Links process, as it’s how the system verifies that your app has permission to act as the default handler for all the links associated with this domain. 

Although I’ll be covering the process of generating and uploading a Digital Asset Links file, since we don’t own the www.example.com domain, we won’t actually be able to perform this step. However, strangely, at the time of writing it does seem possible to test an instant app component on an AVD, even if you haven’t uploaded a Digital Asset Link to the associated domain—you just need to make some tweaks to Android Studio’s runtime configuration. 

If you do have easy access to a domain where you can host a Digital Asset Links file, then I’d recommend replacing the www.example.com URLs with genuine URLs and uploading the resulting Digital Asset Links file to your website. However, even if you do use the www.example.com URLs then you should still be able to test MyLocation’s instant app component, by tweaking the runtime configuration.

Create the URL Mapping

Android Studio 2.3 and higher comes with a built-in App Links Assistant that makes adding App Links to your project much more straightforward: 

  • Select Tools > App Links Assistant from the Android Studio toolbar. The Assistant will open as a new panel along the right side of the Android Studio window. 
  • Give the Open URL Mapping Editor button a click.
  • In the URL-to-Activity mappings panel that appears, click the little + icon. 
  • In the Host field, enter the domain you want to associate with this project; I’m going to use www.example.com

The next step is entering the specific URL you want to use in your mapping. You have a few options here, so open the Path dropdown and choose from: 

  • Path. You should select this option if you want to map a single URL to your entry-point Activity. Since I only want MapsActivity to respond to the www.example.com/maps URL, I’m going to select Path from this dropdown menu. We’ve already associated the domain www.example.com with our project, so we just need to type the final part of the URL (/maps) into the accompanying text field. 
Select Path from the dropdown menu and enter maps in the accompanying text field
  • pathPattern. Similar to Path, this option lets you specify the exact URL that should launch your entry-point Activity. However, it also gives you a bit more flexibility, by allowing you to use wildcard characters in the accompanying text field. 

Next, you need to select MapsActivity as this module’s entry-point Activity:

  • Open the Activity dropdown menu.
  • Select .MapsActivity (mylocation-base).
  • Click OK.

The App Links Assistant helpfully updates your Manifest with all the code required to turn MapsActivity into this module’s entry-point Activity; if you take a look at your mylocation-base module’s Manifest, then you’ll see the following code: 

Next, we need to tell MapsActivity how to respond when it’s launched via this URL. Once again, the App Links Assistant can walk you through this process:

  • Back in the App Links Assistant, give the Select Activity button a click. 
  • Select the Activity you want to map to your URL, which in this instance is MapsActivity
  • Click Insert code, and the App Links Assistant will insert the following code into the MapsActivity

When you come to add instant app support to your own real-life projects, you’ll typically want to expand on this code, depending on how you want your Activity to react when it’s launched as an instant app, but for the purposes of our MyLocation project, these few lines get the job done. 

Associate Your App With Your Website

In this section I’m going to show you how to generate a Digital Asset Links file, and how to upload this file to your website. If you’re using www.example.com as a stand-in for genuine URLs, then you won’t be able to complete this step, but it’s still important to understand how to generate and upload this file, ready for when you’re adding instant app support to your own Android projects. 

To create this association between your domain and your application, you need to complete the following steps: 

  • In the App Links Assistant, click the Open the Digital Asset Links File Generator button.
  • Enter the domain you want to associate with this app, such as www.example.com.  
  • Enter your application ID.
  • Enter your app’s signing config, or select a keystore file. While it’s possible to use a debug config or keystore during testing, the generated Digital Asset Links file won’t be compatible with the release version of your app. If you do upload a Digital Asset Links file that uses a debug config or keystore, then before publishing your app you’ll need to generate and upload a new Digital Asset Links that uses your app’s release key.
  • Click the Generate Digital Asset Links file button. 
  • Download the Digital Asset File, by clicking the Save file button. In the Canary builds of Android Studio 3.0, this button is sometimes positioned offscreen, so you may need to resize your Android Studio window in order to bring the Save file button out of hiding. Clicking this button will download an assetlinks.json file to your computer. 
  • You must host the assetlinks.json file at the following address https://<yoursite>/.well-known/assetlinks.json, so upload your newly downloaded assetlinks.json file to this exact location. Also be aware that Android verifies the assetlinks.json file via an encrypted HTTPs protocol, so you’ll need to ensure this file is accessible over an HTTPS connection.
  • Back in Android Studio, click the App Link Assistant’s Link and verify button. If you’re following along with this tutorial using the www.example.com stand-in links, then Android Studio should report that you’ve successfully completed every step, except uploading the Digital Asset Links file.

Testing Your Instant App 

Now you’re finally ready to test MyLocation’s instant app component!

Specifically, we want to test that if a user doesn’t have MyLocation installed on their device, then tapping the www.example.com/maps link will give them access to the mylocation-base module:

  • Launch your instant app-compatible AVD.
  • Verify that the MyLocation app isn’t installed on your AVD by opening its launcher. If you do spot the MyLocation app, then uninstall it by dragging it to the device’s Uninstall icon. 
  • Next, you’ll need to make some tweaks to our project’s run configuration, especially if you’re using www.example.com/maps to trigger your mylocation-base module. Start by selecting Run > Edit configurations... from the Android Studio toolbar. 
  • Select mylocation-instantapp from the left-hand menu. 
  • Open the Launch dropdown and set it to URL.
  • Delete the <> text, and replace it with the URL you want to use, such as http://www.example.com/maps. When you select this run configuration, it’ll simulate the user tapping the www.example.com/maps link. 
Delete the Error text and replace it with wwwexamplecommaps
  • Click Apply, followed by OK
  • Select Run > Run… from the Android Studio toolbar.
  • Choose mylocation-instantapp as the component you want to launch. 
  • Select your target AVD, and click OK
  • If this is the first time you’re running an instant app on this particular AVD, then the device will prompt you to opt into the instant app program. Read the disclaimer, and if you’re happy to proceed, then click Yes, I’m in.

Android Studio will now simulate you tapping the www.example.com/maps link, and the AVD should respond by loading your base feature module. At this point, the MapsActivity will appear onscreen, and you’ll be able to interact with it exactly as though MyLocation was installed on this device. 

To verify that MyLocation really isn’t present on this device, minimise the MapsActivity and open the AVD’s launcher—the MyLocation app should be completely absent, and yet if you click the AVD’s Recents softkey, the MapsActivity is still visible and available on this device. 

You can download the MyLocation project, updated with full instant app support, from GitHub.

Troubleshooting

Instant apps is still very much a new feature, so it’s not all that unusual to encounter error messages, bugs and other strange behaviour, especially if you’re using one of the Preview or Canary builds of Android Studio 3.0.

The most common problem you’ll encounter is, when selecting Run > Run instantapp from the Android Studio toolbar, to have the AVD respond by displaying the app picker dialog or by opening the URL in its default browser. If this occurs, then it means the AVD isn’t properly recognising that your URL is mapped to an instant app module, and is handling it just like a regular URL.

Assuming that you’ve implemented instant app support correctly, there are a few possible reasons why your AVD may be refusing to cooperate: 

Is Your AVD Set Up to Allow Instant Apps?

Depending on the AVD you’ve created, it’s possible that you may need to explicitly tell your AVD to support instant apps:

  • Open the AVD’s Settings app.
  • Select Google.
  • Scroll to the Services section.
  • If you spot an Instant app option, then give it a tap.
  • On the subsequent screen, drag the slider into the On position. 
  • Repeat the process of trying to launch your instant app module on your AVD, to see whether this has fixed your problem.

Are Instant Apps Supported in Your Locale?

Instant apps aren’t supported in every locale, so check whether instant apps are currently available in your part of the world. If they aren’t, then you’ll need to use adb (Android Debug Bridge) commands to trick your AVD into thinking you’re in a different location:  

  • Open the Terminal (if you’re a Mac user) or Command Prompt, if you’re on Windows.
  • “Change directory” so the Terminal or Command Prompt is pointing at the adb program that’s included in your Android SDK, for example: 
  • Next, enter the following command:
  • Once a # appears in the Terminal or Command Prompt window, enter the next command: 
  • Your AVD will now reboot, and once it's restarted it’ll be using the new locale settings. You should now be able to successfully run instant apps on this device. 

If All Else Fails….

If none of the above fixes work, then you may get some positive results by triggering the instant app component from an adb command, rather than by navigating the various Android Studio menus: 

  • Open a Terminal or Command Prompt window.
  • Use the cd command so that the Terminal/Command Prompt is pointing at the adb program. 
  • Enter the following command, being sure to replace complete-url-path with the URL you want to use:

Side Loading Instant App Failed

Sometimes, Android Studio may outright refuse to even load an instant app component on your AVD, as some developers have reported encountering the following error whenever they try to launch an instant app:

Side loading instant app failed: Reading bundle timed out.

If you do encounter this error message in Android Studio, then you can usually resolve it by clearing the 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 pencil icon.
  • Select Clear provisioned devices cache.
Select the Clear provisioned devices cache checkbox then click OK
  • Click OK, followed by Apply, and then hit OK once more. 
  • Attempt to relaunch your instant app component on your AVD—the problem should now be resolved. 

Conclusion 

In this article, we looked at how to update an existing Android project to support instant apps, by creating a base feature module and an instant app module, implementing App Links, and then testing this project on an AVD. 

At this point, you have all the information you need to add instant app functionality to your existing Android projects, but with one restriction: we’ve only created a single base feature module. This means that, currently, you’re limited to offering one instant app feature per project.

In the final post of this series, we’re going to rectify this by looking at how you’d add an extra feature module to the MyLocation project. That'll be out soon. While you're waiting, check out some of our other great posts on Android app development!


2017-08-08T17:00:00.000Z2017-08-08T17:00:00.000ZJessica Thornsby

How to Create an Instant App Feature

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

Android instant apps are a powerful new way of getting your app in front of as many users as possible. 

Once you’ve added instant app support to your project, users don’t even need to have your app installed in order to access its contents and features—they’ll be able to load entire sections of your application on-demand, simply by tapping a URL. 

In this three-part series, I’m covering the entire process of adding instant app support to your Android projects, so by the time you’ve finished you’ll know exactly how to create Android applications that are discoverable and accessible for any location that supports URLs. 

In the first post, we looked at what instant apps are and how they work, as well as examining why this new feature is such big news for both Android developers and Android users. Previously, we took a few shortcuts and created an Android project that has instant app support built-in, but we didn’t look at how to add instant app support to an existing project—so this is what we’re going to be focusing on in this post. 

I’ll also be showing you how to implement App Links, so by the end of this article you’ll have created a fully functioning instant app that you can launch and test on any compatible Android device.

Downloading the Sample Project 

Adding instant app support to a project typically requires you to make some pretty drastic changes to how that project is structured. 

Chances are you’re not too keen on the idea of experimenting with a new feature by completely changing the structure of one of your own Android projects, so I’ve provided a sample app that you can download from GitHub. Throughout this article, we’ll be working on updating this specific project to support the instant apps feature. 

Download the MyLocation project from GitHub and open it in Android Studio. You’ll see that this is a pretty straightforward project, made up of a single app module that contains one Activity (MapsActivity). 

The MyLocation project displays your current location on a Google Map

Although you can install and launch this project in its current state, if MapsActivity is going to display any real content, then you’ll need to generate an API key and add it to this project: 

  • Open the project’s res/values/google_maps_api.xml file.
  • Generate your Google Maps API key, by following the instructions in this file.
  • Copy/paste the resulting key into the google_maps_api.xml file:

We’re going to update this project so that its single feature (i.e. the ability to display the user’s current location on a map) is available in instant app form. To achieve this, we’re going to complete the following steps:  

  • Create a base feature module containing all the code and resources that are required to deliver this single feature. 
  • Create an instant app module that’ll serve as the container for our instant app APK. 
  • Use App Links to map a specific URL to this base feature module.

Before we begin, there are also a few things you need to be aware of:

  • We won’t be adding any additional feature modules to this project until the next post. However, as you’ll see when we come to test MyLocation, it’s perfectly possible to add instant app support to a project by creating a base feature module and an instant app module—additional feature modules are an optional extra.
  • Since the MyLocation project consists of a single feature only, we pretty much need to include all of its code and resources in the base feature module. We can make this task much easier by turning this project’s app module into the base feature module, and then creating a new module to serve as a replacement app module. This is a handy shortcut that you may be able to use when adding instant app functionality to your own real-life Android projects. However, if this shortcut isn’t feasible for a particular project, then you’ll need to create a new module to act as your base feature module, and then spend some time moving all the relevant code and resources into this new base feature module. 

Convert the App Module Into a Base Feature Module

Our first task is converting MyLocation’s app module into a base feature module.

When you’re working with multiple modules, it helps to establish a naming convention early on, so throughout this article I’m going to be appending each module’s type (-app, -base, -instantapp, etc.) to the module’s name: 

  • Control-click the app directory and select Refactor > Rename…
Select Refactor  Rename from the context menu
  • In the Rename module window, enter mylocation-base and then click OK
  • Open your newly-renamed mylocation-base module’s build.gradle file. The first line reveals that this module is still using the default com.android.application plugin; however, all feature modules must use the com.android.feature plugin, so you’ll need to change this to apply plugin: 'com.android.feature.'.
  • Make it clear that this module is your project’s one and only base feature module, by adding the baseFeature true attribute to the android block of code. 
  • Any project that supports the instant app feature is inevitably going to consist of multiple modules, but you only need to declare the project’s applicationID once—and that’s in the app module. To avoid conflicts and confusion, you should remove this attribute from the rest of your project, so find the applicationID attribute in the mylocation-basebuild.gradle file, and delete it. 

After completing all these steps, your mylocation-basebuild.gradle file should look something like this:

Create Your Application Module 

At this point, MyLocation is missing an application module, so let’s create a replacement: 

  • Select New > New module… from the Android Studio toolbar.
  • In the window that appears, select Phone and Tablet, and then click Next.
  • Let’s stick to the naming convention we’ve established, and call this module mylocation-app. Click Next
  • This module should contain the code and resources that you want to include in your installable application, but to help keep things as straightforward as possible, click Add No Activity, and then click Finish.
  • Open your mylocation-app module’s Manifest file. If you think back to the project we created in the previous post, you’ll remember that the app module’s Manifest was pretty much empty, because eventually the contents of all the other Manifests scattered throughout this project would be merged with this file. This is exactly what’s going to happen with our MyLocation project, so to avoid any conflicts during the merging process, you should delete this Manifest’s entire application block. 
Delete the application block of code from your Manifest
  • Open the mylocation-app module’s build.gradle file. This module depends on our mylocation-base module, so remove all the code from the dependencies block, and replace it with the following: 
  • Remove all unused files and directories from your application module, by switching to Android Studio’s Project view and deleting the src/androidTest directory. Then, open the main directory and delete the Java, res and test directories. 
Delete the following files and directories srcandroidTest mainJava mainres and maintest

We’ve successfully moved all of MyLocation’s functionality into a shareable base feature module. Since this required us to make some pretty drastic changes to our project structure, you should check that MyLocation is still functioning as an installable app:

  • Launch the AVD (Android Virtual Device) we created in part one, or connect a physical Android device that’s compatible with the instant app feature—at the time of writing, this is limited to the Nexus 5X, Nexus 6P, Pixel, Pixel XL, or a Galaxy S7 that’s running Android 6.0 or higher.
  • Select Run > Run… from the Android Studio toolbar.
  • Select the mylocation-app module. 
  • The MyLocation app will appear onscreen and, assuming that you generated a Google Maps API key for this project, it should be displaying some Google Maps content. 

Creating the Instant App Module 

The instant app module fulfils the simple, but essential task of acting as a container for all the Instant App APKs that are generated by your project. To create this module:

  • Select File > New > New Module… from the Android Studio toolbar.
  • In the subsequent window, select Instant App and then click Next
  • Give this module the name mylocation-instantapp and click Finish
  • Since this instant app module exists solely to contain our base feature module, we need to open its build.gradle file and declare mylocation-base as a dependency: 

Adding App Links to Your Project

The user launches an instant app by tapping a URL that’s mapped to a base feature or feature module. This URL could be anywhere—maybe it’s a URL a friend has sent them directly via email or instant message; maybe it’s a URL they’ve spotted in a tweet, forum or in a comment thread, or a URL that’s popped up in their Google search results. 

Regardless of where it appears, when the user taps this link, Google Play will recognise that it’s associated with a base feature or feature module, and retrieves all the code and resources required to run this particular module on the user’s device.

In this section, we’re going to establish this relationship between our base feature module and a URL, using App Links. The Android App Links feature was originally introduced to help users bypass Android’s app selection dialog when they were trying to access content that could be handled by an app that’s already installed on their device. For example, if you tap a link to a YouTube video, then the system may display a dialog asking whether you want to open this link in the YouTube app.

In the context of instant apps, App Links allow you to map a feature module’s entry-point Activity to a specific URL. We explored entry-point Activities in part one, but as a recap, they’re the first Activity the user sees when they launch your base feature or “regular” feature module. 

When you’re adding instant app support to a real-life project, you’ll need to decide which Activity would make the most effective introduction to your instant app component, but since mylocation-base only has a single Activity, this decision has already been made for us! 

Digital Asset Links

In this section, we’re going to use Android Studio’s built-in App Links Assistant to associate MapsActivity with the URL www.example.com/maps, but first, a disclaimer:

Uploading a Digital Asset Links file to the domain you’re working with (in this instance, www.example.com) is a crucial step in the App Links process, as it’s how the system verifies that your app has permission to act as the default handler for all the links associated with this domain. 

Although I’ll be covering the process of generating and uploading a Digital Asset Links file, since we don’t own the www.example.com domain, we won’t actually be able to perform this step. However, strangely, at the time of writing it does seem possible to test an instant app component on an AVD, even if you haven’t uploaded a Digital Asset Link to the associated domain—you just need to make some tweaks to Android Studio’s runtime configuration. 

If you do have easy access to a domain where you can host a Digital Asset Links file, then I’d recommend replacing the www.example.com URLs with genuine URLs and uploading the resulting Digital Asset Links file to your website. However, even if you do use the www.example.com URLs then you should still be able to test MyLocation’s instant app component, by tweaking the runtime configuration.

Create the URL Mapping

Android Studio 2.3 and higher comes with a built-in App Links Assistant that makes adding App Links to your project much more straightforward: 

  • Select Tools > App Links Assistant from the Android Studio toolbar. The Assistant will open as a new panel along the right side of the Android Studio window. 
  • Give the Open URL Mapping Editor button a click.
  • In the URL-to-Activity mappings panel that appears, click the little + icon. 
  • In the Host field, enter the domain you want to associate with this project; I’m going to use www.example.com

The next step is entering the specific URL you want to use in your mapping. You have a few options here, so open the Path dropdown and choose from: 

  • Path. You should select this option if you want to map a single URL to your entry-point Activity. Since I only want MapsActivity to respond to the www.example.com/maps URL, I’m going to select Path from this dropdown menu. We’ve already associated the domain www.example.com with our project, so we just need to type the final part of the URL (/maps) into the accompanying text field. 
Select Path from the dropdown menu and enter maps in the accompanying text field
  • pathPattern. Similar to Path, this option lets you specify the exact URL that should launch your entry-point Activity. However, it also gives you a bit more flexibility, by allowing you to use wildcard characters in the accompanying text field. 

Next, you need to select MapsActivity as this module’s entry-point Activity:

  • Open the Activity dropdown menu.
  • Select .MapsActivity (mylocation-base).
  • Click OK.

The App Links Assistant helpfully updates your Manifest with all the code required to turn MapsActivity into this module’s entry-point Activity; if you take a look at your mylocation-base module’s Manifest, then you’ll see the following code: 

Next, we need to tell MapsActivity how to respond when it’s launched via this URL. Once again, the App Links Assistant can walk you through this process:

  • Back in the App Links Assistant, give the Select Activity button a click. 
  • Select the Activity you want to map to your URL, which in this instance is MapsActivity
  • Click Insert code, and the App Links Assistant will insert the following code into the MapsActivity

When you come to add instant app support to your own real-life projects, you’ll typically want to expand on this code, depending on how you want your Activity to react when it’s launched as an instant app, but for the purposes of our MyLocation project, these few lines get the job done. 

Associate Your App With Your Website

In this section I’m going to show you how to generate a Digital Asset Links file, and how to upload this file to your website. If you’re using www.example.com as a stand-in for genuine URLs, then you won’t be able to complete this step, but it’s still important to understand how to generate and upload this file, ready for when you’re adding instant app support to your own Android projects. 

To create this association between your domain and your application, you need to complete the following steps: 

  • In the App Links Assistant, click the Open the Digital Asset Links File Generator button.
  • Enter the domain you want to associate with this app, such as www.example.com.  
  • Enter your application ID.
  • Enter your app’s signing config, or select a keystore file. While it’s possible to use a debug config or keystore during testing, the generated Digital Asset Links file won’t be compatible with the release version of your app. If you do upload a Digital Asset Links file that uses a debug config or keystore, then before publishing your app you’ll need to generate and upload a new Digital Asset Links that uses your app’s release key.
  • Click the Generate Digital Asset Links file button. 
  • Download the Digital Asset File, by clicking the Save file button. In the Canary builds of Android Studio 3.0, this button is sometimes positioned offscreen, so you may need to resize your Android Studio window in order to bring the Save file button out of hiding. Clicking this button will download an assetlinks.json file to your computer. 
  • You must host the assetlinks.json file at the following address https://<yoursite>/.well-known/assetlinks.json, so upload your newly downloaded assetlinks.json file to this exact location. Also be aware that Android verifies the assetlinks.json file via an encrypted HTTPs protocol, so you’ll need to ensure this file is accessible over an HTTPS connection.
  • Back in Android Studio, click the App Link Assistant’s Link and verify button. If you’re following along with this tutorial using the www.example.com stand-in links, then Android Studio should report that you’ve successfully completed every step, except uploading the Digital Asset Links file.

Testing Your Instant App 

Now you’re finally ready to test MyLocation’s instant app component!

Specifically, we want to test that if a user doesn’t have MyLocation installed on their device, then tapping the www.example.com/maps link will give them access to the mylocation-base module:

  • Launch your instant app-compatible AVD.
  • Verify that the MyLocation app isn’t installed on your AVD by opening its launcher. If you do spot the MyLocation app, then uninstall it by dragging it to the device’s Uninstall icon. 
  • Next, you’ll need to make some tweaks to our project’s run configuration, especially if you’re using www.example.com/maps to trigger your mylocation-base module. Start by selecting Run > Edit configurations... from the Android Studio toolbar. 
  • Select mylocation-instantapp from the left-hand menu. 
  • Open the Launch dropdown and set it to URL.
  • Delete the <> text, and replace it with the URL you want to use, such as http://www.example.com/maps. When you select this run configuration, it’ll simulate the user tapping the www.example.com/maps link. 
Delete the Error text and replace it with wwwexamplecommaps
  • Click Apply, followed by OK
  • Select Run > Run… from the Android Studio toolbar.
  • Choose mylocation-instantapp as the component you want to launch. 
  • Select your target AVD, and click OK
  • If this is the first time you’re running an instant app on this particular AVD, then the device will prompt you to opt into the instant app program. Read the disclaimer, and if you’re happy to proceed, then click Yes, I’m in.

Android Studio will now simulate you tapping the www.example.com/maps link, and the AVD should respond by loading your base feature module. At this point, the MapsActivity will appear onscreen, and you’ll be able to interact with it exactly as though MyLocation was installed on this device. 

To verify that MyLocation really isn’t present on this device, minimise the MapsActivity and open the AVD’s launcher—the MyLocation app should be completely absent, and yet if you click the AVD’s Recents softkey, the MapsActivity is still visible and available on this device. 

You can download the MyLocation project, updated with full instant app support, from GitHub.

Troubleshooting

Instant apps is still very much a new feature, so it’s not all that unusual to encounter error messages, bugs and other strange behaviour, especially if you’re using one of the Preview or Canary builds of Android Studio 3.0.

The most common problem you’ll encounter is, when selecting Run > Run instantapp from the Android Studio toolbar, to have the AVD respond by displaying the app picker dialog or by opening the URL in its default browser. If this occurs, then it means the AVD isn’t properly recognising that your URL is mapped to an instant app module, and is handling it just like a regular URL.

Assuming that you’ve implemented instant app support correctly, there are a few possible reasons why your AVD may be refusing to cooperate: 

Is Your AVD Set Up to Allow Instant Apps?

Depending on the AVD you’ve created, it’s possible that you may need to explicitly tell your AVD to support instant apps:

  • Open the AVD’s Settings app.
  • Select Google.
  • Scroll to the Services section.
  • If you spot an Instant app option, then give it a tap.
  • On the subsequent screen, drag the slider into the On position. 
  • Repeat the process of trying to launch your instant app module on your AVD, to see whether this has fixed your problem.

Are Instant Apps Supported in Your Locale?

Instant apps aren’t supported in every locale, so check whether instant apps are currently available in your part of the world. If they aren’t, then you’ll need to use adb (Android Debug Bridge) commands to trick your AVD into thinking you’re in a different location:  

  • Open the Terminal (if you’re a Mac user) or Command Prompt, if you’re on Windows.
  • “Change directory” so the Terminal or Command Prompt is pointing at the adb program that’s included in your Android SDK, for example: 
  • Next, enter the following command:
  • Once a # appears in the Terminal or Command Prompt window, enter the next command: 
  • Your AVD will now reboot, and once it's restarted it’ll be using the new locale settings. You should now be able to successfully run instant apps on this device. 

If All Else Fails….

If none of the above fixes work, then you may get some positive results by triggering the instant app component from an adb command, rather than by navigating the various Android Studio menus: 

  • Open a Terminal or Command Prompt window.
  • Use the cd command so that the Terminal/Command Prompt is pointing at the adb program. 
  • Enter the following command, being sure to replace complete-url-path with the URL you want to use:

Side Loading Instant App Failed

Sometimes, Android Studio may outright refuse to even load an instant app component on your AVD, as some developers have reported encountering the following error whenever they try to launch an instant app:

Side loading instant app failed: Reading bundle timed out.

If you do encounter this error message in Android Studio, then you can usually resolve it by clearing the 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 pencil icon.
  • Select Clear provisioned devices cache.
Select the Clear provisioned devices cache checkbox then click OK
  • Click OK, followed by Apply, and then hit OK once more. 
  • Attempt to relaunch your instant app component on your AVD—the problem should now be resolved. 

Conclusion 

In this article, we looked at how to update an existing Android project to support instant apps, by creating a base feature module and an instant app module, implementing App Links, and then testing this project on an AVD. 

At this point, you have all the information you need to add instant app functionality to your existing Android projects, but with one restriction: we’ve only created a single base feature module. This means that, currently, you’re limited to offering one instant app feature per project.

In the final post of this series, we’re going to rectify this by looking at how you’d add an extra feature module to the MyLocation project. That'll be out soon. While you're waiting, check out some of our other great posts on Android app development!


2017-08-08T17:00:00.000Z2017-08-08T17:00:00.000ZJessica Thornsby

How to Get Started With CocoaPods

$
0
0

In this tutorial, you'll be learning about the CocoaPods dependency manager and how to implement it in your app. We'll go through the steps from creating an Xcode project all the way to importing frameworks. Along the way, we will learn about some basic Terminal commands and what they do.

About CocoaPods

Before we get into actually implementing CocoaPods in our Xcode project, let's talk a little bit about what it is and why you should use it in the first place.

What Is CocoaPods?

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 35 thousand libraries and is used in over 2.4 million apps. CocoaPods can help you scale your projects elegantly. — CocoaPods website

CocoaPods is getting increasingly popular nowadays for Cocoa Touch development—and with good reason. CocoaPods is an easy-to-use, easy-to-implement dependency manager for your apps written in Swift or Objective-C.

What the Heck Is a Dependency Manager?

Glad you asked! In short, a dependency manager is a tool used to manage third-party frameworks. In CocoaPods, dependencies are listed in a text file called a podfile (which we will get to shortly) with simple one-line statements. 

This solves the issue of having to download and add each framework manually to your Xcode project and then deleting and reinstalling outdated frameworks (that's just a pain). Some libraries even use their own frameworks in their SDK (such as Firebase), and every time they make a small update, you have to manually reinstall everything!

Why Should I Use CocoaPods?

While there are other dependency managers out there (such as Carthage), CocoaPods is still the most widely used, and therefore, has the most libraries available for your use. Since it is the most popular, there are also more discussions regarding it on StackOverflow and other forums—that's helpful in case you ever get stuck.

Let's think of a common scenario: something that CocoaPods (or any dependency manager) can solve. You set out to build an app. This app is huge, and you don't want to rewrite code that someone else has already written, so you create a list of libraries that you think would be good to have in your project. It would be nearly impossible to be able to correctly install all of them manually and future-proof your code at the same time! This is where CocoaPods comes in.

Using CocoaPods

CocoaPods is built with Ruby, which is installed by default on versions of macOS. In this tutorial, we will be using gem to install the necessary Ruby gems to get CocoaPods set up. Gems are Ruby packages, and since CocoaPods is a Ruby program, it needs to be installed with Ruby's package manager.

To start, open up a new terminal window. You can find this in Applications> Utilities or you can simply search for it in Spotlight Search (Command-Space).

1. Installation

Enter the following line of code in your Terminal.

Then, press Enter. You will be prompted to enter your password, and when you have done so, press Enter again. After you do so, CocoaPods will install, and when it is finished your terminal should look something like this:

CocoaPods installed successfully

2. Create an Xcode Project

CocoaPods can be added to any existing Xcode project, but for the purposes of this tutorial, let's create a new one. Please feel free to follow along with your own Xcode project and skip this step.

Launch Xcode

After launching Xcode, you will see three options. Click on the second option which says Create a new Xcode project. If you have used Xcode in the past, your recent projects will appear on the right.

Welcome to Xcode

Choose Your Application Type

For this project, we will choose a single view application, but you can choose any template you need to for your specific purposes.

Choose an app template

Configure Your Project

Now, name your project and choose Swift as the language. Here, you can also set the bundle identifier and choose the devices that your app would support. Again, it is up to you, but I will name it CocoaPods.

Configuring your project

3. Create a Podfile

After you have created an Xcode project, the next step is to navigate to it using the terminal. Many of you may be familiar with this, but let's go over it together; after all, practice makes perfect!

Find the Project Directory

Before you can navigate to the project directory using the command line, it is a good idea to locate your project using the Finder first. In this case, my project is on my desktop in a folder named Tuts+.

Basic Commands

  • sudo—a way to override your user's privileges and become a super-user of the computer. This is why it requires an admin password when using it. We used this command while installing CocoaPods earlier.
  • ls—lists all of the contents in the current directory. This command comes in handy if you don't want to use the Finder to browse files; you can simply list them using this command in your Terminal.
  • cd <directory name>—this command is used to change directories. If you write cd alone, you will move out of the current directory. After using ls (to see the directories), you can write the name of the directory you want to enter.
  • vim—this is one of my favorites. Remember the podfile that I mentioned earlier? You can edit this file using the default TextEdit, but I like to use the terminal. vim is a command line text editor which we will be using to edit our podfile.

Some bonus ones: These aren't necessary right now, but hey, why not learn some more cool things while you're at it?

  • mkdir <directory name>—you can kind of tell what this one does by its name; it makes a directory (now that wasn't so hard, was it?). You have to type the name of the directory after the keyword mkdir and voila, there you have a folder appear (almost) instantly.
  • help—this command is nice because (as the name suggests), it helps you out if you ever forget a command. Just type help into your Terminal window, and a list of basic commands will pop up with their meaning.

Initialize CocoaPods

Since you have already installed CocoaPods on your machine, the next thing to do is actually initialize your Xcode project. Find where your project is located on your hard drive and follow along in your own directory.

After you are done navigating to your project via the terminal, your window should look like this. I have highlighted my project name, and yours should appear in the same spot. It should look something like this:

Ready to initialize the Xcode project

Once you are in your project directory, you will need to initialize CocoaPods, resulting in a podfile being created. To do this, type the following line into your terminal window:

This will initialize CocoaPods in your project folder, and you will see a file called podfile show up.

4. Set Up the Libraries

Hurray! CocoaPods is now ready to manage your project's dependencies. The next step is to actually add the desired libraries into your Xcode project—after all, that's what we are here for.

Edit the Podfile

Remember vim, the text editor? We will be using it to add the desired frameworks to the app. Type the following line to edit your podfile:

To get into edit mode, you just type i, as in "insert."

Add Pods to the Podfile

In CocoaPods, there are two ways to get the command for the framework you want. You can usually find the podfile line in the framework's GitHub project description. If not, go to the CocoaPods website and search for the library there and their podfile lines.

Below, I have a line for Firebase. 

As I said, it doesn't really matter where you get them from. Find one of these and follow the steps below. Now, enter your line under the comment which says:

That's all that's needed to add frameworks. See how easy that was? Now, we need to exit the vim editor and move on to the next step.

Exiting the vim Editor

In order to save your changes and exit the vim editor, you need to:

  1. Press the Esc key to get out of edit mode.
  2. Type :x (the save and exit command).
  3. Press Enter.

Install CocoaPods

This step is another one-liner. All you need to do is, in your project directory, type the following command:

Installing all the project dependencies

This will download any frameworks you listed in your podfile and install them to your Xcode project. The pods should be now available to import just as a regular framework would be (by using import <framework name> at the top of your source file).

5. Conclusion

I hope this tutorial was helpful. We covered installing CocoaPods, basic terminal commands, and how to add pods to your podfile. CocoaPods is a fast, easy-to-use, and effective tool for managing your dependencies, and it is very commonly used.

And remember:

  • You'll need to access your project only through <your project>.xcworkspace and not <your project>.xcodeproj.
  • The podfile can be edited using any text editor, and can also be edited within your Xcode.
  • Run pod install from the terminal after changing your podfile so the dependencies will be removed or added.

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

2017-08-10T12:00:00.000Z2017-08-10T12:00:00.000ZVardhan Agrawal

How to Get Started With CocoaPods

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

In this tutorial, you'll be learning about the CocoaPods dependency manager and how to implement it in your app. We'll go through the steps from creating an Xcode project all the way to importing frameworks. Along the way, we will learn about some basic Terminal commands and what they do.

About CocoaPods

Before we get into actually implementing CocoaPods in our Xcode project, let's talk a little bit about what it is and why you should use it in the first place.

What Is CocoaPods?

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 35 thousand libraries and is used in over 2.4 million apps. CocoaPods can help you scale your projects elegantly. — CocoaPods website

CocoaPods is getting increasingly popular nowadays for Cocoa Touch development—and with good reason. CocoaPods is an easy-to-use, easy-to-implement dependency manager for your apps written in Swift or Objective-C.

What the Heck Is a Dependency Manager?

Glad you asked! In short, a dependency manager is a tool used to manage third-party frameworks. In CocoaPods, dependencies are listed in a text file called a podfile (which we will get to shortly) with simple one-line statements. 

This solves the issue of having to download and add each framework manually to your Xcode project and then deleting and reinstalling outdated frameworks (that's just a pain). Some libraries even use their own frameworks in their SDK (such as Firebase), and every time they make a small update, you have to manually reinstall everything!

Why Should I Use CocoaPods?

While there are other dependency managers out there (such as Carthage), CocoaPods is still the most widely used, and therefore, has the most libraries available for your use. Since it is the most popular, there are also more discussions regarding it on StackOverflow and other forums—that's helpful in case you ever get stuck.

Let's think of a common scenario: something that CocoaPods (or any dependency manager) can solve. You set out to build an app. This app is huge, and you don't want to rewrite code that someone else has already written, so you create a list of libraries that you think would be good to have in your project. It would be nearly impossible to be able to correctly install all of them manually and future-proof your code at the same time! This is where CocoaPods comes in.

Using CocoaPods

CocoaPods is built with Ruby, which is installed by default on versions of macOS. In this tutorial, we will be using gem to install the necessary Ruby gems to get CocoaPods set up. Gems are Ruby packages, and since CocoaPods is a Ruby program, it needs to be installed with Ruby's package manager.

To start, open up a new terminal window. You can find this in Applications> Utilities or you can simply search for it in Spotlight Search (Command-Space).

1. Installation

Enter the following line of code in your Terminal.

Then, press Enter. You will be prompted to enter your password, and when you have done so, press Enter again. After you do so, CocoaPods will install, and when it is finished your terminal should look something like this:

CocoaPods installed successfully

2. Create an Xcode Project

CocoaPods can be added to any existing Xcode project, but for the purposes of this tutorial, let's create a new one. Please feel free to follow along with your own Xcode project and skip this step.

Launch Xcode

After launching Xcode, you will see three options. Click on the second option which says Create a new Xcode project. If you have used Xcode in the past, your recent projects will appear on the right.

Welcome to Xcode

Choose Your Application Type

For this project, we will choose a single view application, but you can choose any template you need to for your specific purposes.

Choose an app template

Configure Your Project

Now, name your project and choose Swift as the language. Here, you can also set the bundle identifier and choose the devices that your app would support. Again, it is up to you, but I will name it CocoaPods.

Configuring your project

3. Create a Podfile

After you have created an Xcode project, the next step is to navigate to it using the terminal. Many of you may be familiar with this, but let's go over it together; after all, practice makes perfect!

Find the Project Directory

Before you can navigate to the project directory using the command line, it is a good idea to locate your project using the Finder first. In this case, my project is on my desktop in a folder named Tuts+.

Basic Commands

  • sudo—a way to override your user's privileges and become a super-user of the computer. This is why it requires an admin password when using it. We used this command while installing CocoaPods earlier.
  • ls—lists all of the contents in the current directory. This command comes in handy if you don't want to use the Finder to browse files; you can simply list them using this command in your Terminal.
  • cd <directory name>—this command is used to change directories. If you write cd alone, you will move out of the current directory. After using ls (to see the directories), you can write the name of the directory you want to enter.
  • vim—this is one of my favorites. Remember the podfile that I mentioned earlier? You can edit this file using the default TextEdit, but I like to use the terminal. vim is a command line text editor which we will be using to edit our podfile.

Some bonus ones: These aren't necessary right now, but hey, why not learn some more cool things while you're at it?

  • mkdir <directory name>—you can kind of tell what this one does by its name; it makes a directory (now that wasn't so hard, was it?). You have to type the name of the directory after the keyword mkdir and voila, there you have a folder appear (almost) instantly.
  • help—this command is nice because (as the name suggests), it helps you out if you ever forget a command. Just type help into your Terminal window, and a list of basic commands will pop up with their meaning.

Initialize CocoaPods

Since you have already installed CocoaPods on your machine, the next thing to do is actually initialize your Xcode project. Find where your project is located on your hard drive and follow along in your own directory.

After you are done navigating to your project via the terminal, your window should look like this. I have highlighted my project name, and yours should appear in the same spot. It should look something like this:

Ready to initialize the Xcode project

Once you are in your project directory, you will need to initialize CocoaPods, resulting in a podfile being created. To do this, type the following line into your terminal window:

This will initialize CocoaPods in your project folder, and you will see a file called podfile show up.

4. Set Up the Libraries

Hurray! CocoaPods is now ready to manage your project's dependencies. The next step is to actually add the desired libraries into your Xcode project—after all, that's what we are here for.

Edit the Podfile

Remember vim, the text editor? We will be using it to add the desired frameworks to the app. Type the following line to edit your podfile:

To get into edit mode, you just type i, as in "insert."

Add Pods to the Podfile

In CocoaPods, there are two ways to get the command for the framework you want. You can usually find the podfile line in the framework's GitHub project description. If not, go to the CocoaPods website and search for the library there and their podfile lines.

Below, I have a line for Firebase. 

As I said, it doesn't really matter where you get them from. Find one of these and follow the steps below. Now, enter your line under the comment which says:

That's all that's needed to add frameworks. See how easy that was? Now, we need to exit the vim editor and move on to the next step.

Exiting the vim Editor

In order to save your changes and exit the vim editor, you need to:

  1. Press the Esc key to get out of edit mode.
  2. Type :x (the save and exit command).
  3. Press Enter.

Install CocoaPods

This step is another one-liner. All you need to do is, in your project directory, type the following command:

Installing all the project dependencies

This will download any frameworks you listed in your podfile and install them to your Xcode project. The pods should be now available to import just as a regular framework would be (by using import <framework name> at the top of your source file).

5. Conclusion

I hope this tutorial was helpful. We covered installing CocoaPods, basic terminal commands, and how to add pods to your podfile. CocoaPods is a fast, easy-to-use, and effective tool for managing your dependencies, and it is very commonly used.

And remember:

  • You'll need to access your project only through <your project>.xcworkspace and not <your project>.xcodeproj.
  • The podfile can be edited using any text editor, and can also be edited within your Xcode.
  • Run pod install from the terminal after changing your podfile so the dependencies will be removed or added.

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

2017-08-10T12:00:00.000Z2017-08-10T12:00:00.000ZVardhan Agrawal

Kotlin From Scratch: Variables, Basic Types, and Arrays

$
0
0

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

Kotlin is 100% interoperable with Java. In other words, it can be used together with Java in the same project. So you can refactor parts of your Java code to Kotlin and it won't break. In addition to that, it is concise, expressive, and has great tooling. Kotlin can be used on the back-end (server-side), but it's getting a lot of attention right now as a language for Android app development. Kotlin is now supported by Google as a first-class language for Android development, so the popularity of Kotlin is set to explode! 

In this first tutorial in the Kotlin From Scratch series, you'll learn about the language basics: comments, variables, simple types, arrays, and type inference. 

Prerequisites

To follow along with me, you will need the Kotlin plugin on Android Studio. Alternatively, you could use the online playground or IntelliJ IDEA Community Edition

1. Variables

In Kotlin, use val to declare a constant or var keywords to declare a variable. You can specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.

But you'll soon realize that in Kotlin, it's often possible to omit the type from the declaration and the compiler won't complain. 

In the code above, you'll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We'll come back to this! 

The difference between the val and var keywords is that the former is immutable or read-only (its value cannot be changed), while the latter is mutable (its value can be changed). 

Note that for a variable declared with the var keyword which has its type inferred by the compiler, assigning another value of a different type won't work. In other words, the value of the variable can change, but its type cannot! For example:

It is highly recommended that you start by making your variables immutable by declaring them with the val keyword, so as not to maintain too many states. This makes your code safer for multithreading, because it ensures your variables cannot be modified by other threads unexpectedly.

Another thing you should know about the val keyword is that you can declare it with a type only and assign it a value later. But you can still only assign a value once.

In Java, it's possible to declare multiple variables of the same type on a single line, but this doesn't work in Kotlin. In Kotlin, all variable declarations must be on their own lines. 

2. Type Inference or Deduction

Kotlin is a strongly typed language that supports type inference or deduction. This is the mechanism employed by the compiler to find out types from context. Java doesn't have a type inference mechanism, which means you must explicitly declare the type of every function or variable. Type inference helps reduce the boilerplate code you have to write. 

The code above would compile even though we did not explicitly state the type for the variable country. The compiler is smart enough to know that the country is of type String, because the value, "Nigeria", is a string.  

3. Basic Types

In Java, we have two types of type—primitive (e.g. int, long, boolean, byte, char, etc.) and reference types (e.g. array, String). Java uses wrappers (like java.lang.Integer) to make primitive types behave like objects. But in Kotlin, there is no such distinction. Instead, all types are objects. 

Numbers

The integer types available in Kotlin are:

  • Long—64 bit
  • Int—32 bit
  • Short—16 bit
  • Byte—8 bit

The floating-point types are: 

  • Double—64 bit
  • Float—32 bit

You can observe that we created a Long literal by adding the suffix L, and for Float we added the suffix F or f.  Numbers can also be written in hexadecimal notation using the 0x or 0X prefix and in binary using the 0b or 0B prefix. Note that in all these cases, Kotlin can use type inference to know the type we want instead.

To convert a number from one type to another, you have to explicitly invoke the corresponding conversion function. In other words, there is no implicit conversion between types of numbers. 

Each number type has helper functions that convert from one number type to another: toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort().

In the code above, we are converting from an integer to a long. We can also do the reverse by using the method toInt() on the long variable. Note that this will truncate the value to fit the smaller size of an Int type if need be—so be careful when converting from larger types to smaller ones! 

You can also convert a String into a number type.

In the code above, we converted the variable stringNumber into an Int type by calling the method toInt() on the variable. We can write this more succinctly by instead calling the method directly on the string:

The Boolean Type

The Boolean type in Kotlin is the same as in Java. Its value can be either true or false. The operations disjunction (||), conjunction (&&), and negation (!) can be performed on boolean types, just like Java. 

Strings

Strings can be created with either double quotes or triple quotes. In addition to that, escape characters can be used with double quotes. 

To create a string that spans multiple lines in the source file, we use triple quotes:

Kotlin also supports string interpolation or string templates. This is an easier way to build dynamic strings than concatenation, which is what we use in Java. Using string templates, we can insert variables and expressions into a string. 

In the code above, we created a string literal, and inside it, we referred to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn't exist, the code won't compile. 

What about if you need to use $ in your string? You just escape it with \$! Also, you can call methods from an interpolated String directly; you have to add curly braces ${} to wrap it. 

Another cool thing you can do is to perform some logic inside the curly braces when creating a String literal. 

Arrays

In Kotlin, there are two main ways to create an array: using the helper function arrayOf() or the constructor Array()

The arrayOf() Function

For example, let's create an array with some elements using arrayOf().  

Now, to access any of the element, we can use its index: myArray[2]. Note that we can pass in values of different types into the arrayOf() as arguments and it will still work—it will be an array of mixed type. 

To enforce that all the array values have the same type, e.g. Int, we declare a type by calling arrayOf<Int>() or intArrayOf().

We also have other utility functions to create arrays of other types such as charArrayOf()booleanArrayOf()longArrayOf()shortArrayOf()byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[], byteArrayOf() will be byte[], longArrayOf() will be long[], and so on. 

The Array() Constructor

Now let's see how to create an array with Array(). The constructor of this class requires a size and a lambda function. We'll learn more about lambda functions later in this series, but for now, just understand that it is a simple, inline way of declaring an anonymous function. In this case, the job of the lambda function is to initialize the array with elements. 

In the code above, we passed 5 as the size of the array in the first argument. The second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array. So in the example above, we created an array with elements 0, 2, 4, 6, and 8.

4. Comments

This is an easy one. In Kotlin, comments are just the same as in Java. We can use either block or line comments:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language: variables, basic types, type inference, arrays, and comments. In the next tutorial in the Kotlin From Scratch series, you'll learn about loops, ranges, conditions, collections, and packages 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 Kotlin tutorials here on Envato Tuts+.


2017-08-11T14:00:00.000Z2017-08-11T14:00:00.000ZChike Mgbemena

Kotlin From Scratch: Variables, Basic Types, and Arrays

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

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.

Kotlin is 100% interoperable with Java. In other words, it can be used together with Java in the same project. So you can refactor parts of your Java code to Kotlin and it won't break. In addition to that, it is concise, expressive, and has great tooling. Kotlin can be used on the back-end (server-side), but it's getting a lot of attention right now as a language for Android app development. Kotlin is now supported by Google as a first-class language for Android development, so the popularity of Kotlin is set to explode! 

In this first tutorial in the Kotlin From Scratch series, you'll learn about the language basics: comments, variables, simple types, arrays, and type inference. 

Prerequisites

To follow along with me, you will need the Kotlin plugin on Android Studio. Alternatively, you could use the online playground or IntelliJ IDEA Community Edition

1. Variables

In Kotlin, use val to declare a constant or var keywords to declare a variable. You can specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.

But you'll soon realize that in Kotlin, it's often possible to omit the type from the declaration and the compiler won't complain. 

In the code above, you'll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We'll come back to this! 

The difference between the val and var keywords is that the former is immutable or read-only (its value cannot be changed), while the latter is mutable (its value can be changed). 

Note that for a variable declared with the var keyword which has its type inferred by the compiler, assigning another value of a different type won't work. In other words, the value of the variable can change, but its type cannot! For example:

It is highly recommended that you start by making your variables immutable by declaring them with the val keyword, so as not to maintain too many states. This makes your code safer for multithreading, because it ensures your variables cannot be modified by other threads unexpectedly.

Another thing you should know about the val keyword is that you can declare it with a type only and assign it a value later. But you can still only assign a value once.

In Java, it's possible to declare multiple variables of the same type on a single line, but this doesn't work in Kotlin. In Kotlin, all variable declarations must be on their own lines. 

2. Type Inference or Deduction

Kotlin is a strongly typed language that supports type inference or deduction. This is the mechanism employed by the compiler to find out types from context. Java doesn't have a type inference mechanism, which means you must explicitly declare the type of every function or variable. Type inference helps reduce the boilerplate code you have to write. 

The code above would compile even though we did not explicitly state the type for the variable country. The compiler is smart enough to know that the country is of type String, because the value, "Nigeria", is a string.  

3. Basic Types

In Java, we have two types of type—primitive (e.g. int, long, boolean, byte, char, etc.) and reference types (e.g. array, String). Java uses wrappers (like java.lang.Integer) to make primitive types behave like objects. But in Kotlin, there is no such distinction. Instead, all types are objects. 

Numbers

The integer types available in Kotlin are:

  • Long—64 bit
  • Int—32 bit
  • Short—16 bit
  • Byte—8 bit

The floating-point types are: 

  • Double—64 bit
  • Float—32 bit

You can observe that we created a Long literal by adding the suffix L, and for Float we added the suffix F or f.  Numbers can also be written in hexadecimal notation using the 0x or 0X prefix and in binary using the 0b or 0B prefix. Note that in all these cases, Kotlin can use type inference to know the type we want instead.

To convert a number from one type to another, you have to explicitly invoke the corresponding conversion function. In other words, there is no implicit conversion between types of numbers. 

Each number type has helper functions that convert from one number type to another: toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort().

In the code above, we are converting from an integer to a long. We can also do the reverse by using the method toInt() on the long variable. Note that this will truncate the value to fit the smaller size of an Int type if need be—so be careful when converting from larger types to smaller ones! 

You can also convert a String into a number type.

In the code above, we converted the variable stringNumber into an Int type by calling the method toInt() on the variable. We can write this more succinctly by instead calling the method directly on the string:

The Boolean Type

The Boolean type in Kotlin is the same as in Java. Its value can be either true or false. The operations disjunction (||), conjunction (&&), and negation (!) can be performed on boolean types, just like Java. 

Strings

Strings can be created with either double quotes or triple quotes. In addition to that, escape characters can be used with double quotes. 

To create a string that spans multiple lines in the source file, we use triple quotes:

Kotlin also supports string interpolation or string templates. This is an easier way to build dynamic strings than concatenation, which is what we use in Java. Using string templates, we can insert variables and expressions into a string. 

In the code above, we created a string literal, and inside it, we referred to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn't exist, the code won't compile. 

What about if you need to use $ in your string? You just escape it with \$! Also, you can call methods from an interpolated String directly; you have to add curly braces ${} to wrap it. 

Another cool thing you can do is to perform some logic inside the curly braces when creating a String literal. 

Arrays

In Kotlin, there are two main ways to create an array: using the helper function arrayOf() or the constructor Array()

The arrayOf() Function

For example, let's create an array with some elements using arrayOf().  

Now, to access any of the element, we can use its index: myArray[2]. Note that we can pass in values of different types into the arrayOf() as arguments and it will still work—it will be an array of mixed type. 

To enforce that all the array values have the same type, e.g. Int, we declare a type by calling arrayOf<Int>() or intArrayOf().

We also have other utility functions to create arrays of other types such as charArrayOf()booleanArrayOf()longArrayOf()shortArrayOf()byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[], byteArrayOf() will be byte[], longArrayOf() will be long[], and so on. 

The Array() Constructor

Now let's see how to create an array with Array(). The constructor of this class requires a size and a lambda function. We'll learn more about lambda functions later in this series, but for now, just understand that it is a simple, inline way of declaring an anonymous function. In this case, the job of the lambda function is to initialize the array with elements. 

In the code above, we passed 5 as the size of the array in the first argument. The second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array. So in the example above, we created an array with elements 0, 2, 4, 6, and 8.

4. Comments

This is an easy one. In Kotlin, comments are just the same as in Java. We can use either block or line comments:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language: variables, basic types, type inference, arrays, and comments. In the next tutorial in the Kotlin From Scratch series, you'll learn about loops, ranges, conditions, collections, and packages 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 Kotlin tutorials here on Envato Tuts+.


2017-08-11T14:00:00.000Z2017-08-11T14:00:00.000ZChike Mgbemena

Android Architecture Components: Lifecycle and LiveModel

$
0
0

In the last part of this series, Introduction to Android Architecture Components, we talked about the new Android Architecture and why it was developed. Basically, the new architecture addresses some known Android issues by offering a bundle of components tailor-made for the system. These are the building blocks of the architecture. We've already had a quick look at these components, so now it is time to start to deep dive into them. 

In this tutorial, we'll take a close look at the Lifecycle and the LiveModel components. While we're exploring these, we're also going to check out some code snippets from a sample application. Since we're talking about Android's new paradigms, the snippets are all made with the awesome Kotlin.

If you don't know Kotlin yet, please don't be afraid to follow along; the implementation is extremely close to Java, and I'm confident that you'll be able to understand it. If you want to learn more about Kotlin, Jessica Thornsby wrote an excellent series here on Tuts+ about Coding Android Apps in Kotlin. You should take a look!

1. The Sample Project

We provided a small application demonstrating the concepts that we're talking about in this tutorial. The app's name is MyWeatherApp, and it allows the user to fetch the day's weather using a city's name or the user's current location. The app's logic is quite simple, but you could improve on it to create your own application.

Sample Application

As you can see in the diagram below, the architecture conforms to the one proposed by Android, and we used the new Architecture Components package as much as possible, keeping things simple enough for a basic analysis. As a bonus, we're using Dagger 2 as a Dependency Injection library. However, we won't dig into much detail about its implementation, since it would escape the tutorial's scope.

The WeatherApplication

How Does the App Work?

The application is as simple as possible. It has only one Activity, where the user can get the weather by searching a city's name or using the device's current location. The MainActivity calls the MainModel to get an observable LiveData and reacts to it. The MainModel fetches weather data from the MainRepository, and consolidates all data as LiveData. The MainRepository gets its data from multiple sources.

Running the Sample App

Download or clone the repository from our GitHub repo and build with Gradle or open it in your IDE. You must also create an OpenWeatherMap account and get a new application ID. Add the application ID on a string resource called openWeather.

2. Setting Up a Project

Since the Architecture Components are still in alpha, you have to include the Google repository, which contains some experimental libraries, in the project's build.gradle.

In the module build.gradle, add the following to the dependencies section to add support for LifecyclesLiveData, and ViewModel:

  • compile "android.arch.lifecycle:runtime:1.0.0-alpha5"
  • compile "android.arch.lifecycle:extensions:1.0.0-alpha5"
  • annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha5"

If you're using Kotlin, you must also add or replace the annotationProcessor with kapt, which handles annotation on Kotlin.

To enable kapt, add the following in the module's build.gradle root.

3. The Lifecycle Component

Every Android developer is familiar with the lifecycle concept. The system drives the lifecycle of Applications, Activities, Fragments, and so on, without the control of the developer. This concept is one of Android's paradigms and, until recently, it wasn't that easy to work with, since it wasn't possible to directly check for the current lifecycle status of a component. What we could do was to react to certain methods, like onCreate and onDestroy, triggered by lifecycle events.

Activity Lifecyle

This has all changed since the announcement of the Architecture Components package, which introduced a component called Lifecycle. Now, some Android objects have a Lifecycle attached to them, and this changes lots of things for the developers. It is possible to consult a Lifecycle state at any given time, and it is also possible to react to Lifecycle events using annotations. In fact, the backbone of the new Android Architecture Components is the Lifecycle component.

All elements of the package android.arch.lifecycle are important to the lifecycle concept, but two of them deserve more attention: LifecycleOwner and LifecycleObserver. They create the possibility of working with Lifecycle, observing as well as reacting to events that occur on Activities, Fragments, Services and so on.

The LifecycleOwner

The LifecycleOwner is a single method interface for classes that contain a Lifecycle. It abstracts the possession of a Lifecycle, allowing you to write components that can work with it. By the new standards, Activities and Fragments are LifecycleOwners. However, until the final version of the Architecture Components is launched, you must use some special classes: ActivityLifecycleFragmentLifecycle, and LifecycleService.

There's no significant change in the implementation of these classes when compared to the standard Activities and Fragments. Once a class extends any of them, it will have a Lifecycle attached, which can be fetched at any time with the method getLifecycle(). Another interesting possibility is that we can check the current lifecycle state with getCurrentState, which returns a Lifecycle.State

There are five different Lifecycle states:

  • INITIALIZED: for an object that has been called, but which isn't "active" yet. It is the equivalent to a state before the Activity.onCreate method.
  • CREATED: for objects that were just created. It is called after the onCreate method and also called just before the onStop method.
  • STARTED: called after the onStart and just before the onPause method.
  • RESUMED: The active state or the resumed state for a LifecycleOwner. Called after the onResume method.
  • DESTROYED: for a destroyed LifecycleOwner object. This Lifecycle won't dispatch more events. This event is reached right before the onDestroy method.
LifecycleOwner Events

The LifecycleObserver

One of the most interesting properties of the Lifecycle is that it can easily be observed.  LifecycleObserver classes can observe LifecycleOwner components, like Activities and Fragments. It receives LifecycleOwner.Events, and can react to them through the annotation @OnLifeCycleEvent( Lifecycle.Event ).

The methods annotated with @OnLifecycleEvent don't need arguments, but if used, the first argument must be the LifecycleOwner. When the annotation uses Lifecycle.Event.ON_ANY, the method should expect two arguments: LifecycleOwner and Lifecycle.Event.

To activate the @OnLifecycleEvent annotation, the LifecycleObserver must be observing a Lifecycle, otherwise it won't receive the event. To make this work, call Lifecycle.addObserver(LifecycleOwner) and the LifecycleOwner will subsequently be able to react to Lifecycle.Event. It is also possible to call Lifecycle.removeObsever(LifecycleObserver) to remove an observer.

There are various interesting use-cases for LifecycleObserver. For example, it could be used to create a Presenter layer from the Model View Presenter architecture pattern. It could also be used to create listeners that can stop listening when the Lifecycle is disabled.

4. The LiveModel Component

Designed to work together with the UI layer, the ViewModel component closes a gap that has existed in Android since the beginning: providing a way to elegantly manage and store data objects related to the view. The component maintains data integrity between configuration changes, can be shared between Activity and Fragments, and is an excellent tool to completely avoid memory leaks.

The ViewModel is always created in close relation to a specific scope, either an Activity or Fragment. The scope is retained as long as the Activity or Fragment is alive. In practical terms, the ViewModel reconnects with the view after configuration changes, maintaining itself until the main view is destroyed. According to the official documentation:

The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment.

On top of all that, the ViewModel facilitates the separation of concerns in the Android development process. By moving all the data-related operations to this component and letting it handle the logic, the application testability and maintainability is greatly increased. With ViewModel, it's possible to easily adopt the Android Architecture proposed at the 2017 Google I/O. You can even use it to adopt more sophisticated architecture patterns, like MVP or MVVM.

Implementing a ViewModel

There are two ways to implement a ViewModel. The standard one is to extend the class, providing a no-argument constructor. This is the easiest way, but it doesn't work well with Dependency Injection.

To get a ViewModel constructed with this technique from an Activity or Fragment, simply call ViewModelProviders.of(FragmentActivity).get(Class<T>). The last argument must contain the ViewModel class. The same ViewModel instance will be fetched by the view and will contain all the data for that view.

Notice that, since the ViewModel is taken from ViewModelProviders.of method, its constructor cannot receive arguments. As a workaround, you can implement a ViewModelProvider.Factory. Actually, this is the same technique we use to inject ViewModel.

Injecting a ViewModel

When using DI, things get a little trickier. You'll need to implement a ViewModelProvider.Factory. The following steps can be used to inject a ViewModel using Dagger. The ViewModelFactory is a utility class that provides a ViewModel for a scope.

Dagger also needs a @MapKey defined for ViewModel and a binder for each model and for the factory in the module.

After that, follow the standard Dagger procedures and you'll be able to create a ViewModel capable of injecting arguments on its constructor. To create a new instance, get the ViewModelFactory and take the desired ViewModel from it.

In our sample project, you can take a close look at DI using Dagger. I've also provided you with a folder of examples in the tutorial GitHub repo with snippets showing how to configure ViewModels on the Dagger system using Kotlin.

Conclusion

So far, our journey through the new Android Architecture Components has been very productive. However, we still have some ground to cover. In the next tutorial, we’ll talk about the awesome LiveData component, investigating its basic and advanced features, and applying these concepts to our sample application.

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

2017-08-14T16:00:00.000Z2017-08-14T16:00:00.000ZTin Megali

Android Architecture Components: Lifecycle and LiveModel

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

In the last part of this series, Introduction to Android Architecture Components, we talked about the new Android Architecture and why it was developed. Basically, the new architecture addresses some known Android issues by offering a bundle of components tailor-made for the system. These are the building blocks of the architecture. We've already had a quick look at these components, so now it is time to start to deep dive into them. 

In this tutorial, we'll take a close look at the Lifecycle and the LiveModel components. While we're exploring these, we're also going to check out some code snippets from a sample application. Since we're talking about Android's new paradigms, the snippets are all made with the awesome Kotlin.

If you don't know Kotlin yet, please don't be afraid to follow along; the implementation is extremely close to Java, and I'm confident that you'll be able to understand it. If you want to learn more about Kotlin, Jessica Thornsby wrote an excellent series here on Tuts+ about Coding Android Apps in Kotlin. You should take a look!

1. The Sample Project

We provided a small application demonstrating the concepts that we're talking about in this tutorial. The app's name is MyWeatherApp, and it allows the user to fetch the day's weather using a city's name or the user's current location. The app's logic is quite simple, but you could improve on it to create your own application.

Sample Application

As you can see in the diagram below, the architecture conforms to the one proposed by Android, and we used the new Architecture Components package as much as possible, keeping things simple enough for a basic analysis. As a bonus, we're using Dagger 2 as a Dependency Injection library. However, we won't dig into much detail about its implementation, since it would escape the tutorial's scope.

The WeatherApplication

How Does the App Work?

The application is as simple as possible. It has only one Activity, where the user can get the weather by searching a city's name or using the device's current location. The MainActivity calls the MainModel to get an observable LiveData and reacts to it. The MainModel fetches weather data from the MainRepository, and consolidates all data as LiveData. The MainRepository gets its data from multiple sources.

Running the Sample App

Download or clone the repository from our GitHub repo and build with Gradle or open it in your IDE. You must also create an OpenWeatherMap account and get a new application ID. Add the application ID on a string resource called openWeather.

2. Setting Up a Project

Since the Architecture Components are still in alpha, you have to include the Google repository, which contains some experimental libraries, in the project's build.gradle.

In the module build.gradle, add the following to the dependencies section to add support for LifecyclesLiveData, and ViewModel:

  • compile "android.arch.lifecycle:runtime:1.0.0-alpha5"
  • compile "android.arch.lifecycle:extensions:1.0.0-alpha5"
  • annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha5"

If you're using Kotlin, you must also add or replace the annotationProcessor with kapt, which handles annotation on Kotlin.

To enable kapt, add the following in the module's build.gradle root.

3. The Lifecycle Component

Every Android developer is familiar with the lifecycle concept. The system drives the lifecycle of Applications, Activities, Fragments, and so on, without the control of the developer. This concept is one of Android's paradigms and, until recently, it wasn't that easy to work with, since it wasn't possible to directly check for the current lifecycle status of a component. What we could do was to react to certain methods, like onCreate and onDestroy, triggered by lifecycle events.

Activity Lifecyle

This has all changed since the announcement of the Architecture Components package, which introduced a component called Lifecycle. Now, some Android objects have a Lifecycle attached to them, and this changes lots of things for the developers. It is possible to consult a Lifecycle state at any given time, and it is also possible to react to Lifecycle events using annotations. In fact, the backbone of the new Android Architecture Components is the Lifecycle component.

All elements of the package android.arch.lifecycle are important to the lifecycle concept, but two of them deserve more attention: LifecycleOwner and LifecycleObserver. They create the possibility of working with Lifecycle, observing as well as reacting to events that occur on Activities, Fragments, Services and so on.

The LifecycleOwner

The LifecycleOwner is a single method interface for classes that contain a Lifecycle. It abstracts the possession of a Lifecycle, allowing you to write components that can work with it. By the new standards, Activities and Fragments are LifecycleOwners. However, until the final version of the Architecture Components is launched, you must use some special classes: ActivityLifecycleFragmentLifecycle, and LifecycleService.

There's no significant change in the implementation of these classes when compared to the standard Activities and Fragments. Once a class extends any of them, it will have a Lifecycle attached, which can be fetched at any time with the method getLifecycle(). Another interesting possibility is that we can check the current lifecycle state with getCurrentState, which returns a Lifecycle.State

There are five different Lifecycle states:

  • INITIALIZED: for an object that has been called, but which isn't "active" yet. It is the equivalent to a state before the Activity.onCreate method.
  • CREATED: for objects that were just created. It is called after the onCreate method and also called just before the onStop method.
  • STARTED: called after the onStart and just before the onPause method.
  • RESUMED: The active state or the resumed state for a LifecycleOwner. Called after the onResume method.
  • DESTROYED: for a destroyed LifecycleOwner object. This Lifecycle won't dispatch more events. This event is reached right before the onDestroy method.
LifecycleOwner Events

The LifecycleObserver

One of the most interesting properties of the Lifecycle is that it can easily be observed.  LifecycleObserver classes can observe LifecycleOwner components, like Activities and Fragments. It receives LifecycleOwner.Events, and can react to them through the annotation @OnLifeCycleEvent( Lifecycle.Event ).

The methods annotated with @OnLifecycleEvent don't need arguments, but if used, the first argument must be the LifecycleOwner. When the annotation uses Lifecycle.Event.ON_ANY, the method should expect two arguments: LifecycleOwner and Lifecycle.Event.

To activate the @OnLifecycleEvent annotation, the LifecycleObserver must be observing a Lifecycle, otherwise it won't receive the event. To make this work, call Lifecycle.addObserver(LifecycleOwner) and the LifecycleOwner will subsequently be able to react to Lifecycle.Event. It is also possible to call Lifecycle.removeObsever(LifecycleObserver) to remove an observer.

There are various interesting use-cases for LifecycleObserver. For example, it could be used to create a Presenter layer from the Model View Presenter architecture pattern. It could also be used to create listeners that can stop listening when the Lifecycle is disabled.

4. The LiveModel Component

Designed to work together with the UI layer, the ViewModel component closes a gap that has existed in Android since the beginning: providing a way to elegantly manage and store data objects related to the view. The component maintains data integrity between configuration changes, can be shared between Activity and Fragments, and is an excellent tool to completely avoid memory leaks.

The ViewModel is always created in close relation to a specific scope, either an Activity or Fragment. The scope is retained as long as the Activity or Fragment is alive. In practical terms, the ViewModel reconnects with the view after configuration changes, maintaining itself until the main view is destroyed. According to the official documentation:

The purpose of the ViewModel is to acquire and keep the information that is necessary for an Activity or a Fragment.

On top of all that, the ViewModel facilitates the separation of concerns in the Android development process. By moving all the data-related operations to this component and letting it handle the logic, the application testability and maintainability is greatly increased. With ViewModel, it's possible to easily adopt the Android Architecture proposed at the 2017 Google I/O. You can even use it to adopt more sophisticated architecture patterns, like MVP or MVVM.

Implementing a ViewModel

There are two ways to implement a ViewModel. The standard one is to extend the class, providing a no-argument constructor. This is the easiest way, but it doesn't work well with Dependency Injection.

To get a ViewModel constructed with this technique from an Activity or Fragment, simply call ViewModelProviders.of(FragmentActivity).get(Class<T>). The last argument must contain the ViewModel class. The same ViewModel instance will be fetched by the view and will contain all the data for that view.

Notice that, since the ViewModel is taken from ViewModelProviders.of method, its constructor cannot receive arguments. As a workaround, you can implement a ViewModelProvider.Factory. Actually, this is the same technique we use to inject ViewModel.

Injecting a ViewModel

When using DI, things get a little trickier. You'll need to implement a ViewModelProvider.Factory. The following steps can be used to inject a ViewModel using Dagger. The ViewModelFactory is a utility class that provides a ViewModel for a scope.

Dagger also needs a @MapKey defined for ViewModel and a binder for each model and for the factory in the module.

After that, follow the standard Dagger procedures and you'll be able to create a ViewModel capable of injecting arguments on its constructor. To create a new instance, get the ViewModelFactory and take the desired ViewModel from it.

In our sample project, you can take a close look at DI using Dagger. I've also provided you with a folder of examples in the tutorial GitHub repo with snippets showing how to configure ViewModels on the Dagger system using Kotlin.

Conclusion

So far, our journey through the new Android Architecture Components has been very productive. However, we still have some ground to cover. In the next tutorial, we’ll talk about the awesome LiveData component, investigating its basic and advanced features, and applying these concepts to our sample application.

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

2017-08-14T16:00:00.000Z2017-08-14T16:00:00.000ZTin Megali

Kotlin From Scratch: Nullability, Loops, and Conditions

$
0
0

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

In the previous article, you learned about variables, simple types, arrays, comments and type inference in Kotlin. In this tutorial, we'll continue to learn the language by looking at nullability, loops, and conditions in Kotlin.

1. Nullability

If you're an Android coder, you must have come across the infamous NullPointerException errors in your app. These happen whenever you try to call a method or read a property of an object reference which is null. The good news is that Kotlin can help us avoid these kind of errors we get because its a null safe language. That means variables can't have the value null unless you explicitly declare their type to be nullable. In other words, by default, types cannot be null. Let's see how this feature of Kotlin can help us avoid errors in our code. 

As you can see above, if we assign null to the name variable, the compiler will complain. For the compiler to allow the assignment, declare name as a nullable by adding ? after the type.

Note that if ? is inserted after any type name, we have explicitly instructed the compiler that the value of the type can either store an object reference or can be null—it is nullable. Here we did so with the String type, it works the same with Int?, Byte?Long?, MyClass?, and so on. 

The safe call operator: ?.

Let's learn more about null-safety works in Kotlin with an operator called the safe call operator ?..

The code above won't compile because Kotlin is a null-safe language. The variable name is assigned the value null. Now, invoking the property length on that variable would trigger a NullPointerException error in Java. But the Kotlin compiler won't allow the invocation of this property because the variable could be null. The compiler won't allow us to do something that could generate a NullPointerException!

Now by adding the safe call operator ?. to the variable before invoking the property, we have explicitly instructed the compiler to invoke the property only if the value isn't null. If the value is null, the compiler will use the string "null" as the value for us. This works also for methods and not just properties. 

When you call a method of a nullable, the return type will also be nullable. So, for example the return type of the v?.length expression when v is nullable will be Int?

To bypass nullability checking by the Kotlin compiler, we can replace the ?. operator with !!.. This is not recommended though, because of the high probability for getting NullPointerException errors if used.  

The Elvis operator: ?:

This operator ?: is called the Elvis operator (because its shape looks like Elvis' head). It is used to provide an alternative value for the variable if it is null.  

Here, the compiler assigned the string "No name" to the variable name, because the first value username is null. If the first value was not null, then that value would be assigned to the variable instead.

2. Loops

Kotlin has while, do-while, and for loops. 

The while Loop

A repetition statement allows us to specify that code should repeat an action while some condition remains true.

So in Kotlin, using the while loop is same as in other languages such as Java.

As long as the condition is true, the code inside the curly braces or the loop's body will be executed. If the condition is false, then the code will not be executed. In our example above, once the fuel variable becomes less than 5 litres, the condition becomes false and then the loop terminates. In other words, driveMeAroundLagos() method execution stops. 

The do..while Loop

Kotlin also has the do..while loop construct. 

This is similar to the while statement. In the while loop, the program tests the loop condition at the beginning of the loop before executing the loop's body. If the condition is false, the body is not executed. But the do-while loop tests the condition after executing the loop's body. This means that the body is executed at least once.

The for Loop

A for loop is a repetition statement that enables us to iterate over objects while a given condition is true.

In Kotlin, the for loop construct works with iteration over ranges, collections, or other iterables (I'll explain more about these in the next post). For loops work together with the in operator, which is used to ascertain whether a value is present in a given range.

In the code above, we are iterating through a closed range 1 to 5 and print out each value in the range. 

Iterating Over an Index Array

We can use the withIndex() function or the indices property on an array to iterate over an array where we need the index for each element.

Using withIndex() Function

We can iterate over an array to access each element's index by calling the withIndex() function on the array, because the withIndex() function returns an iterable of IndexedValue type for each element. This lets us access both the index and value for each element from it.

The code above will print out the result below:

Using the indices Property

Moreover, we can use the indices property on the array. This will return just the range of valid indices for the array.

The above code will produce the same result as the previous example. You can see here also that we can use the index to access an array element, similarly to other programming languages like Java.

3. Conditions

Kotlin has three types of condition statements - the if, if..else, and when statements. 

The if Statement

An if statement runs some code if a condition is true, or simply skips it, if the condition is false. Nothing special here, if statements work similarly to the way they do in most other programming languages, including Java. 

 We can also check whether a variable is of a particular type using the is keyword. 

The if..else statement

The if..else performs one action if the condition is true and performs a different action if the condition is false.

One major feature that distinguishes the if..else statement in Kotlin from other programming languages such as Java, is the ability to assign a variable from the returned value of the  if..else statement. This is possible because an if..else statement can be used not just as a statement, but also as an expression in Kotlin.

In the code above, we assigned the result variable with a String object based on the condition of the if..else statement. Be aware that this will return only the last statement in a particular condition block and also that you can't use an if without an else as an expression. 

The when expression

Kotlin introduced the when construct as a replacement to the familiar switch statement we have in different programming languages such as C++, Java and so on. when is more concise and has more powerful features than the switch statement you might be familiar with. 

The when statement performs different actions based on the possible values of a constant of type Int, String, Byte or Short or any other object. 

In the code above, we passed the function guessTheNumber() a number parameter (we'll discuss functions in Kotlin in a later post). The when expression then checks if any of the branches match the value of number and then executes the action on that branch. If none of the branches was a match, the else branch is executed. 

Another variant of the when expression does not require any argument, like in the example below.

If we want to execute more than one action on a branch, we need to wrap the actions in curly braces {}.

Moreover, we can combine test values in a single branch.

Here the first branch is executed because we are testing for a value of either 1 or 2.

Conclusion

In this tutorial, you learned about nullability, loops, and conditions in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you'll learn about the ranges and collections API 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 Kotlin tutorials here on Envato Tuts+!

2017-08-16T12:45:38.000Z2017-08-16T12:45:38.000ZChike Mgbemena

Kotlin From Scratch: Nullability, Loops, and Conditions

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

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

In the previous article, you learned about variables, simple types, arrays, comments and type inference in Kotlin. In this tutorial, we'll continue to learn the language by looking at nullability, loops, and conditions in Kotlin.

1. Nullability

If you're an Android coder, you must have come across the infamous NullPointerException errors in your app. These happen whenever you try to call a method or read a property of an object reference which is null. The good news is that Kotlin can help us avoid these kind of errors we get because its a null safe language. That means variables can't have the value null unless you explicitly declare their type to be nullable. In other words, by default, types cannot be null. Let's see how this feature of Kotlin can help us avoid errors in our code. 

As you can see above, if we assign null to the name variable, the compiler will complain. For the compiler to allow the assignment, declare name as a nullable by adding ? after the type.

Note that if ? is inserted after any type name, we have explicitly instructed the compiler that the value of the type can either store an object reference or can be null—it is nullable. Here we did so with the String type, it works the same with Int?, Byte?Long?, MyClass?, and so on. 

The safe call operator: ?.

Let's learn more about null-safety works in Kotlin with an operator called the safe call operator ?..

The code above won't compile because Kotlin is a null-safe language. The variable name is assigned the value null. Now, invoking the property length on that variable would trigger a NullPointerException error in Java. But the Kotlin compiler won't allow the invocation of this property because the variable could be null. The compiler won't allow us to do something that could generate a NullPointerException!

Now by adding the safe call operator ?. to the variable before invoking the property, we have explicitly instructed the compiler to invoke the property only if the value isn't null. If the value is null, the compiler will use the string "null" as the value for us. This works also for methods and not just properties. 

When you call a method of a nullable, the return type will also be nullable. So, for example the return type of the v?.length expression when v is nullable will be Int?

To bypass nullability checking by the Kotlin compiler, we can replace the ?. operator with !!.. This is not recommended though, because of the high probability for getting NullPointerException errors if used.  

The Elvis operator: ?:

This operator ?: is called the Elvis operator (because its shape looks like Elvis' head). It is used to provide an alternative value for the variable if it is null.  

Here, the compiler assigned the string "No name" to the variable name, because the first value username is null. If the first value was not null, then that value would be assigned to the variable instead.

2. Loops

Kotlin has while, do-while, and for loops. 

The while Loop

A repetition statement allows us to specify that code should repeat an action while some condition remains true.

So in Kotlin, using the while loop is same as in other languages such as Java.

As long as the condition is true, the code inside the curly braces or the loop's body will be executed. If the condition is false, then the code will not be executed. In our example above, once the fuel variable becomes less than 5 litres, the condition becomes false and then the loop terminates. In other words, driveMeAroundLagos() method execution stops. 

The do..while Loop

Kotlin also has the do..while loop construct. 

This is similar to the while statement. In the while loop, the program tests the loop condition at the beginning of the loop before executing the loop's body. If the condition is false, the body is not executed. But the do-while loop tests the condition after executing the loop's body. This means that the body is executed at least once.

The for Loop

A for loop is a repetition statement that enables us to iterate over objects while a given condition is true.

In Kotlin, the for loop construct works with iteration over ranges, collections, or other iterables (I'll explain more about these in the next post). For loops work together with the in operator, which is used to ascertain whether a value is present in a given range.

In the code above, we are iterating through a closed range 1 to 5 and print out each value in the range. 

Iterating Over an Index Array

We can use the withIndex() function or the indices property on an array to iterate over an array where we need the index for each element.

Using withIndex() Function

We can iterate over an array to access each element's index by calling the withIndex() function on the array, because the withIndex() function returns an iterable of IndexedValue type for each element. This lets us access both the index and value for each element from it.

The code above will print out the result below:

Using the indices Property

Moreover, we can use the indices property on the array. This will return just the range of valid indices for the array.

The above code will produce the same result as the previous example. You can see here also that we can use the index to access an array element, similarly to other programming languages like Java.

3. Conditions

Kotlin has three types of condition statements - the if, if..else, and when statements. 

The if Statement

An if statement runs some code if a condition is true, or simply skips it, if the condition is false. Nothing special here, if statements work similarly to the way they do in most other programming languages, including Java. 

 We can also check whether a variable is of a particular type using the is keyword. 

The if..else statement

The if..else performs one action if the condition is true and performs a different action if the condition is false.

One major feature that distinguishes the if..else statement in Kotlin from other programming languages such as Java, is the ability to assign a variable from the returned value of the  if..else statement. This is possible because an if..else statement can be used not just as a statement, but also as an expression in Kotlin.

In the code above, we assigned the result variable with a String object based on the condition of the if..else statement. Be aware that this will return only the last statement in a particular condition block and also that you can't use an if without an else as an expression. 

The when expression

Kotlin introduced the when construct as a replacement to the familiar switch statement we have in different programming languages such as C++, Java and so on. when is more concise and has more powerful features than the switch statement you might be familiar with. 

The when statement performs different actions based on the possible values of a constant of type Int, String, Byte or Short or any other object. 

In the code above, we passed the function guessTheNumber() a number parameter (we'll discuss functions in Kotlin in a later post). The when expression then checks if any of the branches match the value of number and then executes the action on that branch. If none of the branches was a match, the else branch is executed. 

Another variant of the when expression does not require any argument, like in the example below.

If we want to execute more than one action on a branch, we need to wrap the actions in curly braces {}.

Moreover, we can combine test values in a single branch.

Here the first branch is executed because we are testing for a value of either 1 or 2.

Conclusion

In this tutorial, you learned about nullability, loops, and conditions in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you'll learn about the ranges and collections API 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 Kotlin tutorials here on Envato Tuts+!

2017-08-16T12:45:38.000Z2017-08-16T12:45:38.000ZChike Mgbemena
Viewing all 1836 articles
Browse latest View live