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

Google Flutter From Scratch: Grids, Lists, and Data Sources

$
0
0

Almost every non-trivial mobile app today is likely to have lists in its layouts. That's because using a scrollable list is often the most straightforward way to display a large number of similar items on a small screen. 

The Flutter framework offers several widgets you can use to efficiently, and with minimal code, create and display such lists. In this tutorial, I'll show you how to use them with both local and remote data sources.

1. Displaying a Non-Scrollable List

If you need to display a small number of similar items, and you are sure that the user's screen will be able to accommodate all of them at the same time, using the Column widget is the most efficient thing to do.

To create a list in your Flutter app, you can use the List class that the Dart programming language offers. After creating the list, you can use its add() method to add any number of items to it. The following code shows you how to create a list containing three RaisedButton widgets:

Note that each item in the list has an empty onPressed event handler associated with it because, without that, the item would be disabled.

Now that the list is ready, you can directly assign it to the children property of the Column widget to be displayed. Usually, however, you'll also want to specify where the list items should be placed on the screen. Because the Column widget is a flex widget, you can control the positions of the items along its main axis and cross axis using the mainAxisAlignment and crossAxisAlignment properties. By default, for the Column widget, the main axis is the vertical axis, and the cross axis is the horizontal axis.

The following code shows you how to stretch the three buttons across the horizontal axis and place them in the center of the screen vertically:

Here's what the column will look like now:

App displaying column with three buttons

It is important to note that you will encounter a runtime error if a Column widget is unable to accommodate all its children. For example, if you had over a dozen RaisedButton widgets in your list instead of three, you would see an error message that looks like this:

App displaying overflow error

2. Displaying a Simple Scrollable List

For slightly larger lists, lists whose contents are likely to overflow the screen, you must consider using a ListView widget because it supports scrolling.

You may have noticed that the code we wrote to create the list in the previous step was both lengthy and repetitive. Creating a larger list using the same approach can be very tedious. An easy alternative approach is to use two lists instead: one containing the data, and one containing the widgets.

Here's how you can use the [] operator to quickly create a data list, which, for now, only contains several strings:

To convert the above list of strings into a list of RaisedButton widgets, you can use the map() and toList() methods. With the map() method, you can you use each string to generate a new RaisedButton widget. And with the toList() method, you can convert the Iterable object returned by the map() method into an actual List object. The following code shows you how:

For the sake of completeness, the above code also shows you how to create an onPressed event handler that uses the canLaunch() and launch() methods offered by the url_launcher package to open the website the user selected in the default browser.

Once your list is ready, you can pass it to the children property of the ListView widget to display it.

At this point, if you run the app, you should be able to scroll through the list and press any button to launch the associated website.

App displaying a scrollable list

3. Creating a Grid

The ListView widget allows you to place only one item on its cross axis. The item will, by default, be stretched to occupy all the space available on that axis. If you want more flexibility, you should consider using a GridView widget instead, which lets you specify how many items you want on the cross axis.

The following code uses the GridView.count() constructor to create a GridView widget that displays two items per row:

Here's what the grid looks like:

App displaying a grid of buttons

4. Displaying Large Lists

For data lists that contain more than a few dozen items, you should avoid generating widget lists manually, the way you did in an earlier step. Why? Because creating a widget is an expensive operation, and large lists of widgets can consume a lot of memory.

Instead, you should use the IndexedWidgetBuilder function, which lets you generate widgets only when the user needs to see them. With it, you can lazily generate widgets as the user scrolls through your ListView widget.

It is quite unlikely that you're going to have large amounts of data defined right inside your apps. Usually, you would be fetching such data from a remote server. Therefore, to give you a realistic example, let me now show you how to fetch 100 questions from Stack Overflow using the Stack Exchange API and display them on demand.

Start by creating a subclass of the StatefulWidget class, which will act as a container for your ListView widget and override its createState() method.

The MyState class mentioned in the above code doesn't exist yet, so create it and override its build() method.

Next, add a List object as one of the member variables of the class. You'll be using it to store the questions you downloaded from Stack Overflow. Additionally, add the API's endpoint as another variable.

Unless you want your user to press a button to download the questions, I suggest you download them automatically when the widget is initializing. Accordingly, override the initState() method and make a call to a new asynchronous method called loadData().

Inside the loadData() method, you can use the get() function of Dart's http package to download the questions. The API endpoint returns a JSON document, which you can parse by using the json.decode() function available in Dart's convert package. The following code shows you how:

Once the JSON document has been converted into a Map object, you can use the value associated with its items key to initialize the questions variable. The variable, however, is a part of the widget's state. Therefore, you must make sure you update it inside the setState() method only. Here's how:

At this point you can create a new ListView widget using the ListView.builder() constructor, which expects an IndexedWidgetBuilder function and an item count as its arguments. For now, the item count is nothing but the size of the questions list. Accordingly, add the following code inside the build() method of the MyState class:

Inside the builder function, all you need to do is create a small widget tree to display various details about each question you downloaded. Flutter's material package offers a very handy widget called ListTile, which allows you to quickly create such a tree while adhering to the Material Design guidelines.

The following code shows you how to display the question's title and author, using the title and subtitle properties of the ListTile widget:

Lastly, create a new Scaffold widget, assign the ListView widget to its body property, and return it from the build() method so it can be used with a MaterialApp widget. Optionally, you can add an AppBar widget to the Scaffold widget.

Here's what the app will look like after it has downloaded the questions:

App displaying Stack Overflow data

Conclusion

You now know how to work with lists in a Flutter application. In this tutorial, you learned not only how to create lists and grids that support large data sources, but also how to make each item inside them interactive. To learn more about lists in Flutter, you can refer to the official documentation.

2018-08-10T02:00:29.684Z2018-08-10T02:00:29.684ZAshraff Hathibelagal

Google Flutter From Scratch: Grids, Lists, and Data Sources

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

Almost every non-trivial mobile app today is likely to have lists in its layouts. That's because using a scrollable list is often the most straightforward way to display a large number of similar items on a small screen. 

The Flutter framework offers several widgets you can use to efficiently, and with minimal code, create and display such lists. In this tutorial, I'll show you how to use them with both local and remote data sources.

1. Displaying a Non-Scrollable List

If you need to display a small number of similar items, and you are sure that the user's screen will be able to accommodate all of them at the same time, using the Column widget is the most efficient thing to do.

To create a list in your Flutter app, you can use the List class that the Dart programming language offers. After creating the list, you can use its add() method to add any number of items to it. The following code shows you how to create a list containing three RaisedButton widgets:

Note that each item in the list has an empty onPressed event handler associated with it because, without that, the item would be disabled.

Now that the list is ready, you can directly assign it to the children property of the Column widget to be displayed. Usually, however, you'll also want to specify where the list items should be placed on the screen. Because the Column widget is a flex widget, you can control the positions of the items along its main axis and cross axis using the mainAxisAlignment and crossAxisAlignment properties. By default, for the Column widget, the main axis is the vertical axis, and the cross axis is the horizontal axis.

The following code shows you how to stretch the three buttons across the horizontal axis and place them in the center of the screen vertically:

Here's what the column will look like now:

App displaying column with three buttons

It is important to note that you will encounter a runtime error if a Column widget is unable to accommodate all its children. For example, if you had over a dozen RaisedButton widgets in your list instead of three, you would see an error message that looks like this:

App displaying overflow error

2. Displaying a Simple Scrollable List

For slightly larger lists, lists whose contents are likely to overflow the screen, you must consider using a ListView widget because it supports scrolling.

You may have noticed that the code we wrote to create the list in the previous step was both lengthy and repetitive. Creating a larger list using the same approach can be very tedious. An easy alternative approach is to use two lists instead: one containing the data, and one containing the widgets.

Here's how you can use the [] operator to quickly create a data list, which, for now, only contains several strings:

To convert the above list of strings into a list of RaisedButton widgets, you can use the map() and toList() methods. With the map() method, you can you use each string to generate a new RaisedButton widget. And with the toList() method, you can convert the Iterable object returned by the map() method into an actual List object. The following code shows you how:

For the sake of completeness, the above code also shows you how to create an onPressed event handler that uses the canLaunch() and launch() methods offered by the url_launcher package to open the website the user selected in the default browser.

Once your list is ready, you can pass it to the children property of the ListView widget to display it.

At this point, if you run the app, you should be able to scroll through the list and press any button to launch the associated website.

App displaying a scrollable list

3. Creating a Grid

The ListView widget allows you to place only one item on its cross axis. The item will, by default, be stretched to occupy all the space available on that axis. If you want more flexibility, you should consider using a GridView widget instead, which lets you specify how many items you want on the cross axis.

The following code uses the GridView.count() constructor to create a GridView widget that displays two items per row:

Here's what the grid looks like:

App displaying a grid of buttons

4. Displaying Large Lists

For data lists that contain more than a few dozen items, you should avoid generating widget lists manually, the way you did in an earlier step. Why? Because creating a widget is an expensive operation, and large lists of widgets can consume a lot of memory.

Instead, you should use the IndexedWidgetBuilder function, which lets you generate widgets only when the user needs to see them. With it, you can lazily generate widgets as the user scrolls through your ListView widget.

It is quite unlikely that you're going to have large amounts of data defined right inside your apps. Usually, you would be fetching such data from a remote server. Therefore, to give you a realistic example, let me now show you how to fetch 100 questions from Stack Overflow using the Stack Exchange API and display them on demand.

Start by creating a subclass of the StatefulWidget class, which will act as a container for your ListView widget and override its createState() method.

The MyState class mentioned in the above code doesn't exist yet, so create it and override its build() method.

Next, add a List object as one of the member variables of the class. You'll be using it to store the questions you downloaded from Stack Overflow. Additionally, add the API's endpoint as another variable.

Unless you want your user to press a button to download the questions, I suggest you download them automatically when the widget is initializing. Accordingly, override the initState() method and make a call to a new asynchronous method called loadData().

Inside the loadData() method, you can use the get() function of Dart's http package to download the questions. The API endpoint returns a JSON document, which you can parse by using the json.decode() function available in Dart's convert package. The following code shows you how:

Once the JSON document has been converted into a Map object, you can use the value associated with its items key to initialize the questions variable. The variable, however, is a part of the widget's state. Therefore, you must make sure you update it inside the setState() method only. Here's how:

At this point you can create a new ListView widget using the ListView.builder() constructor, which expects an IndexedWidgetBuilder function and an item count as its arguments. For now, the item count is nothing but the size of the questions list. Accordingly, add the following code inside the build() method of the MyState class:

Inside the builder function, all you need to do is create a small widget tree to display various details about each question you downloaded. Flutter's material package offers a very handy widget called ListTile, which allows you to quickly create such a tree while adhering to the Material Design guidelines.

The following code shows you how to display the question's title and author, using the title and subtitle properties of the ListTile widget:

Lastly, create a new Scaffold widget, assign the ListView widget to its body property, and return it from the build() method so it can be used with a MaterialApp widget. Optionally, you can add an AppBar widget to the Scaffold widget.

Here's what the app will look like after it has downloaded the questions:

App displaying Stack Overflow data

Conclusion

You now know how to work with lists in a Flutter application. In this tutorial, you learned not only how to create lists and grids that support large data sources, but also how to make each item inside them interactive. To learn more about lists in Flutter, you can refer to the official documentation.

2018-08-10T02:00:29.684Z2018-08-10T02:00:29.684ZAshraff Hathibelagal

How to Code With Swift on the Server

$
0
0
Final product image
What You'll Be Creating

Since Apple first introduced Swift as the successor to Objective-C, it has revolutionized how the community codes iOS, macOS, watchOS and tvOS apps. When Swift became an open-source platform, it opened new possibilities for the language beyond mobile and client-side apps—Swift became a server language too! In this tutorial, you'll learn what server-side Swift is and why you would want to have Swift on your back-end. 

The server-side Swift initiative is being pushed by three prominent projects—Vapor by QutheoryIBM’s Kitura, and Perfect—with the goal of letting Swift developers create fully fledged back-end services. This, in essence, will transform such developers into full-stack developers, negating the need for reliance on Node or PHP or giving control to a BaaS platform such as Google’s Firebase. 

Objectives of This Article 

In this article, you will learn all about server-side Swift. First I'll explain how server-side Swift works, and then I'll show you how to get started with the Kitura, Vapor, and Perfect frameworks.

What Is Server-Side Swift?

Swift was first announced by Apple in 2014 and quickly became one of the fastest-growing programming languages. Swift draws from many of the best contemporary languages, such as Python, allowing elegance and ease of use. It frees engineers from the technical shackles of Objective-C, allowing more fluid and intuitive work. 

In December 2015, Apple made another monumental announcement and made the Swift language—along with its supporting libraries, debugger, and package manager—an open-source project under the Apache 2.0 license, opening up the platform for the public to create pull requests and contribute. The shift away from Objective-C has not only enticed the many Objective-C developers contributing to the App Store, but it has made it easier for developers of all skills and backgrounds to enter the Apple ecosystem with Swift. 

However, while Apple’s development tools have historically made it easier for developers to create visually compelling and engaging apps for the App Store, one notable bottleneck has been that projects still needed specialized back-end developers to create complex data-driven applications. So iOS and macOS developers would either need to engage the assistance of a Python, PHP or Node developer to create their back-end database or pick up the skill themselves, resulting in a significantly heavier workload to complete their project objectives. 

Although back-end-as-a-service (BaaS) has come to the rescue of iOS developers, with no-code back-end solutions such as Google’s Firebase and Apple’s very own CloudKit which alleviate the complexities of the back-end, many teams and projects demand more. This is where server-side Swift comes in, allowing you to create a fully fledged multi-threaded back-end server that is open-sourced and infinitely configurable. 

Server-side Swift lets you choose how you host your back-end server, whether with AWS, RackSpace, or your own physical servers. You can also choose how to load balance your servers (e.g. via popular server solutions such as NGINX) and how to persist your data in a database (be it NoSQL solutions such as MongoDB, or traditional databases such as Postgres, MySQL, or Oracle). Not only that, but you are never tied to one component solution—you can switch up without affecting your entire app codebase. 

The point is that by opting for an open-source server-side Swift solution such as Vapor by QutheoryIBM’s Kitura, or Perfect, you take advantage of a vast array of plugins that allow you to configure your back end just the way you want it, making use of your existing team’s skill set in Swift to do so. 

Server-side Swift certainly sounds compelling, but which framework is right for you? Next we take a look at each one in turn, starting with Kitura.

Getting Started With Kitura

Overview 

Starting with Kitura, you have a platform that was initially released in February 2016 and gained prominence later that year at Apple’s WWDC, representing IBM’s foray into supporting server-side web with Swift, which was then set to transition from Apple’s hands to open source. 

Generally speaking, Kitura is focused on convention over configuration: it builds your initial project out with stubs, before you opt for the specific frameworks and libraries you are looking to build. Kitura’s authentication mechanism is supported by its very own Kitura-Credentials middleware framework, allowing you to choose from a smorgasbord of authentication mechanisms, from the traditional username/password to social-media login and federated authentication, using OpenID which handles JSON Web Tokens (JWT).

Kitura’s database ORM solution is powered by Kuery to obfuscate the complexities of dealing with SQL directly, supporting common relational databases such as MySQL, SQLite and PostgreSQL natively, as well as other database solutions, including NoSQL databases, through the various other compatible plugins. 

Kitura also provides other useful plugins for things such as HTML templating, using popular plugins such as Stencil and Markdown. Coming from IBM, the server-side framework also benefits from intimate connectivity with IBM Watson APIs as well as providing native macOS support for integrating directly into their Bluemix cloud platform. This provides an additional option at your disposal, along with your other traditional deployment options across Linux/Unix and macOS servers. 

While the platform certainly does provide a unique set of features—from Kuery to the ability to integrate with the various IBM API libraries—it doesn’t have the community clout that Vapor has. Adopting Kitura requires appreciating and embracing its own non-conventional ways of doing things, from how Kuery operates to its authentication mechanisms. However, given that it is backed by a large company with a focus on the enterprise, there are some future-proofing assurances built in. 

Kitura documentation page

Installing and Running Kitura

The quickest way to get started is by using Kitura’s command-line interface (CLI), supported on both macOS and Linux. Using the popular package management utility Homebrew, install Kitura and Kitura CLI by entering the following:

Within an empty folder that you will use as your project, run the following to initialize your project:

When it's done generating your skeleton application, you will notice a new project called HelloKitura.xcodeproject. You can learn more about project generation by referring to Kitura’s official documentation. You can open the newly generated project in Xcode and edit the primary application class, Application.swift, to handle all calls to your server’s root http://localhost:8080/ URL:

The code snippet above responds by returning the classic Hello, World!. Before you can finally run the project, change your Xcode scheme to point to HelloKitura (your active project), and kick off your project by pressing Command-R. While your server is running, in a browser of your choice, go to http://localhost:8080 and you should see the hello world text in your browser. 

Further Information

Check out the following links for more information about Kitura.

Getting Started With Vapor

Overview 

Released a few months later than Kitura, in September 2016, Vapor by Qutheory is widely considered the most popular in terms of community size and number of plugins. It's built on top of Apple’s Swift-nio framework, making it a true performance powerhouse. Unlike Kitura and other platforms, which aren’t built purely in Swift but rather on Node.js or other intermediary parsers, Vapor decouples itself from any of those dependencies to deliver a Swift parser and provide clear and readable APIs.

Vapor documentation page

Vapor provides comprehensive support of databases for SQL vendors such as MySQL and PostgreSQL, as well as NoSQL vendors such as Redis and MongoDB, like Kitura. Whereas Kitura has its own Kuery ORM solution, Vapor leverages Fluent ORM to support the databases I just mentioned, making it relatively easy to extend the ORM to other third-party database providers. Vapor separates itself from the other frameworks in natively supporting Apple’s Push Notification Service, as well as supporting SMTP for pushing email notifications. 

Whereas Kitura implements its own authentication framework, Vapor has Stormpath’s Turnstile authentication library baked in natively. Like Kitura, the platform also supports the Mustache and Markdown templates, as well as its own Swift-native expressive templating language, Leaf. Vapor also comes with its own CLI engine like the other server-side Swift frameworks, with the ability to extend the application command-line arguments with custom flags. 

Installing and Running

To get started with Vapor, you start by installing the Vapor toolbox, which consists of all the library dependencies and the CLI toolkit. Install it with Homebrew by entering the following in the terminal:

When installation has completed, you can confirm Vapor has installed successfully by typing vapor —help. To create a project, type in the following, substituting with your own project name:

The Vapor engine will build a folder structure resembling the following:

To actually create an Xcode project, you will also need to explicitly enter the following command, from within the project folder: 

Finally, to build and run your project, from Xcode select the Run scheme as well as the deployment target device of My Mac, and then press the Run button as you would do for any other Xcode project. Provided your Xcode project doesn’t encounter any errors, you should see the following confirmation message in the terminal:

Go ahead and enter that URL in your browser of choice, and you should see your application running. 

Further Information

Check out the following links for more information.

Getting Started With Perfect

Overview

Finally, we take a look at Perfect by PerfectlySoft, a feature-rich server-side platform like Vapor and Kitura. Perfect includes the same standard bells and whistles you would find on the previous vendors, from templating with Mustache or Markdown to networking with web sockets, as well as Apple Push Notification and SMTP.

Perfect documentation page

Like the other server-side platforms, Perfect has its own ORM implementation, the StORM platform (Perfect StORM), which provides native support for MySQL, PostgreSQL and other prominent relational databases, as well as MongoDB, Redis, and other NoSQL solutions. One notable omission from Perfect is a CLI, but the framework makes up for this with a native macOS app.

Like Vapor, Perfect also has Turnstile baked in to power its authentication mechanism, extended to interact with StORM more intimately. Another distinction that this solution has over the others is in many of the native utility libraries it supports, including their very own cURL wrapper as well as tools for working with files and folders. Perfect’s developer base is the second largest, almost on par with Vapor's, meaning you have a strong community to back this platform, along with a rich set of educational resources to give you confidence if you choose it.

Installing and Running

Getting up and running with Perfect is really straightforward. First, clone the PerfectlySoft repo, by entering the following:

From within the cloned folder, build the project:

Finally, run the project, which will run a local server on address 0.0.0.0:8181:

You can also run your project on Xcode by first generating a new project, as follows:

Within Xcode, ensure your executable target is pointed at My Mac, before building and running the project.

Further Information 

Check out the following links for more information about the Perfect framework.

Conclusion 

The release of Swift to the open-source community has instigated a push for Swift solutions beyond client apps, with back-end server frameworks becoming the next frontier. Pushed by three prominent projects—Vapor by QutheoryIBM’s Kitura, and Perfect—server-side Swift has enabled iOS (and macOS) engineers to become full-stack developers. This can negate the dependence on Node.js, PHP or .NET back-end engineers. Server-side Swift also gives teams the ability to control their back-end without having to rely on mobile back-end-as-a-service solutions like Firebase or CloudKit.

Server-side Swift isn’t for everyone: you have to decide on how much control you need for your back-end, and whether it does make sense for you to roll your own. Also, I didn't try to tell you which server-side Swift solution is best. Developers are certainly spoiled for choice, and all three provide a unique and mature take and are worth experimenting with. I would encourage you to play around with each of the sample codes, evaluate the syntax, and engage with their respective communities to see which solution fits you best.

2018-08-13T12:31:19.000Z2018-08-13T12:31:19.000ZDoron Katz

How to Code With Swift on the Server

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-31608
Final product image
What You'll Be Creating

Since Apple first introduced Swift as the successor to Objective-C, it has revolutionized how the community codes iOS, macOS, watchOS and tvOS apps. When Swift became an open-source platform, it opened new possibilities for the language beyond mobile and client-side apps—Swift became a server language too! In this tutorial, you'll learn what server-side Swift is and why you would want to have Swift on your back-end. 

The server-side Swift initiative is being pushed by three prominent projects—Vapor by QutheoryIBM’s Kitura, and Perfect—with the goal of letting Swift developers create fully fledged back-end services. This, in essence, will transform such developers into full-stack developers, negating the need for reliance on Node or PHP or giving control to a BaaS platform such as Google’s Firebase. 

Objectives of This Article 

In this article, you will learn all about server-side Swift. First I'll explain how server-side Swift works, and then I'll show you how to get started with the Kitura, Vapor, and Perfect frameworks.

What Is Server-Side Swift?

Swift was first announced by Apple in 2014 and quickly became one of the fastest-growing programming languages. Swift draws from many of the best contemporary languages, such as Python, allowing elegance and ease of use. It frees engineers from the technical shackles of Objective-C, allowing more fluid and intuitive work. 

In December 2015, Apple made another monumental announcement and made the Swift language—along with its supporting libraries, debugger, and package manager—an open-source project under the Apache 2.0 license, opening up the platform for the public to create pull requests and contribute. The shift away from Objective-C has not only enticed the many Objective-C developers contributing to the App Store, but it has made it easier for developers of all skills and backgrounds to enter the Apple ecosystem with Swift. 

However, while Apple’s development tools have historically made it easier for developers to create visually compelling and engaging apps for the App Store, one notable bottleneck has been that projects still needed specialized back-end developers to create complex data-driven applications. So iOS and macOS developers would either need to engage the assistance of a Python, PHP or Node developer to create their back-end database or pick up the skill themselves, resulting in a significantly heavier workload to complete their project objectives. 

Although back-end-as-a-service (BaaS) has come to the rescue of iOS developers, with no-code back-end solutions such as Google’s Firebase and Apple’s very own CloudKit which alleviate the complexities of the back-end, many teams and projects demand more. This is where server-side Swift comes in, allowing you to create a fully fledged multi-threaded back-end server that is open-sourced and infinitely configurable. 

Server-side Swift lets you choose how you host your back-end server, whether with AWS, RackSpace, or your own physical servers. You can also choose how to load balance your servers (e.g. via popular server solutions such as NGINX) and how to persist your data in a database (be it NoSQL solutions such as MongoDB, or traditional databases such as Postgres, MySQL, or Oracle). Not only that, but you are never tied to one component solution—you can switch up without affecting your entire app codebase. 

The point is that by opting for an open-source server-side Swift solution such as Vapor by QutheoryIBM’s Kitura, or Perfect, you take advantage of a vast array of plugins that allow you to configure your back end just the way you want it, making use of your existing team’s skill set in Swift to do so. 

Server-side Swift certainly sounds compelling, but which framework is right for you? Next we take a look at each one in turn, starting with Kitura.

Getting Started With Kitura

Overview 

Starting with Kitura, you have a platform that was initially released in February 2016 and gained prominence later that year at Apple’s WWDC, representing IBM’s foray into supporting server-side web with Swift, which was then set to transition from Apple’s hands to open source. 

Generally speaking, Kitura is focused on convention over configuration: it builds your initial project out with stubs, before you opt for the specific frameworks and libraries you are looking to build. Kitura’s authentication mechanism is supported by its very own Kitura-Credentials middleware framework, allowing you to choose from a smorgasbord of authentication mechanisms, from the traditional username/password to social-media login and federated authentication, using OpenID which handles JSON Web Tokens (JWT).

Kitura’s database ORM solution is powered by Kuery to obfuscate the complexities of dealing with SQL directly, supporting common relational databases such as MySQL, SQLite and PostgreSQL natively, as well as other database solutions, including NoSQL databases, through the various other compatible plugins. 

Kitura also provides other useful plugins for things such as HTML templating, using popular plugins such as Stencil and Markdown. Coming from IBM, the server-side framework also benefits from intimate connectivity with IBM Watson APIs as well as providing native macOS support for integrating directly into their Bluemix cloud platform. This provides an additional option at your disposal, along with your other traditional deployment options across Linux/Unix and macOS servers. 

While the platform certainly does provide a unique set of features—from Kuery to the ability to integrate with the various IBM API libraries—it doesn’t have the community clout that Vapor has. Adopting Kitura requires appreciating and embracing its own non-conventional ways of doing things, from how Kuery operates to its authentication mechanisms. However, given that it is backed by a large company with a focus on the enterprise, there are some future-proofing assurances built in. 

Kitura documentation page

Installing and Running Kitura

The quickest way to get started is by using Kitura’s command-line interface (CLI), supported on both macOS and Linux. Using the popular package management utility Homebrew, install Kitura and Kitura CLI by entering the following:

Within an empty folder that you will use as your project, run the following to initialize your project:

When it's done generating your skeleton application, you will notice a new project called HelloKitura.xcodeproject. You can learn more about project generation by referring to Kitura’s official documentation. You can open the newly generated project in Xcode and edit the primary application class, Application.swift, to handle all calls to your server’s root http://localhost:8080/ URL:

The code snippet above responds by returning the classic Hello, World!. Before you can finally run the project, change your Xcode scheme to point to HelloKitura (your active project), and kick off your project by pressing Command-R. While your server is running, in a browser of your choice, go to http://localhost:8080 and you should see the hello world text in your browser. 

Further Information

Check out the following links for more information about Kitura.

Getting Started With Vapor

Overview 

Released a few months later than Kitura, in September 2016, Vapor by Qutheory is widely considered the most popular in terms of community size and number of plugins. It's built on top of Apple’s Swift-nio framework, making it a true performance powerhouse. Unlike Kitura and other platforms, which aren’t built purely in Swift but rather on Node.js or other intermediary parsers, Vapor decouples itself from any of those dependencies to deliver a Swift parser and provide clear and readable APIs.

Vapor documentation page

Vapor provides comprehensive support of databases for SQL vendors such as MySQL and PostgreSQL, as well as NoSQL vendors such as Redis and MongoDB, like Kitura. Whereas Kitura has its own Kuery ORM solution, Vapor leverages Fluent ORM to support the databases I just mentioned, making it relatively easy to extend the ORM to other third-party database providers. Vapor separates itself from the other frameworks in natively supporting Apple’s Push Notification Service, as well as supporting SMTP for pushing email notifications. 

Whereas Kitura implements its own authentication framework, Vapor has Stormpath’s Turnstile authentication library baked in natively. Like Kitura, the platform also supports the Mustache and Markdown templates, as well as its own Swift-native expressive templating language, Leaf. Vapor also comes with its own CLI engine like the other server-side Swift frameworks, with the ability to extend the application command-line arguments with custom flags. 

Installing and Running

To get started with Vapor, you start by installing the Vapor toolbox, which consists of all the library dependencies and the CLI toolkit. Install it with Homebrew by entering the following in the terminal:

When installation has completed, you can confirm Vapor has installed successfully by typing vapor —help. To create a project, type in the following, substituting with your own project name:

The Vapor engine will build a folder structure resembling the following:

To actually create an Xcode project, you will also need to explicitly enter the following command, from within the project folder: 

Finally, to build and run your project, from Xcode select the Run scheme as well as the deployment target device of My Mac, and then press the Run button as you would do for any other Xcode project. Provided your Xcode project doesn’t encounter any errors, you should see the following confirmation message in the terminal:

Go ahead and enter that URL in your browser of choice, and you should see your application running. 

Further Information

Check out the following links for more information.

Getting Started With Perfect

Overview

Finally, we take a look at Perfect by PerfectlySoft, a feature-rich server-side platform like Vapor and Kitura. Perfect includes the same standard bells and whistles you would find on the previous vendors, from templating with Mustache or Markdown to networking with web sockets, as well as Apple Push Notification and SMTP.

Perfect documentation page

Like the other server-side platforms, Perfect has its own ORM implementation, the StORM platform (Perfect StORM), which provides native support for MySQL, PostgreSQL and other prominent relational databases, as well as MongoDB, Redis, and other NoSQL solutions. One notable omission from Perfect is a CLI, but the framework makes up for this with a native macOS app.

Like Vapor, Perfect also has Turnstile baked in to power its authentication mechanism, extended to interact with StORM more intimately. Another distinction that this solution has over the others is in many of the native utility libraries it supports, including their very own cURL wrapper as well as tools for working with files and folders. Perfect’s developer base is the second largest, almost on par with Vapor's, meaning you have a strong community to back this platform, along with a rich set of educational resources to give you confidence if you choose it.

Installing and Running

Getting up and running with Perfect is really straightforward. First, clone the PerfectlySoft repo, by entering the following:

From within the cloned folder, build the project:

Finally, run the project, which will run a local server on address 0.0.0.0:8181:

You can also run your project on Xcode by first generating a new project, as follows:

Within Xcode, ensure your executable target is pointed at My Mac, before building and running the project.

Further Information 

Check out the following links for more information about the Perfect framework.

Conclusion 

The release of Swift to the open-source community has instigated a push for Swift solutions beyond client apps, with back-end server frameworks becoming the next frontier. Pushed by three prominent projects—Vapor by QutheoryIBM’s Kitura, and Perfect—server-side Swift has enabled iOS (and macOS) engineers to become full-stack developers. This can negate the dependence on Node.js, PHP or .NET back-end engineers. Server-side Swift also gives teams the ability to control their back-end without having to rely on mobile back-end-as-a-service solutions like Firebase or CloudKit.

Server-side Swift isn’t for everyone: you have to decide on how much control you need for your back-end, and whether it does make sense for you to roll your own. Also, I didn't try to tell you which server-side Swift solution is best. Developers are certainly spoiled for choice, and all three provide a unique and mature take and are worth experimenting with. I would encourage you to play around with each of the sample codes, evaluate the syntax, and engage with their respective communities to see which solution fits you best.

2018-08-13T12:31:19.000Z2018-08-13T12:31:19.000ZDoron Katz

10 Best Android News App Templates

$
0
0

The best news app templates organise news into a few broad categories, allow users to save news stories they want to read later in a favourites list, and have a powerful search feature that helps them find relevant news stories quickly and easily. 

Whether you’re interested in building a news app from posts on your own website, creating an app for a localised news source, or pulling together all major news sources into one handy app, you’re sure to find a template that’s right for you from among these ten best Android news app templates available at CodeCanyon

1. Android News App

Developed using Android Studio and Google Material Design, Android News App provides developers with an easy to configure template.

Content can be managed from the PHP MySQL admin panel where you can change admin username and password, profile information, organise news categories and news items etc.

Android News App

User Naradasi says:

"Documentation for the code is so clear that anyone without coding knowledge can use it. Response from the author is also very quick. Worth the money.”

2. News Application

The News Application template makes it super easy for you to create your own news app. The template features a beautiful UI created with Material Design. It supports both landscape and portrait mode, gives users the ability to add unlimited categories. It also offers push notifications, powerful search, and the ability to share news stories via social media.

News Application

User Tlosos says:

This app is just brilliant, easy to configure and great to arrange your news. Also, the support team is great.”

3. Ultimate News App

Breaking news headlines, modifiable categories, deep link sharing, powerful search, Facebook comments, Admob Ads, push notifications, video and image support are just a few of the great features to be found in the Ultimate News App template. 

The template also comes with two separate video tutorials and online documentation  to help you set up the admin page and customise the app.

Ultimate News App

User aidyMatic says:

"Works as expected. Easy to setup, quick response from author. VERY HAPPY!”

4. YouNews

YouNews app template is ideal for those looking to create their own news app to keep followers, clients and/or customers updated with news about their business. Administrators of the app can easily add and edit news items via the dashboard, and their additions and changes will be displayed right away in the app.

YouNews

User WeecomCA says:

“Amazing app with a great support! Very easy to customise the app with your colours and brand.”

5. PSNews

PSNews allows developers to build their Android news app in just a few hours. Like the other news app templates here, news stories are organised in categories, but PSNews also adds an editor’s pick category as well as trending and recent news categories.

The template also offers YouTube integration, Admob banner support, a powerful search function which allows end users to find stories quickly and easily, as well as the usual push notifications and the ability to share news stories on social media. 

PSNews

User hayasuliman says:

“All things is great: Support, App, Design! Everything!”

6. News App for WordPress Site

News App for WordPress Site  is ideal for those who already have a news rich WordPress blog that they want to turn into a news app. The template is quite different from the other app templates featured here because instead of drawing news from various sources, it allows users to turn their WordPress website into a news feed just by inserting their website URL into the template. News stories can be organised by category just like with other news app templates, and the app is AdMob ready.

News App for WordPress Site

User carmentv says:

“Excellent app template for WordPress site. Excellent documentation and customer support. Very easy to set up and send push notifications. Great for small news sites and can be easily used for any small business to have a competitive edge against big companies.”

7. All-In-One News

The All-In-One News app template offers developers a beautifully designed app that allows users to get all their news, including live TV, videos and photo, weather and top stories in one place. Like the other apps features here, users can login with their social media accounts, filter news based on the categories they prefer, share and comment on news items, etc. 

All-In-One News

User codebini says:

“It’s great news app!"

8. News App Pro

News App Pro is another template that is perfect for those looking to create their own news app to keep followers, fans, customers and clients updated with news about their activities or business. The PHP and MySQL database allows app administrators to easily add and edit articles, videos, notifications, etc. 

News App Pro

User umang656 says:

“One of the best news app templates available in CodeCanyon. Easy to use and with powerful and proper coding. Loved This Product.”

9. New News Android App

New News Android App is a simple and easy-to-use app template that helps developers create a news reader app quickly. The admin panel contains a category manager,  news manager, user manager, notification manager, and various other settings. The app features a dynamic drawer menus system for organising news categories, dynamic search, multi-language support and more. 

 New News Android App

User rajivvaishnav says:

“I got excellent and prompt support from the seller. I would highly recommend him. The app was totally awesome. I didn’t have any issue opening up in Android Studio and without making a single change, I was able to run the application.”

10. My News

My News  is a multipurpose Android app template that can be used as news resource, a personal blog, or portfolio. My News offers Facebook sign up and login, categories for organising news stories, push notifications, AdMob banners and a full-featured admin panel which allows the app’s admin to manage user accounts.

My News

User forgive says:

“Good features, good app.”

Conclusion

These top Android news app templates are just a small selection of the news app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-08-13T18:59:47.520Z2018-08-13T18:59:47.520ZNona Blackman

10 Best Android News App Templates

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

The best news app templates organise news into a few broad categories, allow users to save news stories they want to read later in a favourites list, and have a powerful search feature that helps them find relevant news stories quickly and easily. 

Whether you’re interested in building a news app from posts on your own website, creating an app for a localised news source, or pulling together all major news sources into one handy app, you’re sure to find a template that’s right for you from among these ten best Android news app templates available at CodeCanyon

1. Android News App

Developed using Android Studio and Google Material Design, Android News App provides developers with an easy-to-configure template.

Content can be managed from the PHP MySQL admin panel, where you can change the admin username and password, profile information, organise news categories, news items, etc.

Android News App

User Naradasi says:

"Documentation for the code is so clear that anyone without coding knowledge can use it. Response from the author is also very quick. Worth the money.”

2. News Application

The News Application template makes it super easy for you to create your own news app. The template features a beautiful UI created with Material Design. It supports both landscape and portrait mode, and it gives users the ability to add unlimited categories. It also offers push notifications, powerful search, and the ability to share news stories via social media.

News Application

User Tlosos says:

"This app is just brilliant, easy to configure and great to arrange your news. Also, the support team is great.”

3. Ultimate News App

Breaking news headlines, modifiable categories, deep link sharing, powerful search, Facebook comments, AdMob ads, push notifications, video and image support are just a few of the great features to be found in the Ultimate News App template. 

The template also comes with two separate video tutorials and online documentation to help you set up the admin page and customise the app.

Ultimate News App

User aidyMatic says:

"Works as expected. Easy to setup, quick response from author. VERY HAPPY!”

4. YouNews

YouNews app template is ideal for those looking to create their own news app to keep followers, clients and/or customers updated with news about their business. Administrators of the app can easily add and edit news items via the dashboard, and their additions and changes will be displayed right away in the app.

YouNews

User WeecomCA says:

“Amazing app with a great support! Very easy to customise the app with your colours and brand.”

5. PSNews

PSNews allows developers to build their Android news app in just a few hours. Like the other news app templates here, PSNews organises the news stories in categories, and it also adds an editor’s pick category as well as trending and recent news categories.

The template also offers YouTube integration, AdMob banner support, and a powerful search function which allows end users to find stories quickly and easily, as well as the usual push notifications and the ability to share news stories on social media. 

PSNews

User hayasuliman says:

“All things is great: Support, App, Design! Everything!”

6. News App for WordPress Site

News App for WordPress Site is ideal for those who already have a news-rich WordPress blog that they want to turn into a news app. The template is quite different from the other app templates featured here because instead of drawing news from various sources, it allows users to turn their WordPress website into a news feed just by inserting their website URL into the template. News stories can be organised by category just like with other news app templates, and the app is AdMob ready.

News App for WordPress Site

User carmentv says:

“Excellent app template for WordPress site. Excellent documentation and customer support. Very easy to set up and send push notifications. Great for small news sites and can be easily used for any small business to have a competitive edge against big companies.”

7. All-In-One News

The All-In-One News app template offers developers a beautifully designed app that allows users to get all their news, including live TV, videos and photo, weather and top stories in one place. As with the other apps features here, users can log in with their social media accounts, filter news based on the categories they prefer, share and comment on news items, etc. 

All-In-One News

User codebini says:

“It’s great news app!"

8. News App Pro

News App Pro is another template that is perfect for those looking to create their own news app to keep followers, fans, customers and clients updated with news about their activities or business. The PHP and MySQL database allows app administrators to easily add and edit articles, videos, notifications, etc. 

News App Pro

User umang656 says:

“One of the best news app templates available in CodeCanyon. Easy to use and with powerful and proper coding. Loved This Product.”

9. New News Android App

New News Android App is a simple and easy-to-use app template that helps developers create a news reader app quickly. The admin panel contains a category manager, news manager, user manager, notification manager, and various other settings. The app features a dynamic drawer menu system for organising news categories, dynamic search, multi-language support, and more. 

 New News Android App

User rajivvaishnav says:

“I got excellent and prompt support from the seller. I would highly recommend him. The app was totally awesome. I didn’t have any issue opening up in Android Studio and without making a single change, I was able to run the application.”

10. My News

My News is a multipurpose Android app template that can be used as a news resource, a personal blog, or a portfolio. My News offers Facebook signup and login, categories for organising news stories, push notifications, AdMob banners, and a full-featured admin panel which allows the app’s admin to manage user accounts.

My News

User forgive says:

“Good features, good app.”

Conclusion

These top Android news app templates are just a small selection of the news app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-08-13T18:59:47.520Z2018-08-13T18:59:47.520ZNona Blackman

Android Architecture Components: Using the Paging Library With Room

$
0
0

In this tutorial, I'll show you how to use the Paging library from the Android Architecture Components with a Room-backed database in an Android app. 

You'll learn how to use the Paging library to efficiently load large data sets from a Room-backed database—giving your users a smoother experience while scrolling in a RecyclerView. 

Prerequisites

To be able to follow this tutorial, you'll need:

If you haven't learnt about the architecture components, you are strongly advised to check out our awesome series all about Android Architecture Components by Tin Megali. Make sure you go dive in! 

A sample project for this tutorial can be found on our GitHub repo so you can easily follow along.

What Is the Paging Library?

The Paging library is another library added to the Architecture Components. The library helps efficiently manage the loading and display of a large data set in the RecyclerView. According to the official docs:

The Paging Library makes it easier for you to load data gradually and gracefully within your app's RecyclerView.

If any part of your Android app is going to display a large dataset from either a local or remote data source but displays only part of it at a time, then you should consider using the Paging library. This will help improve the performance of your app! 

So Why Use the Paging Library?

Now that you've seen an introduction to the Paging library, you might ask, why use it? Here are some reasons why you should consider using it in loading large data sets in a RecyclerView

  • It doesn't request data that aren't needed. This library only requests data that are visible to the user—as the user scrolls through the list. 
  • Saves the user's battery and consumes less bandwidth. Because it only requests data that are needed, this saves some device resources. 

It won't be efficient when working with a large amount of data, as the underlying data source retrieves all the data, even though only a subset of that data is going to be displayed to the user. In such a situation, we should consider paging the data instead. 

1. Create an Android Studio Project

Fire up your Android Studio 3 and create a new project with an empty activity called MainActivity. Make sure to check Include Kotlin support

Android Studio create project screen

2. Add the Architecture Components

After creating a new project, add the following dependencies in your build.gradle. In this tutorial, we are using the latest Paging library version 1.0.1, while Room is 1.1.1 (as of this writing). 

These artifacts are available at Google’s Maven repository. 

By adding the dependencies, we have taught Gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the Entity

Create a new Kotlin data class Person. For simplicity's sake, our Person entity has just two fields:

  • a unique ID (id)
  • the name of the person (name)

In addition, include a toString( method that simply returns the name

4. Create the DAO

As you know, for us to access our app's data with the Room library, we need data access objects (DAOs). In our own case, we have created a PersonDao

In our PersonDao class, we have two @Query methods. One of them is getAll(), which returns a LiveData that holds a list of Person objects. The other one is getAllPaged(), which returns a DataSource.Factory

According to the official docs, the DataSource class is the:

Base class for loading pages of snapshot data into a PagedList.

A PagedList is a special kind of List for showing paged data in Android: 

A PagedList is a List which loads its data in chunks (pages) from a DataSource. Items can be accessed with get(int), and further loading can be triggered with loadAround(int).

We called the Factory static method in the DataSource class, which serves as a factory (creating objects without having to specify the exact class of the object that will be created) for the DataSource. This static method takes in two data types:

  • The key that identifies items in DataSource. Note that for a Room query, pages are numbered—so we use Integer as the page identifier type. It is possible to have "keyed" pages using the Paging library, but Room doesn't offer that at present. 
  • The type of items or entities (POJOs) in the list loaded by the DataSources.

5. Create the Database

Here's is what our Room database class AppDatabase looks like: 

Here we have created a single instance of our database and pre-populated it with data using the new WorkManager API. Note that the data pre-populated is just a list of 1,000 names (dive into the sample source code provided to learn more). 

6. Creating the ViewModel

For our UI to store, observe, and serve data in a lifecycle-conscious way, we need a ViewModel. Our PersonsViewModel, which extends the AndroidViewModel class, is going to function as our ViewModel

In this class, we have a single field called personsLiveData. This field is simply a LiveData that holds a PagedList of Person objects. Because this is a LiveData, our UI (the Activity or Fragment) is going to observe this data by calling the getter method getPersonsLiveData()

We initialized personsLiveData inside the init block. Inside this block, we get the DataSource.Factory by calling the AppDatabase singleton for the PersonDao object. When we get this object, we call getAllPaged()

We then create a LivePagedListBuilder. Here's what the official documentation says about a LivePagedListBuilder

Builder for LiveData<PagedList>, given a DataSource.Factory and a PagedList.Config.

We supply its constructor a DataSource.Factory as the first argument and the page size as the second argument (in our own case, the page size will be 50). Typically, you should choose a size that's higher than the maximum number that you might display at once to the user. In the end, we call build() to construct and return to us a LiveData<PagedList>

7. Creating the PagedListAdapter

To show our PagedList data in a RecyclerView, we need a PagedListAdapter. Here's a clear definition of this class from the official docs:

RecyclerView.Adapter base class for presenting paged data from PagedLists in a RecyclerView.

So we create a PersonAdapter that extends PagedListAdapter.

PagedListAdapter is used just like any other subclass of RecyclerView.Adapter. In other words, you have to implement the methods onCreateViewHolder() and onBindViewHolder()

To extend the PagedListAdapter abstract class, you will have to supply—in its constructor—the type of PageLists (this should be a plain old Java class: a POJO) and also a class that extends the ViewHolder that will be used by the adapter. In our case, we gave it Person and PersonViewHolder as the first and second argument respectively. 

Note that PagedListAdapter requires you pass it a DiffUtil.ItemCallback to the PageListAdapter constructor. DiffUtil is a RecyclerView utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one. ItemCallback is an inner abstract static class (inside DiffUtil) used for calculating the diff between two non-null items in a list. 

Specifically, we supply PersonDiffCallback to our PagedListAdapter constructor. 

Because we are implementing DiffUtil.ItemCallback, we have to implement two methods: areItemsTheSame() and areContentsTheSame()

  • areItemsTheSame is called to check whether two objects represent the same item. For example, if your items have unique ids, this method should check their id equality. This method returns true if the two items represent the same object or false if they are different.
  • areContentsTheSame is called to check whether two items have the same data. This method returns true if the contents of the items are the same or false if they are different.

Our PersonViewHolder inner class is just a typical RecyclerView.ViewHolder. It's responsible for binding data as needed from our model into the widgets for a row in our list. 

8. Showing the Result

In our onCreate() of our MainActivity, we simply did the following:

  • initialize our viewModel field using the utility class ViewModelProviders
  • create an instance of PersonAdapter
  • configure our RecyclerView
  • bind the PersonAdapter to the RecyclerView
  • observe the LiveData and submit the PagedList objects over to the PersonAdapter by invoking submitList()

Finally, when you run the app, here's the result:

Tutorial result screenshot

While scrolling, Room is able to prevent gaps by loading 50 items at a time and making them available to our PersonAdapter, which is a subclass of PagingListAdapter. But note that not all data sources will be loaded quickly. The loading speed also depends on the processing power of the Android device. 

9. Integration With RxJava

If you're using or want to use RxJava in your project, the paging library includes another useful artifact: RxPagedListBuilder. You use this artifact instead of LivePagedListBuilder for RxJava support. 

You simply create an instance of RxPagedListBuilder, supplying the same arguments as you would for LivePagedListBuilder—the DataSource.Factory and the page size. You then call buildObservable() or buildFlowable() to return an Observable or Flowable for your PagedList respectively. 

To explicitly provide the Scheduler for the data loading work, you call the setter method setFetchScheduler(). To also provide the Scheduler for delivering the result (e.g. AndroidSchedulers.mainThread()), simply call setNotifyScheduler(). By default, setNotifyScheduler() defaults to the UI thread, while setFetchScheduler() defaults to the I/O thread pool. 

Conclusion

In this tutorial, you learned how to easily use the Paging component from the Android Architecture Components (which are part of Android Jetpack) with Room. This helps us efficiently load large data sets from the local database to enable a smoother user experience while scrolling through a list in the RecyclerView

I highly recommend checking out the official documentation to learn more about the Paging library in Android.

2018-08-14T12:47:36.000Z2018-08-14T12:47:36.000ZChike Mgbemena

Android Architecture Components: Using the Paging Library With Room

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

In this tutorial, I'll show you how to use the Paging library from the Android Architecture Components with a Room-backed database in an Android app. 

You'll learn how to use the Paging library to efficiently load large data sets from a Room-backed database—giving your users a smoother experience while scrolling in a RecyclerView. 

Prerequisites

To be able to follow this tutorial, you'll need:

If you haven't learnt about the architecture components, you are strongly advised to check out our awesome series all about Android Architecture Components by Tin Megali. Make sure you go dive in! 

A sample project for this tutorial can be found on our GitHub repo so you can easily follow along.

What Is the Paging Library?

The Paging library is another library added to the Architecture Components. The library helps efficiently manage the loading and display of a large data set in the RecyclerView. According to the official docs:

The Paging Library makes it easier for you to load data gradually and gracefully within your app's RecyclerView.

If any part of your Android app is going to display a large dataset from either a local or remote data source but displays only part of it at a time, then you should consider using the Paging library. This will help improve the performance of your app! 

So Why Use the Paging Library?

Now that you've seen an introduction to the Paging library, you might ask, why use it? Here are some reasons why you should consider using it in loading large data sets in a RecyclerView

  • It doesn't request data that aren't needed. This library only requests data that are visible to the user—as the user scrolls through the list. 
  • Saves the user's battery and consumes less bandwidth. Because it only requests data that are needed, this saves some device resources. 

It won't be efficient when working with a large amount of data, as the underlying data source retrieves all the data, even though only a subset of that data is going to be displayed to the user. In such a situation, we should consider paging the data instead. 

1. Create an Android Studio Project

Fire up your Android Studio 3 and create a new project with an empty activity called MainActivity. Make sure to check Include Kotlin support

Android Studio create project screen

2. Add the Architecture Components

After creating a new project, add the following dependencies in your build.gradle. In this tutorial, we are using the latest Paging library version 1.0.1, while Room is 1.1.1 (as of this writing). 

These artifacts are available at Google’s Maven repository. 

By adding the dependencies, we have taught Gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the Entity

Create a new Kotlin data class Person. For simplicity's sake, our Person entity has just two fields:

  • a unique ID (id)
  • the name of the person (name)

In addition, include a toString( method that simply returns the name

4. Create the DAO

As you know, for us to access our app's data with the Room library, we need data access objects (DAOs). In our own case, we have created a PersonDao

In our PersonDao class, we have two @Query methods. One of them is getAll(), which returns a LiveData that holds a list of Person objects. The other one is getAllPaged(), which returns a DataSource.Factory

According to the official docs, the DataSource class is the:

Base class for loading pages of snapshot data into a PagedList.

A PagedList is a special kind of List for showing paged data in Android: 

A PagedList is a List which loads its data in chunks (pages) from a DataSource. Items can be accessed with get(int), and further loading can be triggered with loadAround(int).

We called the Factory static method in the DataSource class, which serves as a factory (creating objects without having to specify the exact class of the object that will be created) for the DataSource. This static method takes in two data types:

  • The key that identifies items in DataSource. Note that for a Room query, pages are numbered—so we use Integer as the page identifier type. It is possible to have "keyed" pages using the Paging library, but Room doesn't offer that at present. 
  • The type of items or entities (POJOs) in the list loaded by the DataSources.

5. Create the Database

Here's is what our Room database class AppDatabase looks like: 

Here we have created a single instance of our database and pre-populated it with data using the new WorkManager API. Note that the data pre-populated is just a list of 1,000 names (dive into the sample source code provided to learn more). 

6. Creating the ViewModel

For our UI to store, observe, and serve data in a lifecycle-conscious way, we need a ViewModel. Our PersonsViewModel, which extends the AndroidViewModel class, is going to function as our ViewModel

In this class, we have a single field called personsLiveData. This field is simply a LiveData that holds a PagedList of Person objects. Because this is a LiveData, our UI (the Activity or Fragment) is going to observe this data by calling the getter method getPersonsLiveData()

We initialized personsLiveData inside the init block. Inside this block, we get the DataSource.Factory by calling the AppDatabase singleton for the PersonDao object. When we get this object, we call getAllPaged()

We then create a LivePagedListBuilder. Here's what the official documentation says about a LivePagedListBuilder

Builder for LiveData<PagedList>, given a DataSource.Factory and a PagedList.Config.

We supply its constructor a DataSource.Factory as the first argument and the page size as the second argument (in our own case, the page size will be 50). Typically, you should choose a size that's higher than the maximum number that you might display at once to the user. In the end, we call build() to construct and return to us a LiveData<PagedList>

7. Creating the PagedListAdapter

To show our PagedList data in a RecyclerView, we need a PagedListAdapter. Here's a clear definition of this class from the official docs:

RecyclerView.Adapter base class for presenting paged data from PagedLists in a RecyclerView.

So we create a PersonAdapter that extends PagedListAdapter.

PagedListAdapter is used just like any other subclass of RecyclerView.Adapter. In other words, you have to implement the methods onCreateViewHolder() and onBindViewHolder()

To extend the PagedListAdapter abstract class, you will have to supply—in its constructor—the type of PageLists (this should be a plain old Java class: a POJO) and also a class that extends the ViewHolder that will be used by the adapter. In our case, we gave it Person and PersonViewHolder as the first and second argument respectively. 

Note that PagedListAdapter requires you pass it a DiffUtil.ItemCallback to the PageListAdapter constructor. DiffUtil is a RecyclerView utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one. ItemCallback is an inner abstract static class (inside DiffUtil) used for calculating the diff between two non-null items in a list. 

Specifically, we supply PersonDiffCallback to our PagedListAdapter constructor. 

Because we are implementing DiffUtil.ItemCallback, we have to implement two methods: areItemsTheSame() and areContentsTheSame()

  • areItemsTheSame is called to check whether two objects represent the same item. For example, if your items have unique ids, this method should check their id equality. This method returns true if the two items represent the same object or false if they are different.
  • areContentsTheSame is called to check whether two items have the same data. This method returns true if the contents of the items are the same or false if they are different.

Our PersonViewHolder inner class is just a typical RecyclerView.ViewHolder. It's responsible for binding data as needed from our model into the widgets for a row in our list. 

8. Showing the Result

In our onCreate() of our MainActivity, we simply did the following:

  • initialize our viewModel field using the utility class ViewModelProviders
  • create an instance of PersonAdapter
  • configure our RecyclerView
  • bind the PersonAdapter to the RecyclerView
  • observe the LiveData and submit the PagedList objects over to the PersonAdapter by invoking submitList()

Finally, when you run the app, here's the result:

Tutorial result screenshot

While scrolling, Room is able to prevent gaps by loading 50 items at a time and making them available to our PersonAdapter, which is a subclass of PagingListAdapter. But note that not all data sources will be loaded quickly. The loading speed also depends on the processing power of the Android device. 

9. Integration With RxJava

If you're using or want to use RxJava in your project, the paging library includes another useful artifact: RxPagedListBuilder. You use this artifact instead of LivePagedListBuilder for RxJava support. 

You simply create an instance of RxPagedListBuilder, supplying the same arguments as you would for LivePagedListBuilder—the DataSource.Factory and the page size. You then call buildObservable() or buildFlowable() to return an Observable or Flowable for your PagedList respectively. 

To explicitly provide the Scheduler for the data loading work, you call the setter method setFetchScheduler(). To also provide the Scheduler for delivering the result (e.g. AndroidSchedulers.mainThread()), simply call setNotifyScheduler(). By default, setNotifyScheduler() defaults to the UI thread, while setFetchScheduler() defaults to the I/O thread pool. 

Conclusion

In this tutorial, you learned how to easily use the Paging component from the Android Architecture Components (which are part of Android Jetpack) with Room. This helps us efficiently load large data sets from the local database to enable a smoother user experience while scrolling through a list in the RecyclerView

I highly recommend checking out the official documentation to learn more about the Paging library in Android.

2018-08-14T12:47:36.000Z2018-08-14T12:47:36.000ZChike Mgbemena

15 Ready-Made Ionic 3 App Templates

$
0
0

With Ionic, creating a high-performance, cross-platform mobile app is as easy as creating a website. In fact, if you are a seasoned web developer who wants to become an Android or iOS app developer overnight, all you have to do is install and start using Ionic. I assure you, you'll take to it like a fish to water.

Building a feature-rich Ionic app with an elegant user interface, however, can be challenging—even more so if it is to look native on multiple platforms. Fortunately, by using a ready-made Ionic template, you can save substantial amounts of time and effort.

CodeCanyon is one of the largest online marketplaces for Ionic templates. No matter what your app's requirements are, there's a good chance that CodeCanyon has a template for it. In this article, I'm going to list 15 outstanding Ionic 3 templates you should consider using this year.

1. Ionic 3 UI Theme 

Ionic 3 UI Theme

This template, developed by elite author CreativeForm, is ideal for Ionic developers who want to create beautiful apps but spend less time designing them. It offers just one theme that includes over 70 commonly used screens and more than 45 finished layouts ready to use. It also has a well-organized Sass file containing dozens of variables you can change to further customize your app's looks.

2. IonFullApp 

onFullApp

IonFullApp, developed by elite author IonicThemes, is a multipurpose app template which comes in three different versions: basic, pro, and elite. These three versions offer from 30 to 38 screens and different combinations of components to suit a variety of needs. Some of the best features offered are Google Maps integration, social login, geolocation, a video player, and an image slider.

3. Ionic 3 App for WooCommerce 

Ionic 3 App for WooCommerce

Ionic 3 App for WooCommerce, developed by hakeemnala, is a template you should definitely consider using if you are creating an e-commerce app. It allows you to quickly create a beautiful app that can connect to your WooCommerce website, pull data and settings from it, and sync categories and products in real time. It also promises your customers an easy and hassle-free shopping experience. 

The app template supports most of the payment methods out there, automatically loads shipping methods, allows customers to search for products globally on the home page or within categories, and much more. 

4. Ionic 3 Restaurant App

Ionic 3 Restaurant App

If you’re looking for an intuitive, easy to set up Restaurant app then check out Ionic 3 Restaurant App template, developed by Lrandom. The app is well structured and offers useful features like food categories, item details that allow you to use images of products, product names and details, prices, current promotions, a powerful search, a cart list view, and much more. In addition, the source code for the app comes with an admin panel CMS that will help you build your app faster.

5. IonChat v3

IonChat v3

IonChat v3, as its name suggests, is a template that lets you build cross-platform instant messaging apps. Developed by IonCoder, this is a large template offering dozens of powerful features, such as support for group conversations, social login, and friend management.

Not only is this template easily customizable, the apps you create with it will be powered by Firebase, a cloud-based platform that's owned by Google. That means you can use the Firebase console to manage your app data.

6. Ionic Framework App

If you are looking for a modern template with dozens of beautiful pages and a wide variety of useful features, this template, created by gtsopour, is for you. Built with Ionic 3, it is very modular and extremely easy to extend. In fact, it has over 20 modules and over 35 components!

The apps you create with this template will be able to communicate with your WordPress blog using its REST API. They'll also be able to display charts, YouTube videos, Google maps, and RSS feeds. Another impressive fact about the template is that it offers a barcode scanner module, which you can use to scan several types of barcodes.

7. Restaurant Ionic 3

Restaurant Ionic 3

Restaurant Ionic 3, developed by appseed, is a template that's bound to entice any restaurant owner. Apps created with it are feature-packed, and they have intuitive user interfaces that let customers view menus, place customized orders, read about special offers, and choose delivery methods. They'll also allow you to communicate with your customers using push notifications.

Setting this template up is a breeze. So is customizing it, because you can dramatically change the looks of your app by simply selecting one of the several beautiful Material Design-inspired color themes it offers. 

8. Ionium 2 

Ionium 2

Ionium 2 is an update of the popular multipurpose app template Ionium, created by ionicpremium. Built with Ionic 3, this multipurpose app template is a great choice whether you’re building an e-commerce app, a hotel booking app, a news reader, or even a social media app. The template allows you to quickly create CRUD-oriented apps, which support both local and remote storage.

Using Sass and Material Design components, animations, and gestures, you can be sure that the apps you create with Ionium 2 will look very modern and polished.

9. Ionic 3 Toolkit 

 Ionic 3 Toolkit

The Ionic 3 Toolkit app template developed by appseed certainly lives up to its promise of being a toolkit with its wide range of features and its modular structure, which allow users to build whatever kind of app they need quickly and easily.  

It also allows you to collect data from your WordPress, Drupal, YouTube, Vimeo, Instagram and other social media accounts and add them to the content of your app as needed. Furthermore, the template makes it easy to customise the template’s default styles by changing the predefined colours or the default value of the Sass.

10. Firetask

Firetask

Apps with social features tend to be more successful on both Google Play and Apple's App Store. If you’re looking for an Ionic 3 app template to build a social media app for yourself or a client, look no further than Firetask by developer Stewan_io. Firetask is a social media app template that has everything you need to get started. It offers screens that allow users to sign up, sign in, create posts, write comments, browse through trending topics, and much more.

11. WooCommerce Mobile App

WooCommerce Mobile App

In spite of being on the market for just a few months, WooCommerce Mobile App template, by hakeemnala, has been selling steadily and is one of the best-rated templates in this category. 

The app allows clients to connect to their WooCommerce store and sync categories and products in real time. Once customers register and log in, they can shop, pay for items, view order status and order history, and manage their account. Useful features include a featured products page, categories, a powerful search and filter, list and grid views, ratings and reviews, etc. 

12. Hotel Room Reservation

Hotel Room Reservation

Another recent addition to CodeCanyon’s mobile app section, the Hotel Room Reservation app template by developer FunnyIonic is created in the vein of popular hotel booking services like Booking and Airbnb. The template helps developers to create an app that will allow end users to search, view and book hotels in their targeted location. The app is integrated with Google Maps and PayPal for user convenience. 

13. Conference Ionic 3

Conference Ionic 3

Another app template by the prolific developer appseed, Conference Ionic 3 app template offers something unique in the app template arena. The app is aimed at conference organisers who want to create an app for attendees that provides all the information related to a conference in one handy app. 

It allows attendees to view conference information such as location, exhibition halls, speakers, schedules, sponsors, committees, etc. Users can access speaker profiles and can create their own personal agendas based on what events they want to attend.

14. Ionic Ecommerce 

Ionic Ecommerce

I’ve featured a couple of e-commerce app templates here so far, but I'm adding Ionic Ecommerce by the developer vectorcoder to this list not just because of its popularity but because of the template's all-round usefulness. 

A relative newcomer to the field, Ionic Ecommerce offers a variety of ready-made e-commerce pages to create your mobile app and provides a comprehensive CMS to manage your store. Some key features include interactive themes, social share, product filters, sorting and search, inventory management, and much more. The developer provides full support and will customise and install the app for you for a fee.

15. Nearme

Nearme

Nearme is a location-based app template by developer quanlabs. The Ionic 3 template helps developers build an app that will identify supermarkets, restaurants, places of interest, gas stations, etc. that are near the user. The template comes with an admin panel that allows developers to send push notifications to users and manage categories, places, deals, slider images, users, reviews, etc.

Conclusion

In this article, you learned about 15 premium Ionic templates you can use to jumpstart your app development process. But don't limit yourself to just them because these are just a small selection of the hundreds of Ionic 3 app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills in building Ionic apps and templates, then check out some of the ever-so-useful Ionic tutorials we have on offer!

2018-08-20T01:25:01.965Z2018-08-20T01:25:01.965ZNona Blackman

15 Ready-Made Ionic 3 App Templates

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

With Ionic, creating a high-performance, cross-platform mobile app is as easy as creating a website. In fact, if you are a seasoned web developer who wants to become an Android or iOS app developer overnight, all you have to do is install and start using Ionic. I assure you, you'll take to it like a fish to water.

Building a feature-rich Ionic app with an elegant user interface, however, can be challenging—even more so if it is to look native on multiple platforms. Fortunately, by using a ready-made Ionic template, you can save substantial amounts of time and effort.

CodeCanyon is one of the largest online marketplaces for Ionic templates. No matter what your app's requirements are, there's a good chance that CodeCanyon has a template for it. In this article, I'm going to list 15 outstanding Ionic 3 templates you should consider using this year.

1. Ionic 3 UI Theme 

Ionic 3 UI Theme

This template, developed by elite author CreativeForm, is ideal for Ionic developers who want to create beautiful apps but spend less time designing them. It offers just one theme that includes over 70 commonly used screens and more than 45 finished layouts ready to use. It also has a well-organized Sass file containing dozens of variables you can change to further customize your app's looks.

2. IonFullApp 

onFullApp

IonFullApp, developed by elite author IonicThemes, is a multipurpose app template which comes in three different versions: basic, pro, and elite. These three versions offer from 30 to 38 screens and different combinations of components to suit a variety of needs. Some of the best features offered are Google Maps integration, social login, geolocation, a video player, and an image slider.

3. Ionic 3 App for WooCommerce 

Ionic 3 App for WooCommerce

Ionic 3 App for WooCommerce, developed by hakeemnala, is a template you should definitely consider using if you are creating an e-commerce app. It allows you to quickly create a beautiful app that can connect to your WooCommerce website, pull data and settings from it, and sync categories and products in real time. It also promises your customers an easy and hassle-free shopping experience. 

The app template supports most of the payment methods out there, automatically loads shipping methods, allows customers to search for products globally on the home page or within categories, and much more. 

4. Ionic 3 Restaurant App

Ionic 3 Restaurant App

If you’re looking for an intuitive, easy to set up Restaurant app then check out Ionic 3 Restaurant App template, developed by Lrandom. The app is well structured and offers useful features like food categories, item details that allow you to use images of products, product names and details, prices, current promotions, a powerful search, a cart list view, and much more. In addition, the source code for the app comes with an admin panel CMS that will help you build your app faster.

5. IonChat v3

IonChat v3

IonChat v3, as its name suggests, is a template that lets you build cross-platform instant messaging apps. Developed by IonCoder, this is a large template offering dozens of powerful features, such as support for group conversations, social login, and friend management.

Not only is this template easily customizable, the apps you create with it will be powered by Firebase, a cloud-based platform that's owned by Google. That means you can use the Firebase console to manage your app data.

6. Ionic Framework App

If you are looking for a modern template with dozens of beautiful pages and a wide variety of useful features, this template, created by gtsopour, is for you. Built with Ionic 3, it is very modular and extremely easy to extend. In fact, it has over 20 modules and over 35 components!

The apps you create with this template will be able to communicate with your WordPress blog using its REST API. They'll also be able to display charts, YouTube videos, Google maps, and RSS feeds. Another impressive fact about the template is that it offers a barcode scanner module, which you can use to scan several types of barcodes.

7. Restaurant Ionic 3

Restaurant Ionic 3

Restaurant Ionic 3, developed by appseed, is a template that's bound to entice any restaurant owner. Apps created with it are feature-packed, and they have intuitive user interfaces that let customers view menus, place customized orders, read about special offers, and choose delivery methods. They'll also allow you to communicate with your customers using push notifications.

Setting this template up is a breeze. So is customizing it, because you can dramatically change the looks of your app by simply selecting one of the several beautiful Material Design-inspired color themes it offers. 

8. Ionium 2 

Ionium 2

Ionium 2 is an update of the popular multipurpose app template Ionium, created by ionicpremium. Built with Ionic 3, this multipurpose app template is a great choice whether you’re building an e-commerce app, a hotel booking app, a news reader, or even a social media app. The template allows you to quickly create CRUD-oriented apps, which support both local and remote storage.

Using Sass and Material Design components, animations, and gestures, you can be sure that the apps you create with Ionium 2 will look very modern and polished.

9. Ionic 3 Toolkit 

 Ionic 3 Toolkit

The Ionic 3 Toolkit app template developed by appseed certainly lives up to its promise of being a toolkit with its wide range of features and its modular structure, which allow users to build whatever kind of app they need quickly and easily.  

It also allows you to collect data from your WordPress, Drupal, YouTube, Vimeo, Instagram and other social media accounts and add them to the content of your app as needed. Furthermore, the template makes it easy to customise the template’s default styles by changing the predefined colours or the default value of the Sass.

10. Firetask

Firetask

Apps with social features tend to be more successful on both Google Play and Apple's App Store. If you’re looking for an Ionic 3 app template to build a social media app for yourself or a client, look no further than Firetask by developer Stewan_io. Firetask is a social media app template that has everything you need to get started. It offers screens that allow users to sign up, sign in, create posts, write comments, browse through trending topics, and much more.

11. WooCommerce Mobile App

WooCommerce Mobile App

In spite of being on the market for just a few months, WooCommerce Mobile App template, by hakeemnala, has been selling steadily and is one of the best-rated templates in this category. 

The app allows clients to connect to their WooCommerce store and sync categories and products in real time. Once customers register and log in, they can shop, pay for items, view order status and order history, and manage their account. Useful features include a featured products page, categories, a powerful search and filter, list and grid views, ratings and reviews, etc. 

12. Hotel Room Reservation

Hotel Room Reservation

Another recent addition to CodeCanyon’s mobile app section, the Hotel Room Reservation app template by developer FunnyIonic is created in the vein of popular hotel booking services like Booking and Airbnb. The template helps developers to create an app that will allow end users to search, view and book hotels in their targeted location. The app is integrated with Google Maps and PayPal for user convenience. 

13. Conference Ionic 3

Conference Ionic 3

Another app template by the prolific developer appseed, Conference Ionic 3 app template offers something unique in the app template arena. The app is aimed at conference organisers who want to create an app for attendees that provides all the information related to a conference in one handy app. 

It allows attendees to view conference information such as location, exhibition halls, speakers, schedules, sponsors, committees, etc. Users can access speaker profiles and can create their own personal agendas based on what events they want to attend.

14. Ionic Ecommerce 

Ionic Ecommerce

I’ve featured a couple of e-commerce app templates here so far, but I'm adding Ionic Ecommerce by the developer vectorcoder to this list not just because of its popularity but because of the template's all-round usefulness. 

A relative newcomer to the field, Ionic Ecommerce offers a variety of ready-made e-commerce pages to create your mobile app and provides a comprehensive CMS to manage your store. Some key features include interactive themes, social share, product filters, sorting and search, inventory management, and much more. The developer provides full support and will customise and install the app for you for a fee.

15. Nearme

Nearme

Nearme is a location-based app template by developer quanlabs. The Ionic 3 template helps developers build an app that will identify supermarkets, restaurants, places of interest, gas stations, etc. that are near the user. The template comes with an admin panel that allows developers to send push notifications to users and manage categories, places, deals, slider images, users, reviews, etc.

Conclusion

In this article, you learned about 15 premium Ionic templates you can use to jumpstart your app development process. But don't limit yourself to just them because these are just a small selection of the hundreds of Ionic 3 app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills in building Ionic apps and templates, then check out some of the ever-so-useful Ionic tutorials we have on offer!

2018-08-20T01:25:01.965Z2018-08-20T01:25:01.965ZNona Blackman

7 Android Templates to Inspire Your Next Project

$
0
0

App templates are a great way to jumpstart your next project or to learn from other people's work. This article lists a few popular Android templates available on Envato Market. If you are looking for inspiration or you're building an Android app and need help with a particular feature, then you may find your answer in some of these templates. All of these templates come with full source code so you can customize the apps however you want.

1. Restaurant Finder

This template bursts with features, and it even includes a back-end ready to be deployed to a server. The application enables users to search for nearby restaurants, read reviews, and share on social media, and it also includes the ability to book a table via email or text message.

Restaurant Finder

Almost every modern, mobile app talks to a back-end for some reason or another, and this one is no different. The template includes a back-end for storing restaurants and user profiles. It also includes an analytics dashboard that shows metrics about the restaurants and users of the app. If you need inspiration for a location-based app, then this template is worth checking out.

2. Your Radio App

If you've ever wanted to know how to stream audio in an Android application, then this template is worth checking out. The application is focused on streaming audio from online radio stations. The template includes a feature-packed Android application as well as a back-end for managing the radio stations users can listen to.

Your Radio App

The template is compatible with both Android Studio and Eclipse, and it relies on Parse for push notifications. It also includes AdMob for ad management. The application supports a wide range of stream formats and has a beautiful, modern user interface. If you're not convinced yet, then download the application from Google Play to try it out.

3.  Universal

Universal is a beautiful, minimal, multi-purpose Android app template. You can create just about anything with it. And you can do it fast! Universal is a WebView app that lets you convert a website into an Android app. This app template has been around for a long time and is packed with features: a customizable native navigation menu, share buttons, geolocation, push notifications, and more!

Whether you're looking to build a simple app or an app packed full of features, this is a stellar template to get you started.

Universal - Full Multi-Purpose Android App

Build your app, your way. Some of the features include:

  • in-app purchases and AdMob advertising
  • push notifications
  • media player
  • localization
  • and more

The template UI features parallax animations and content-focused design. Best of all, the built-in configuration tool is so powerful that you don't need to write any code.

If you need to convert your WordPress website, YouTube channel, WooCommerce site, or other web site into a mobile app, it's hard to recommend anything else—Universal deserves serious consideration.

4. Cookbook Recipe App

You'll find plenty of inspiration with the Cookbook Recipe App.

If you're interested in building a cookbook app, this is perfect. But even if you have something else in mind, there's plenty here to draw inspiration from.

Cookbook - Recipe App

This template features:

  • a sweet material design
  • flavorful search
  • delectable recipe details
  • a yummy shopping list feature
  • a crunchy kitchen timer
  • and so many more delicious features

AdMob and Google Analytics are supported, and the code is clean. If you hunger for some fresh inspiration, consider the Cookbook - Recipe App.

5. Taxi Booking App

I already mentioned that many traditional businesses are making the jump to mobile and this includes taxi companies. There's a reason why Uber and Lyft are so popular—mobile apps are simply more convenient for customers. 

This Android template is quite impressive. It contains a feature-rich Android app as well as a powerful back-end, making a complete solution. The app includes an interactive map with vehicle information and tracking, voice recognition, and support for push notifications.

Taxi Booking App

The template offers a solution for both users and drivers. Users can order a ride with the mobile application and drivers receive a notification when someone requests a ride. Even if you don't plan to build a taxi booking application, there's a lot you can learn from browsing the ins and outs of this template.

6. The City

This interesting places app template is suitable for a tourism or city guide. This all-native app lets users discover interesting places on a city map. The app UI follows material design specs and even has animations.

The City

Data is stored locally on the user's phone, so the app is fast and responsive. But there is also an integrated admin back-end, so you can update the location data from anywhere on the fly. Then, with GCM notification, you can send those updates out to your users so they always have the latest version.

7. Android Material UI Template 

Sometimes it's really helpful just to have a reference template to work from. Some examples of a good UI design that you can copy and paste and modify. That's where Android Material UI Template comes in.

Android Material UI Template

This popular template contains many examples of material design app layouts. These pixel-perfect layouts make it easy for you to create your own beautiful material design app. Just focus on the functionality, and let the template author do the grunt work of UI design and layout for you!

More?

Envato Market contains hundreds of mobile application templates to get you started with your next project. These templates are great for learning, to see how fellow developers have implemented a particular feature. They're also great if you're looking for a jumpstart on your next app project. Check out more Android app templates on Envato Market.

2018-08-31T07:59:59.471Z2018-08-31T07:59:59.471ZEric Dye

7 Android Templates to Inspire Your Next Project

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

App templates are a great way to jumpstart your next project or to learn from other people's work. This article lists a few popular Android templates available on Envato Market. If you are looking for inspiration or you're building an Android app and need help with a particular feature, then you may find your answer in some of these templates. All of these templates come with full source code so you can customize the apps however you want.

1. Restaurant Finder

This template bursts with features, and it even includes a back-end ready to be deployed to a server. The application enables users to search for nearby restaurants, read reviews, and share on social media, and it also includes the ability to book a table via email or text message.

Restaurant Finder

Almost every modern, mobile app talks to a back-end for some reason or another, and this one is no different. The template includes a back-end for storing restaurants and user profiles. It also includes an analytics dashboard that shows metrics about the restaurants and users of the app. If you need inspiration for a location-based app, then this template is worth checking out.

2. Your Radio App

If you've ever wanted to know how to stream audio in an Android application, then this template is worth checking out. The application is focused on streaming audio from online radio stations. The template includes a feature-packed Android application as well as a back-end for managing the radio stations users can listen to.

Your Radio App

The template is compatible with both Android Studio and Eclipse, and it relies on Parse for push notifications. It also includes AdMob for ad management. The application supports a wide range of stream formats and has a beautiful, modern user interface. If you're not convinced yet, then download the application from Google Play to try it out.

3.  Universal

Universal is a beautiful, minimal, multi-purpose Android app template. You can create just about anything with it. And you can do it fast! Universal is a WebView app that lets you convert a website into an Android app. This app template has been around for a long time and is packed with features: a customizable native navigation menu, share buttons, geolocation, push notifications, and more!

Whether you're looking to build a simple app or an app packed full of features, this is a stellar template to get you started.

Universal - Full Multi-Purpose Android App

Build your app, your way. Some of the features include:

  • in-app purchases and AdMob advertising
  • push notifications
  • media player
  • localization
  • and more

The template UI features parallax animations and content-focused design. Best of all, the built-in configuration tool is so powerful that you don't need to write any code.

If you need to convert your WordPress website, YouTube channel, WooCommerce site, or other web site into a mobile app, it's hard to recommend anything else—Universal deserves serious consideration.

4. Cookbook Recipe App

You'll find plenty of inspiration with the Cookbook Recipe App.

If you're interested in building a cookbook app, this is perfect. But even if you have something else in mind, there's plenty here to draw inspiration from.

Cookbook - Recipe App

This template features:

  • a sweet material design
  • flavorful search
  • delectable recipe details
  • a yummy shopping list feature
  • a crunchy kitchen timer
  • and so many more delicious features

AdMob and Google Analytics are supported, and the code is clean. If you hunger for some fresh inspiration, consider the Cookbook - Recipe App.

5. Taxi Booking App

I already mentioned that many traditional businesses are making the jump to mobile and this includes taxi companies. There's a reason why Uber and Lyft are so popular—mobile apps are simply more convenient for customers. 

This Android template is quite impressive. It contains a feature-rich Android app as well as a powerful back-end, making a complete solution. The app includes an interactive map with vehicle information and tracking, voice recognition, and support for push notifications.

Taxi Booking App

The template offers a solution for both users and drivers. Users can order a ride with the mobile application and drivers receive a notification when someone requests a ride. Even if you don't plan to build a taxi booking application, there's a lot you can learn from browsing the ins and outs of this template.

6. The City

This interesting places app template is suitable for a tourism or city guide. This all-native app lets users discover interesting places on a city map. The app UI follows material design specs and even has animations.

The City

Data is stored locally on the user's phone, so the app is fast and responsive. But there is also an integrated admin back-end, so you can update the location data from anywhere on the fly. Then, with GCM notification, you can send those updates out to your users so they always have the latest version.

7. Android Material UI Template 

Sometimes it's really helpful just to have a reference template to work from. Some examples of a good UI design that you can copy and paste and modify. That's where Android Material UI Template comes in.

Android Material UI Template

This popular template contains many examples of material design app layouts. These pixel-perfect layouts make it easy for you to create your own beautiful material design app. Just focus on the functionality, and let the template author do the grunt work of UI design and layout for you!

More?

Envato Market contains hundreds of mobile application templates to get you started with your next project. These templates are great for learning, to see how fellow developers have implemented a particular feature. They're also great if you're looking for a jumpstart on your next app project. Check out more Android app templates on Envato Market.

2018-08-31T07:59:59.471Z2018-08-31T07:59:59.471ZEric Dye

New Short Course on Kotlin Android Intents

$
0
0

The Intent is one of the fundamental building blocks of an Android app. If you want to become a pro Android coder, you're going to need to master Intents. And the best way to do that is by taking our new short course, Kotlin Android Fundamentals: Intents.

What You’ll Learn

In this course, Annapurna Agrawal will teach you everything you need to know to use Intents in your Kotlin Android app. 

You'll start by learning how Intents help different components of Android to work together. You'll learn how to call activities within the same app and how to use activities from outside the app. You will also see how to accept data from other apps using Intent filters.

Using Android Kotlin Implicit Intents

Finally, you'll learn an effective way to test your implementation of implicit intents and custom actions using the Android Debug Bridge (ADB). ADB makes testing very easy and saves a lot of time.

Watch the Introduction

 

Take the Course

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

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

2018-09-04T08:22:28.000Z2018-09-04T08:22:28.000ZAndrew Blackman

New Short Course on Kotlin Android Intents

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

The Intent is one of the fundamental building blocks of an Android app. If you want to become a pro Android coder, you're going to need to master Intents. And the best way to do that is by taking our new short course, Kotlin Android Fundamentals: Intents.

What You’ll Learn

In this course, Annapurna Agrawal will teach you everything you need to know to use Intents in your Kotlin Android app. 

You'll start by learning how Intents help different components of Android to work together. You'll learn how to call activities within the same app and how to use activities from outside the app. You will also see how to accept data from other apps using Intent filters.

Using Android Kotlin Implicit Intents

Finally, you'll learn an effective way to test your implementation of implicit intents and custom actions using the Android Debug Bridge (ADB). ADB makes testing very easy and saves a lot of time.

Watch the Introduction

 

Take the Course

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

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

2018-09-04T08:22:28.000Z2018-09-04T08:22:28.000ZAndrew Blackman

Testing Android User Interfaces With Espresso

$
0
0

In this post, you'll learn about how to write UI tests with the Espresso testing framework and automate your test workflow, instead of using the tedious and highly error-prone manual process. 

Espresso is a testing framework for writing UI tests in Android. According to the official docs, you can:

Use Espresso to write concise, beautiful, and reliable Android UI tests.

1. Why Use Espresso?

One of the problems with manual testing is that it can be time-consuming and tedious to perform. For example, to test a login screen (manually) in an Android app, you will have to do the following:

  1. Launch the app. 
  2. Navigate to the login screen. 
  3. Confirm if the usernameEditText and passwordEditText are visible. 
  4. Type the username and password into their respective fields. 
  5. Confirm if the login button is also visible, and then click on that login button.
  6. Check if the correct views are displayed when that login was successful or was a failure. 

Instead of spending all this time manually testing our app, it would be better to spend more time writing code that makes our app stand out from the rest! And, even though manual testing is tedious and quite slow, it is still error-prone and you might miss some corner cases. 

Some of the advantages of automated testing include the following:   

  • Automated tests execute exactly the same test cases every time they are executed. 
  • Developers can quickly spot a problem quickly before it is sent to the QA team. 
  • It can save a lot of time, unlike doing manual testing. By saving time, software engineers and the QA team can instead spend more time on challenging and rewarding tasks. 
  • Higher test coverage is achieved, which leads to a better quality application. 

In this tutorial, we'll learn about Espresso by integrating it into an Android Studio project. We'll write UI tests for a login screen and a RecyclerView, and we'll learn about testing intents. 

Quality is not an act, it is a habit. — Pablo Picasso

2. Prerequisites

To be able to follow this tutorial, you'll need:

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

3. Create an Android Studio Project

Fire up your Android Studio 3 and create a new project with an empty activity called MainActivity. Make sure to check Include Kotlin support

Create Android Project dialog

4. Set Up Espresso and AndroidJUnitRunner

After creating a new project, make sure to add the following dependencies from the Android Testing Support Library in your build.gradle (although Android Studio has already included them for us). In this tutorial, we are using the latest Espresso library version 3.0.2 (as of this writing). 

We also included the instrumentation runner AndroidJUnitRunner:

An Instrumentation that runs JUnit3 and JUnit4 tests against an Android package (application).

Note that Instrumentation is simply a base class for implementing application instrumentation code. 

Turn Off Animation 

The synchronisation of Espresso, which doesn't know how to wait for an animation to finish, can cause some tests to fail—if you allow animation on your test device. To turn off animation on your test device, go to Settings > Developer Options and turn off all the following options under the "Drawing" section: 

  • Window animation scale
  • Transition animation scale
  • Animator duration scale

5. Write Your First Test in Espresso

First, we start off testing a Login screen. Here's how the login flow starts: the user launches the app, and the first screen shown contains a single Login button. When that Login button is clicked, it opens up the LoginActivity screen. This screen contains just two EditTexts (the username and password fields) and a Submit button. 

Here's what our MainActivity layout looks like:

MainActivity layout

Here's what our LoginActivity layout looks like:

Let's now write a test for our MainActivity class. Go to your MainActivity class, move the cursor to the MainActivity name, and press Shift-Control-T. Select Create New Test... in the popup menu. 

Create new test dialog

Press the OK button, and another dialog shows up. Choose the androidTest directory and click the OK button once more. Note that because we are writing an instrumentation test (Android SDK specific tests), the test cases reside in the androidTest/java folder. 

Now, Android Studio has successfully created a test class for us. Above the class name, include this annotation: @RunWith(AndroidJUnit4::class).

This annotation signifies that all the tests in this class are Android-specific tests.

Testing Activities

Because we want to test an Activity, we have to do a little setup. We need to inform Espresso which Activity to open or launch before executing and destroy after executing any test method. 

Note that the @Rule annotation means that this is a JUnit4 test rule. JUnit4 test rules are run before and after every test method (annotated with @Test). In our own scenario, we want to launch MainActivity before every test method and destroy it after. 

We also included the @JvmField Kotlin annotation. This simply instructs the compiler not to generate getters and setters for the property and instead to expose it as a simple Java field.

Here are the three major steps in writing an Espresso test:

  • Look for the widget (e.g. TextView or Button) you want to test.
  • Perform one or more actions on that widget. 
  • Verify or check to see if that widget is now in a certain state. 

The following types of annotations can be applied to the methods used inside the test class.

  • @BeforeClass: this indicates that the static method this annotation is applied to must be executed once and before all tests in the class. This could be used, for example, to set up a connection to a database. 
  • @Before: indicates that the method this annotation is attached to must be executed before each test method in the class.
  • @Test: indicates that the method this annotation is attached to should run as a test case.
  • @After: indicates that the method this annotation is attached to should run after each test method. 
  • @AfterClass: indicates that the method this annotation is attached to should run after all the test methods in the class have been run. Here, we typically close out resources that were opened in @BeforeClass

Find a View Using onView()

In our MainActivity layout file, we just have one widget—the Login button. Let's test a scenario where a user will find that button and click on it.

To find widgets in Espresso, we make use of the onView() static method (instead of findViewById()). The parameter type we supply to onView() is a Matcher. Note that the Matcher API doesn't come from the Android SDK but instead from the Hamcrest Project. Hamcrest's matcher library is inside the Espresso library we pulled via Gradle. 

The onView(withId(R.id.btn_login)) will return a ViewInteraction that is for a View whose ID is R.id.btn_login. In the example above, we used withId() to look for a widget with a given id. Other view matchers we can use are: 

  • withText(): returns a matcher that matches TextView based on its text property value.
  • withHint(): returns a matcher that matches TextView based on its hint property value.
  • withTagKey(): returns a matcher that matches View based on tag keys.
  • withTagValue(): returns a matcher that matches Views based on tag property values.

First, let's test to see if the button is actually displayed on the screen. 

Here, we are just confirming if the button with the given id (R.id.btn_login) is visible to the user, so we use the check() method to confirm if the underlying View has a certain state—in our case, if it is visible.

The matches() static method returns a generic ViewAssertion that asserts that a view exists in the view hierarchy and is matched by the given view matcher. That given view matcher is returned by calling isDisplayed(). As suggested by the method name, isDisplayed() is a matcher that matches Views that are currently displayed on the screen to the user. For example, if we want to check if a button is enabled, we simply pass isEnabled() to matches()

Other popular view matchers we can pass into the matches() method are:

  • hasFocus(): returns a matcher that matches Views that currently have focus.
  • isChecked(): returns a matcher that accepts if and only if the view is a CompoundButton (or subtype of) and is in checked state. The opposite of this method is isNotChecked()
  • isSelected(): returns a matcher that matches Views that are selected.

To run the test, you can click the green triangle beside the method or the class name. Clicking the green triangle beside the class name will run all the test methods in that class, while the one beside a method will run the test only for that method. 

MainActivityTest class

Hooray! Our test passed!

Android Studio test result toolbar

Perform Actions on a View

On a ViewInteraction object which is returned by calling onView(), we can simulate actions a user can perform on a widget. For example, we can simulate a click action by simply calling the click() static method inside the ViewActions class. This will return a ViewAction object for us. 

The documentation says that ViewAction is:

Responsible for performing an interaction on the given View element.

We perform a click event by first calling perform(). This method performs the given action(s) on the view selected by the current view matcher. Note that we can pass it a single action or a list of actions (executed in order). Here, we gave it click(). Other possible actions are:

  • typeText() to imitate typing text into an EditText.
  • clearText() to simulate clearing text in an EditText.
  • doubleClick() to simulate double-clicking a View.
  • longClick() to imitate long-clicking a View.
  • scrollTo() to simulate scrolling a ScrollView to a particular View that is visible. 
  • swipeLeft() to simulate swiping right to left across the vertical center of a View.

Many more simulations can be found inside the ViewActions class

Validate With View Assertions

Let's complete our test, to validate that the LoginActivity screen is shown whenever the Login button is clicked. Though we have already seen how to use check() on a ViewInteraction, let's use it again, passing it another ViewAssertion

Inside the LoginActivity layout file, apart from EditTexts and a Button, we also have a TextView with ID R.id.tv_login. So we simply do a check to confirm that the TextView is visible to the user. 

Now you can run the test again!

Android Studio test result toolbar

Your tests should pass successfully if you followed all the steps correctly. 

Here's what happened during the process of executing our tests: 

  1. Launched the MainActivity using the activityRule field.
  2. Verified if the Login button (R.id.btn_login) was visible (isDisplayed()) to the user.
  3. Simulated a click action (click()) on that button.
  4. Verified if the LoginActivity was shown to the user by checking if a TextView with id R.id.tv_login in the LoginActivity is visible.

You can always refer to the Espresso cheat sheet to see the different view matchers, view actions, and view assertions available. 

6. Test the LoginActivity Screen

Here's our LoginActivity.kt:

In the code above, if the entered username is "chike" and the password is "password", then the login is successful. For any other input, it's a failure. Let's now write an Espresso test for this!

Go to LoginActivity.kt, move the cursor to the LoginActivity name, and press Shift-Control-T. Select Create New Test... in the popup menu. Follow the same process as we did for MainActivity.kt, and click the OK button. 

This test class is very similar to our first one. If we run the test, our LoginActivity screen is opened. The username and password are typed into the R.id.et_username and R.id.et_password fields respectively. Next, Espresso will click the Submit button (R.id.btn_submit). It will wait until a View with id R.id.tv_login can be found with text reading Success

7. Test a RecyclerView

RecyclerViewActions is the class that exposes a set of APIs to operate on a RecyclerView. RecyclerViewActions is part of a separate artifact inside the espresso-contrib artifact, which also should be added to build.gradle:

Note that this artifact also contains the API for UI testing the navigation drawer through DrawerActions and DrawerMatchers

To click on an item at any position in a RecyclerView, we invoke actionOnItemAtPosition(). We have to give it a type of item. In our case, the item is the ViewHolder class inside our RandomAdapter. This method also takes in two parameters; the first is the position, and the second is the action (ViewActions.click()). 

Other RecyclerViewActions that can be performed are:

  • actionOnHolderItem(): performs a ViewAction on a view matched by viewHolderMatcher. This allows us to match it by what's contained inside the ViewHolder rather than the position. 
  • scrollToPosition(): returns a ViewAction which scrolls RecyclerView to a position.

Next (once the "add note screen" is open), we will enter our note text and save the note. We don't need to wait for the new screen to open—Espresso will do this automatically for us. It waits until a View with the id R.id.add_note_title can be found.

8. Test Intents

Espresso makes use of another artifact named espresso-intents for testing intents. This artifact is just another extension to Espresso that focuses on the validation and mocking of Intents. Let's look at an example.

First, we have to pull the espresso-intents library into our project. 

IntentsTestRule extends ActivityTestRule, so they both have similar behaviours. Here's what the doc says:

This class is an extension of ActivityTestRule, which initializes Espresso-Intents before each test annotated with Test and releases Espresso-Intents after each test run. The Activity will be terminated after each test and this rule can be used in the same way as ActivityTestRule.

The main differentiating feature is that it has additional functionalities for testing startActivity() and startActivityForResult() with mocks and stubs. 

We are now going to test a scenario where a user will click on a button (R.id.btn_select_contact) on the screen to pick a contact from the phone's contact list. 

Here we are using intending() from the espresso-intents library to set up a stub with a mock response for our ACTION_PICK request. Here's what happens in  PickContactActivity.kt when the user clicks the button with id R.id.btn_select_contact to pick a contact.

intending() takes in a Matcher that matches intents for which stubbed response should be provided. In other words, the Matcher identifies which request you're interested in stubbing. In our own case, we make use of hasAction() (a helper method in IntentMatchers) to find our ACTION_PICK request. We then invoke respondWith(), which sets the result for onActivityResult(). In our case, the result has Activity.RESULT_OK, simulating the user selecting a contact from the list. 

We then simulate clicking the select contact button, which calls startActivityForResult(). Note that our stub sent the mock response to onActivityResult()

Finally, we use the intended() helper method to simply validate that the calls to startActivity() and startActivityForResult() were made with the right information. 

Conclusion

In this tutorial, you learned how to easily use the Espresso testing framework in your Android Studio project to automate your test workflow. 

I highly recommend checking out the official documentation to learn more about writing UI tests with Espresso. 

2018-09-17T12:53:38.000Z2018-09-17T12:53:38.000ZChike Mgbemena

Testing Android User Interfaces With Espresso

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

In this post, you'll learn about how to write UI tests with the Espresso testing framework and automate your test workflow, instead of using the tedious and highly error-prone manual process. 

Espresso is a testing framework for writing UI tests in Android. According to the official docs, you can:

Use Espresso to write concise, beautiful, and reliable Android UI tests.

1. Why Use Espresso?

One of the problems with manual testing is that it can be time-consuming and tedious to perform. For example, to test a login screen (manually) in an Android app, you will have to do the following:

  1. Launch the app. 
  2. Navigate to the login screen. 
  3. Confirm if the usernameEditText and passwordEditText are visible. 
  4. Type the username and password into their respective fields. 
  5. Confirm if the login button is also visible, and then click on that login button.
  6. Check if the correct views are displayed when that login was successful or was a failure. 

Instead of spending all this time manually testing our app, it would be better to spend more time writing code that makes our app stand out from the rest! And, even though manual testing is tedious and quite slow, it is still error-prone and you might miss some corner cases. 

Some of the advantages of automated testing include the following:   

  • Automated tests execute exactly the same test cases every time they are executed. 
  • Developers can quickly spot a problem quickly before it is sent to the QA team. 
  • It can save a lot of time, unlike doing manual testing. By saving time, software engineers and the QA team can instead spend more time on challenging and rewarding tasks. 
  • Higher test coverage is achieved, which leads to a better quality application. 

In this tutorial, we'll learn about Espresso by integrating it into an Android Studio project. We'll write UI tests for a login screen and a RecyclerView, and we'll learn about testing intents. 

Quality is not an act, it is a habit. — Pablo Picasso

2. Prerequisites

To be able to follow this tutorial, you'll need:

A sample project (in Kotlin) for this tutorial can be found on our GitHub repo so you can easily follow along.

3. Create an Android Studio Project

Fire up your Android Studio 3 and create a new project with an empty activity called MainActivity. Make sure to check Include Kotlin support

Create Android Project dialog

4. Set Up Espresso and AndroidJUnitRunner

After creating a new project, make sure to add the following dependencies from the Android Testing Support Library in your build.gradle (although Android Studio has already included them for us). In this tutorial, we are using the latest Espresso library version 3.0.2 (as of this writing). 

We also included the instrumentation runner AndroidJUnitRunner:

An Instrumentation that runs JUnit3 and JUnit4 tests against an Android package (application).

Note that Instrumentation is simply a base class for implementing application instrumentation code. 

Turn Off Animation 

The synchronisation of Espresso, which doesn't know how to wait for an animation to finish, can cause some tests to fail—if you allow animation on your test device. To turn off animation on your test device, go to Settings > Developer Options and turn off all the following options under the "Drawing" section: 

  • Window animation scale
  • Transition animation scale
  • Animator duration scale

5. Write Your First Test in Espresso

First, we start off testing a Login screen. Here's how the login flow starts: the user launches the app, and the first screen shown contains a single Login button. When that Login button is clicked, it opens up the LoginActivity screen. This screen contains just two EditTexts (the username and password fields) and a Submit button. 

Here's what our MainActivity layout looks like:

MainActivity layout

Here's what our LoginActivity layout looks like:

Let's now write a test for our MainActivity class. Go to your MainActivity class, move the cursor to the MainActivity name, and press Shift-Control-T. Select Create New Test... in the popup menu. 

Create new test dialog

Press the OK button, and another dialog shows up. Choose the androidTest directory and click the OK button once more. Note that because we are writing an instrumentation test (Android SDK specific tests), the test cases reside in the androidTest/java folder. 

Now, Android Studio has successfully created a test class for us. Above the class name, include this annotation: @RunWith(AndroidJUnit4::class).

This annotation signifies that all the tests in this class are Android-specific tests.

Testing Activities

Because we want to test an Activity, we have to do a little setup. We need to inform Espresso which Activity to open or launch before executing and destroy after executing any test method. 

Note that the @Rule annotation means that this is a JUnit4 test rule. JUnit4 test rules are run before and after every test method (annotated with @Test). In our own scenario, we want to launch MainActivity before every test method and destroy it after. 

We also included the @JvmField Kotlin annotation. This simply instructs the compiler not to generate getters and setters for the property and instead to expose it as a simple Java field.

Here are the three major steps in writing an Espresso test:

  • Look for the widget (e.g. TextView or Button) you want to test.
  • Perform one or more actions on that widget. 
  • Verify or check to see if that widget is now in a certain state. 

The following types of annotations can be applied to the methods used inside the test class.

  • @BeforeClass: this indicates that the static method this annotation is applied to must be executed once and before all tests in the class. This could be used, for example, to set up a connection to a database. 
  • @Before: indicates that the method this annotation is attached to must be executed before each test method in the class.
  • @Test: indicates that the method this annotation is attached to should run as a test case.
  • @After: indicates that the method this annotation is attached to should run after each test method. 
  • @AfterClass: indicates that the method this annotation is attached to should run after all the test methods in the class have been run. Here, we typically close out resources that were opened in @BeforeClass

Find a View Using onView()

In our MainActivity layout file, we just have one widget—the Login button. Let's test a scenario where a user will find that button and click on it.

To find widgets in Espresso, we make use of the onView() static method (instead of findViewById()). The parameter type we supply to onView() is a Matcher. Note that the Matcher API doesn't come from the Android SDK but instead from the Hamcrest Project. Hamcrest's matcher library is inside the Espresso library we pulled via Gradle. 

The onView(withId(R.id.btn_login)) will return a ViewInteraction that is for a View whose ID is R.id.btn_login. In the example above, we used withId() to look for a widget with a given id. Other view matchers we can use are: 

  • withText(): returns a matcher that matches TextView based on its text property value.
  • withHint(): returns a matcher that matches TextView based on its hint property value.
  • withTagKey(): returns a matcher that matches View based on tag keys.
  • withTagValue(): returns a matcher that matches Views based on tag property values.

First, let's test to see if the button is actually displayed on the screen. 

Here, we are just confirming if the button with the given id (R.id.btn_login) is visible to the user, so we use the check() method to confirm if the underlying View has a certain state—in our case, if it is visible.

The matches() static method returns a generic ViewAssertion that asserts that a view exists in the view hierarchy and is matched by the given view matcher. That given view matcher is returned by calling isDisplayed(). As suggested by the method name, isDisplayed() is a matcher that matches Views that are currently displayed on the screen to the user. For example, if we want to check if a button is enabled, we simply pass isEnabled() to matches()

Other popular view matchers we can pass into the matches() method are:

  • hasFocus(): returns a matcher that matches Views that currently have focus.
  • isChecked(): returns a matcher that accepts if and only if the view is a CompoundButton (or subtype of) and is in checked state. The opposite of this method is isNotChecked()
  • isSelected(): returns a matcher that matches Views that are selected.

To run the test, you can click the green triangle beside the method or the class name. Clicking the green triangle beside the class name will run all the test methods in that class, while the one beside a method will run the test only for that method. 

MainActivityTest class

Hooray! Our test passed!

Android Studio test result toolbar

Perform Actions on a View

On a ViewInteraction object which is returned by calling onView(), we can simulate actions a user can perform on a widget. For example, we can simulate a click action by simply calling the click() static method inside the ViewActions class. This will return a ViewAction object for us. 

The documentation says that ViewAction is:

Responsible for performing an interaction on the given View element.

We perform a click event by first calling perform(). This method performs the given action(s) on the view selected by the current view matcher. Note that we can pass it a single action or a list of actions (executed in order). Here, we gave it click(). Other possible actions are:

  • typeText() to imitate typing text into an EditText.
  • clearText() to simulate clearing text in an EditText.
  • doubleClick() to simulate double-clicking a View.
  • longClick() to imitate long-clicking a View.
  • scrollTo() to simulate scrolling a ScrollView to a particular View that is visible. 
  • swipeLeft() to simulate swiping right to left across the vertical center of a View.

Many more simulations can be found inside the ViewActions class

Validate With View Assertions

Let's complete our test, to validate that the LoginActivity screen is shown whenever the Login button is clicked. Though we have already seen how to use check() on a ViewInteraction, let's use it again, passing it another ViewAssertion

Inside the LoginActivity layout file, apart from EditTexts and a Button, we also have a TextView with ID R.id.tv_login. So we simply do a check to confirm that the TextView is visible to the user. 

Now you can run the test again!

Android Studio test result toolbar

Your tests should pass successfully if you followed all the steps correctly. 

Here's what happened during the process of executing our tests: 

  1. Launched the MainActivity using the activityRule field.
  2. Verified if the Login button (R.id.btn_login) was visible (isDisplayed()) to the user.
  3. Simulated a click action (click()) on that button.
  4. Verified if the LoginActivity was shown to the user by checking if a TextView with id R.id.tv_login in the LoginActivity is visible.

You can always refer to the Espresso cheat sheet to see the different view matchers, view actions, and view assertions available. 

6. Test the LoginActivity Screen

Here's our LoginActivity.kt:

In the code above, if the entered username is "chike" and the password is "password", then the login is successful. For any other input, it's a failure. Let's now write an Espresso test for this!

Go to LoginActivity.kt, move the cursor to the LoginActivity name, and press Shift-Control-T. Select Create New Test... in the popup menu. Follow the same process as we did for MainActivity.kt, and click the OK button. 

This test class is very similar to our first one. If we run the test, our LoginActivity screen is opened. The username and password are typed into the R.id.et_username and R.id.et_password fields respectively. Next, Espresso will click the Submit button (R.id.btn_submit). It will wait until a View with id R.id.tv_login can be found with text reading Success

7. Test a RecyclerView

RecyclerViewActions is the class that exposes a set of APIs to operate on a RecyclerView. RecyclerViewActions is part of a separate artifact inside the espresso-contrib artifact, which also should be added to build.gradle:

Note that this artifact also contains the API for UI testing the navigation drawer through DrawerActions and DrawerMatchers

To click on an item at any position in a RecyclerView, we invoke actionOnItemAtPosition(). We have to give it a type of item. In our case, the item is the ViewHolder class inside our RandomAdapter. This method also takes in two parameters; the first is the position, and the second is the action (ViewActions.click()). 

Other RecyclerViewActions that can be performed are:

  • actionOnHolderItem(): performs a ViewAction on a view matched by viewHolderMatcher. This allows us to match it by what's contained inside the ViewHolder rather than the position. 
  • scrollToPosition(): returns a ViewAction which scrolls RecyclerView to a position.

Next (once the "add note screen" is open), we will enter our note text and save the note. We don't need to wait for the new screen to open—Espresso will do this automatically for us. It waits until a View with the id R.id.add_note_title can be found.

8. Test Intents

Espresso makes use of another artifact named espresso-intents for testing intents. This artifact is just another extension to Espresso that focuses on the validation and mocking of Intents. Let's look at an example.

First, we have to pull the espresso-intents library into our project. 

IntentsTestRule extends ActivityTestRule, so they both have similar behaviours. Here's what the doc says:

This class is an extension of ActivityTestRule, which initializes Espresso-Intents before each test annotated with Test and releases Espresso-Intents after each test run. The Activity will be terminated after each test and this rule can be used in the same way as ActivityTestRule.

The main differentiating feature is that it has additional functionalities for testing startActivity() and startActivityForResult() with mocks and stubs. 

We are now going to test a scenario where a user will click on a button (R.id.btn_select_contact) on the screen to pick a contact from the phone's contact list. 

Here we are using intending() from the espresso-intents library to set up a stub with a mock response for our ACTION_PICK request. Here's what happens in  PickContactActivity.kt when the user clicks the button with id R.id.btn_select_contact to pick a contact.

intending() takes in a Matcher that matches intents for which stubbed response should be provided. In other words, the Matcher identifies which request you're interested in stubbing. In our own case, we make use of hasAction() (a helper method in IntentMatchers) to find our ACTION_PICK request. We then invoke respondWith(), which sets the result for onActivityResult(). In our case, the result has Activity.RESULT_OK, simulating the user selecting a contact from the list. 

We then simulate clicking the select contact button, which calls startActivityForResult(). Note that our stub sent the mock response to onActivityResult()

Finally, we use the intended() helper method to simply validate that the calls to startActivity() and startActivityForResult() were made with the right information. 

Conclusion

In this tutorial, you learned how to easily use the Espresso testing framework in your Android Studio project to automate your test workflow. 

I highly recommend checking out the official documentation to learn more about writing UI tests with Espresso. 

2018-09-17T12:53:38.000Z2018-09-17T12:53:38.000ZChike Mgbemena

New eBooks Available for Subscribers

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

Do you want to learn more about big data analytics? How about creating microservices with Kotlin, or learning Node.js development? Our latest batch of eBooks will teach you all you need to know about these topics and more.

New eBooks available

What You’ll Learn

This month, we’ve made eight new eBooks available for Envato Tuts+ subscribers to download. Here’s a summary of what you can learn from them.

1. Security With Go

Security With Go

Go is becoming more and more popular as a language for security experts. Security With Go is the first Golang security book, and it is useful for both blue team and red team applications. With this book, you will learn how to write secure software, monitor your systems, secure your data, attack systems, and extract information.

2. Rust Programming by Example

Rust Programming By Example

Rust is an open source, safe, concurrent, practical language created by Mozilla. It runs blazingly fast, prevents segfaults, and guarantees safety. This book gets you started with essential software development by guiding you through the different aspects of Rust programming. With this approach, you can bridge the gap between learning and implementing immediately.

3. Practical Big Data Analytics

Practical Big Data Analytics

With the help of this guide, you will be able to bridge the gap between the theoretical world of technology with the practical ground reality of building corporate Big Data and data science platforms. You will get hands-on exposure to Hadoop and Spark, build machine learning dashboards using R and R Shiny, create web-based apps using NoSQL databases such as MongoDB, and even learn how to write R code for neural networks.

By the end of the book, you will have a very clear and concrete understanding of what Big Data analytics means, how it drives revenues for organizations, and how you can develop your own Big Data analytics solution using the different tools and methods articulated in this book.

4. Learn iOS 11 Programming With Swift 4

Learn iOS 11 Programming with Swift 4

You want to build iOS applications but where do you start? Forget sifting through tutorials and blog posts—this book is a direct route into iOS development, taking you through the basics and showing you how to put the principles into practice. So take advantage of this developer-friendly guide and start building applications that may just take the App Store by storm!

5. Learning Node.js Development

Learning Nodejs Development

Learning Node.js Development is a practical, project-based book that provides you with everything you need to get started as a Node.js developer. If you are looking to create real-world Node applications, or you want to switch careers or launch a side project to generate some extra income, then you're in the right place. This book has been written around a single goal—turning you into a professional Node developer capable of developing, testing, and deploying real-world production applications.

6. Hands-on Microservices With Kotlin

Hands-On Microservices with Kotlin

Microservices help you design scalable, easy-to-maintain web applications; Kotlin allows you to take advantage of modern idioms to simplify your development and create high-quality services. 

This book guides you in designing and implementing services and producing production-ready, testable, lean code that's shorter and simpler than a traditional Java implementation. Reap the benefits of using the reactive paradigm and take advantage of non-blocking techniques to take your services to the next level in terms of industry standards. 

7. Hands-on Data Structures and Algorithms With JavaScript

Hands-On Data Structures and Algorithms with JavaScript

Do you want to build applications that are high-performing and fast? Are you looking for complete solutions to implement complex data structures and algorithms in a practical way? If either of these questions rings a bell, then this book is for you!

You'll start by building stacks and understanding performance and memory implications. You will learn how to pick the right type of queue for the application. You will then use sets, maps, trees, and graphs to simplify complex applications. You will learn to implement different types of sorting algorithm before gradually calculating and analyzing space and time complexity. Finally, you'll increase the performance of your application using micro optimizations and memory management.

By the end of the book you will have gained the skills and expertise necessary to create and employ various data structures in a way that is demanded by your project or use case.

8. Django RESTful Web Services

Django RESTful Web Services

If you are a Python developer and want to efficiently create RESTful web services with Django for your apps, then this is the right book for you. The book starts off by showing you how to install and configure the environment, required software, and tools to create RESTful web services with Django and the Django REST framework. You then move on to working with advanced serialization and migrations to interact with SQLite and non-SQL data sources, creating API views to process diverse HTTP requests on objects, include security and permissions, and much more. 

By the end of the book, you will be able to build RESTful web services with Django.

Start Reading With a Combined Subscription

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

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

2018-09-19T10:56:52.000Z2018-09-19T10:56:52.000ZAndrew Blackman

10 Best Multi-Purpose Android App Templates

$
0
0

These multi-purpose Android app templates let developers create many kinds of app easily and quickly. That way, you can use the same universal, all-in-one template over and over for different clients and projects.

If you're an experienced coder, one of these templates is a great way to jump-start your next project. And if you don't program at all, you'll find templates here to make it possible to create an Android app without having to code a single line! 

Today, we’ll take a look at the 10 best multi-purpose app templates for Android at CodeCanyon

1. Universal Android App 

Universal Android App template allows developers to create an app for almost any purpose using the template’s dedicated layouts, with different layouts designed for different kinds of content. The template’s "configurator" tool can be used to define the content without you needing to write a single line of code, and the template has tons of built-in features to give you a head start. 

Universal Android App

More features:

  • in-app purchase option
  • AdMob advertising
  • push notifications by OneSignal
  • step-by-step documentation
  • and more

User djcelo says:

“This is one of the best products I’ve bought on the internet. The system and the support are all excellent. I’m very very happy with this product.”

2. Material Design UI

Material Design UI is a stylish Android UI template with five beautiful themes that can be used to make any app project you’re working on more aesthetically appealing. The template themes target social, travel, media, and shopping apps, and there is a universal theme that can be used with a wider variety of apps. The template uses hundreds of UI elements that can be recombined endlessly to create a beautiful and unique looking app.  

Material Design UI

More features:

  • six versions of list view
  • several versions of left menu
  • image galleries
  • five tab themes
  • and more

User MiloDNA says:

“Even when there are various projects in just one, it was easy to use and has all it promises. For me is a great pack of resources, will be very useful for my apps.

3. WebView App

The WebView App template can be used to turn any content on WordPress or other web frameworks into a unique application. In this way, you can use it to create recipe, fashion, photography, video or any other type of app. The app uses Google Analytics to give you key insights that will help you improve your app. 

WebView App

Other features:

  • AdMob (banner and interstitial ad)
  • push notifications
  • pull-to-refresh
  • supports HTML5 videos, YouTube, Vimeo, JW Player
  • and more

User japoloa01 says:

“Great job, very flexible. Approved by Android without problems. Supports HTML5 geolocation.”

4. WP Connect

WP Connect is a multi-purpose native Android app template that allows developers to create media and social media content apps from a WordPress website, YouTube channel, Facebook page, Instagram page, etc. 

Using Material Design, the template provides beautiful layouts that include animations, card layouts, and customisable colours and icons. The template offers a selection of splash screens to showcase your logo and app name when the app opens. 

WP Connect

Other features:

  • AdMob banners 
  • social share
  • in-app video player and media viewer
  • push notifications
  • and more

User iDesignzone says:

“Great template with a lot of features. Very easy to configure and works without any problem.”

5. Video Template for Android

Video Template for Android is a video player which can also be used to create apps for a wide range of video content, such as teaching tutorials, recipes, game guides, etc. The template uses a powerful and responsive admin panel that can manage unlimited categories as well as tracking the most viewed, most liked, and most shared videos.

Video Template for Android

More features:

  • 17 colour themes
  • easy to understand and alter API
  • drawer menu
  • responsive admin panel
  • and more

User shimlapost says:

“Excellent support. Product fulfils my requirement excellently.”

6. Learning App

Learning App is an educational game app template that is designed to be adaptable for children of every age. It can be set up to teach pre-schoolers or elementary school children of different ages and can target the learning of the alphabet, numbers, colours, shapes, maths, science or English, and much more.

Learning App

More features:  

  • easy to re-skin 
  • AdMob integrated 
  • customisable splash screen 
  • full source code
  • and more 

7. Multipurpose Android by Bison Code

With Multipurpose Android by Bison Code, you can create different types of apps using one admin panel, without changing the code. That’s because the code is designed to handle different types of apps automatically. The template specialises in media so you can create news, quotes, video and photo apps with it. 

Multipurpose Android by Bison Code

App features:

  • in-app purchases possible
  • monetise with AdMob
  • let users share content via social media
  • easy to customise
  • and more

User mydigitera says:

“Customer Support is quick to respond. Solid company here, and a great product!”

8. Social Network Multi-Purpose

Social Network Multi-Purpose allows you to create a wide variety of social media apps. You can create apps like Instagram for sharing images or video or both, as well as real-time chat apps, etc. 

Social Network Multi-Purpose

More features:

  • add in-app purchases
  • like post and comment
  • edit and add filters to images
  • send real-time messages
  • and more

User tcheloweber says:

"Excellent Application, with a lot of quality, modern layout and with a service in the very attentive support. Congratulations on the quality and dedication with your customers."

9. MaterialX

MaterialX is a UI template that can support any app project you want to develop. It is specifically designed to make your apps look amazing by providing you with beautiful, ready-to-use materials, so that no matter what app you’re creating, you can implement it in the code. 

MaterialX

More features: 

  • grid, list, and tab views
  • player (media)
  • timeline (social media)
  • shopping (ecommerce)
  • and more

User 8perezm says:

“It's a top-notch library. Really useful for building Android apps. It saved me a massive amount of time. Money well spent.”

10. AppBox Android

AppBox Android is one of the newest app templates in this category and is a bit different from the other app templates featured here in that it is a collection of apps rather than a single multi-purpose app. 

Nevertheless, it fulfills the same function as the other apps on this list in that it provides developers with the flexibility of creating multiple apps for different purposes. The collection featured here will allow you to create a business directory, real estate finder, news, hotel, restaurant ordering, e-commerce, or hotel finder app. 

AppBox Android

More features:

  • lets users share content via social media
  • users can like, mark as favourite, and comment
  • powerful keyword search
  • item detail information
  • and more

Conclusion

These 10 best multi-purpose Android app templates are just a small selection of the hundreds of Android app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-09-19T12:49:15.000Z2018-09-19T12:49:15.000ZNona Blackman

10 Best Multi-Purpose Android App Templates

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

These multi-purpose Android app templates let developers create many kinds of app easily and quickly. That way, you can use the same universal, all-in-one template over and over for different clients and projects.

If you're an experienced coder, one of these templates is a great way to jump-start your next project. And if you don't program at all, you'll find templates here to make it possible to create an Android app without having to code a single line! 

Today, we’ll take a look at the 10 best multi-purpose app templates for Android at CodeCanyon

1. Universal Android App 

Universal Android App template allows developers to create an app for almost any purpose using the template’s dedicated layouts, with different layouts designed for different kinds of content. The template’s "configurator" tool can be used to define the content without you needing to write a single line of code, and the template has tons of built-in features to give you a head start. 

Universal Android App

More features:

  • in-app purchase option
  • AdMob advertising
  • push notifications by OneSignal
  • step-by-step documentation
  • and more

User djcelo says:

“This is one of the best products I’ve bought on the internet. The system and the support are all excellent. I’m very very happy with this product.”

2. Material Design UI

Material Design UI is a stylish Android UI template with five beautiful themes that can be used to make any app project you’re working on more aesthetically appealing. The template themes target social, travel, media, and shopping apps, and there is a universal theme that can be used with a wider variety of apps. The template uses hundreds of UI elements that can be recombined endlessly to create a beautiful and unique looking app.  

Material Design UI

More features:

  • six versions of list view
  • several versions of left menu
  • image galleries
  • five tab themes
  • and more

User MiloDNA says:

“Even when there are various projects in just one, it was easy to use and has all it promises. For me is a great pack of resources, will be very useful for my apps.

3. WebView App

The WebView App template can be used to turn any content on WordPress or other web frameworks into a unique application. In this way, you can use it to create recipe, fashion, photography, video or any other type of app. The app uses Google Analytics to give you key insights that will help you improve your app. 

WebView App

Other features:

  • AdMob (banner and interstitial ad)
  • push notifications
  • pull-to-refresh
  • supports HTML5 videos, YouTube, Vimeo, JW Player
  • and more

User japoloa01 says:

“Great job, very flexible. Approved by Android without problems. Supports HTML5 geolocation.”

4. WP Connect

WP Connect is a multi-purpose native Android app template that allows developers to create media and social media content apps from a WordPress website, YouTube channel, Facebook page, Instagram page, etc. 

Using Material Design, the template provides beautiful layouts that include animations, card layouts, and customisable colours and icons. The template offers a selection of splash screens to showcase your logo and app name when the app opens. 

WP Connect

Other features:

  • AdMob banners 
  • social share
  • in-app video player and media viewer
  • push notifications
  • and more

User iDesignzone says:

“Great template with a lot of features. Very easy to configure and works without any problem.”

5. Video Template for Android

Video Template for Android is a video player which can also be used to create apps for a wide range of video content, such as teaching tutorials, recipes, game guides, etc. The template uses a powerful and responsive admin panel that can manage unlimited categories as well as tracking the most viewed, most liked, and most shared videos.

Video Template for Android

More features:

  • 17 colour themes
  • easy to understand and alter API
  • drawer menu
  • responsive admin panel
  • and more

User shimlapost says:

“Excellent support. Product fulfils my requirement excellently.”

6. Learning App

Learning App is an educational game app template that is designed to be adaptable for children of every age. It can be set up to teach pre-schoolers or elementary school children of different ages and can target the learning of the alphabet, numbers, colours, shapes, maths, science or English, and much more.

Learning App

More features:  

  • easy to re-skin 
  • AdMob integrated 
  • customisable splash screen 
  • full source code
  • and more 

7. Multipurpose Android by Bison Code

With Multipurpose Android by Bison Code, you can create different types of apps using one admin panel, without changing the code. That’s because the code is designed to handle different types of apps automatically. The template specialises in media so you can create news, quotes, video and photo apps with it. 

Multipurpose Android by Bison Code

App features:

  • in-app purchases possible
  • monetise with AdMob
  • let users share content via social media
  • easy to customise
  • and more

User mydigitera says:

“Customer Support is quick to respond. Solid company here, and a great product!”

8. Social Network Multi-Purpose

Social Network Multi-Purpose allows you to create a wide variety of social media apps. You can create apps like Instagram for sharing images or video or both, as well as real-time chat apps, etc. 

Social Network Multi-Purpose

More features:

  • add in-app purchases
  • like post and comment
  • edit and add filters to images
  • send real-time messages
  • and more

User tcheloweber says:

"Excellent Application, with a lot of quality, modern layout and with a service in the very attentive support. Congratulations on the quality and dedication with your customers."

9. MaterialX

MaterialX is a UI template that can support any app project you want to develop. It is specifically designed to make your apps look amazing by providing you with beautiful, ready-to-use materials, so that no matter what app you’re creating, you can implement it in the code. 

MaterialX

More features: 

  • grid, list, and tab views
  • player (media)
  • timeline (social media)
  • shopping (ecommerce)
  • and more

User 8perezm says:

“It's a top-notch library. Really useful for building Android apps. It saved me a massive amount of time. Money well spent.”

10. AppBox Android

AppBox Android is one of the newest app templates in this category and is a bit different from the other app templates featured here in that it is a collection of apps rather than a single multi-purpose app. 

Nevertheless, it fulfills the same function as the other apps on this list in that it provides developers with the flexibility of creating multiple apps for different purposes. The collection featured here will allow you to create a business directory, real estate finder, news, hotel, restaurant ordering, e-commerce, or hotel finder app. 

AppBox Android

More features:

  • lets users share content via social media
  • users can like, mark as favourite, and comment
  • powerful keyword search
  • item detail information
  • and more

Conclusion

These 10 best multi-purpose Android app templates are just a small selection of the hundreds of Android app templates we have available at CodeCanyon, so if none of them quite fits your needs, there are plenty of other great options to choose from.

And if you want to improve your skills building Android apps and templates, then check out some of the ever-so-useful Android tutorials we have on offer.

2018-09-19T12:49:15.000Z2018-09-19T12:49:15.000ZNona Blackman

Securing Communications on Android

$
0
0

With all the recent data breaches, privacy has become an important topic. Almost every app communicates over the network, so it's important to consider the security of user information. In this post, you'll learn the current best practices for securing the communications of your Android app.

Use HTTPS

As you are developing your app, it's best practice to limit your network requests to ones that are essential. For the essential ones, make sure that they're made over HTTPS instead of HTTP. HTTPS is a protocol that encrypts traffic so that it can't easily be intercepted by eavesdroppers. The good thing about Android is that migrating is as simple as changing the URL from http to https

In fact, Android N and higher versions can enforce HTTPS using Android’s Network Security Configuration.

In Android Studio, select the app/res/xml directory for your project. Create the xml directory if it doesn't already exist. Select it and click File > New File. Call it network_security_config.xml. The format for the file is as follows:

To tell Android to use this file, add the name of the file to the application tag in the AndroidManifest.xml file:

Update Crypto Providers

The HTTPS protocol has been exploited several times over the years. When security researchers report vulnerabilities, the defects are often patched. Applying the patches ensures that your app's network connections are using the most updated industry standard protocols. The most recent versions of the protocols contain fewer weaknesses than the previous ones. 

To update the crypto providers, you will need to include Google Play Services. In your module file of build.gradle, add the following line to the dependencies section:

The SafetyNet services API has many more features, including the Safe Browsing API that checks URLs to see if they have been marked as a known threat, and a reCAPTCHA API to protect your app from spammers and other malicious traffic.

After you sync Gradle, you can call the ProviderInstaller's installIfNeededAsync method:

The onProviderInstalled() method is called when the provider is successfully updated, or already up to date. Otherwise, onProviderInstallFailed(int errorCode, Intent recoveryIntent) is called. 

Certificate and Public Key Pinning

When you make an HTTPS connection to a server, a digital certificate is presented by the server and validated by Android to make sure the connection is secure. The certificate may be signed with a certificate from an intermediate certificate authority. This certificate used by the intermediate authority might in turn be signed by another intermediate authority, and so on, which is trustworthy as long as the last certificate is signed by a root certificate authority that is already trusted by Android OS.

If any of the certificates in the chain of trust are not valid, then the connection is not secure. While this is a good system, it's not foolproof. It's possible for an attacker to instruct Android OS to accept custom certificates. Interception proxies can possess a certificate that is trusted, and if the device is controlled by a company, the company may have configured the device to accept its own certificate. These scenarios allow for a “man in the middle” attack, allowing the HTTPS traffic to be decrypted and read. 

Certificate pinning comes to the rescue by checking the server's certificate that is presented against a copy of the expected certificate. This prevents connections from being made when the certificate is different from the expected one.

In order to implement pinning on Android N and higher, you need to add a hash (called pins) of the certificate into the network_security_config.xml file. Here is an example implementation:

To find the pins for a specific site, you can go to SSL Labs, enter the site, and click Submit. Or, if you're developing an app for a company, you can ask the company for it.

Note: If you need to support devices running an OS version older than Android N, you can use the TrustKit library. It utilizes the Network Security Configuration file in exactly the same way.

Sanitization and Validation

With all of the protections so far, your connections should be quite secure. Even so, don't forget about regular programming validation. Blindly trusting data received from the network is not safe. A good programming practice is “design by contract”, where the inputs and outputs of your methods satisfy a contract that defines specific interface expectations. 

For example, if your server is expecting a string of 48 characters or less, make sure that the interface will only return up to and including 48 characters.

If you're only expecting numbers from the server, your inputs should check for this. While this helps to prevent innocent errors, it also reduces the likelihood of injection and memory corruption attacks. This is especially true when that data gets passed to NDK or JNI—native C and C++ code.

The same is true for sending data to the server. Don't blindly send out data, especially if it's user-generated. For example, it's good practice to limit the length of user input, especially if it will be executed by an SQL server or any technology that will run code. 

While securing a server against attacks is beyond the scope of this article, as a mobile developer, you can do your part by removing characters for the language that the server is using. That way, the input is not susceptible to injection attacks. Some examples are stripping quotes, semicolons and slashes when they're not essential for the user input:

If you know exactly the format that is expected, you should check for this. A good example is email validation:

Files can be checked as well. If you're sending a photo to your server, you can check it's a valid photo. The first two bytes and last two bytes are always FF D8 and FF D9 for the JPEG format.

Be careful when displaying an error alert that directly shows a message from the server. Error messages could disclose private debugging or security-related information. The solution is to have the server send an error code that the client looks up to show a predefined message.

Communication With Other Apps

While you're protecting communication to and from the device, it's important to protect IPC as well. There have been cases where developers have left shared files or have implemented sockets to exchange sensitive information. This is not secure. It is better to use Intents. You can send data using an Intent by providing the package name like this:

To broadcast data to more than one app, you should enforce that only apps signed with your signing key will get the data. Otherwise, the information you send can be read by any app that registers to receive the broadcast. Likewise, a malicious app can send a broadcast to your app if you have registered to receive the broadcast. You can use a permission when sending and receiving broadcasts where signature is used as the protectionLevel. You can define a custom permission in the manifest file like this:

Then you can grant the permission like this: 

Both apps need to have the permissions in the manifest file for it to work. To send the broadcast:

Alternatively, you can usesetPackage(String) when sending a broadcast to restrict it to a set of apps matching the specified package. Setting android:exported to false in the manifest file will exclude broadcasts that are received from outside of your app.

End-to-End Encryption

It's important to understand the limits of HTTPS for protecting network communications. In most HTTPS implementations, the encryption is terminated at the server. For example, your connection to a corporation's server may be over HTTPS, but once that traffic hits the server, it is unencrypted. It may then be forwarded to other servers, either by establishing another HTTPS session or by sending it unencrypted. The corporation is able to see the information that has been sent, and in most cases that's a requirement for business operations. However, it also means that the company could pass the information out to third parties unencrypted.

There is a recent trend called "end-to-end encryption" where only the two end communicating devices can read the traffic. A good example is an encrypted chat app where two mobile devices are communicating with each other through a server; only the sender and receiver can read each other's messages.

An analogy to help you understand end-to-end encryption is to imagine that you want someone to send you a message that only you can read. To do this, you provide them with a box with an open padlock on it (the public key) while you keep the padlock key (private key). The user writes a message, puts it in the box, locks the padlock, and sends it back to you. Only you can read the message because you're the only one with the key to unlock the padlock.

With end-to-end encryption, both users send each other their keys. The server only provides a service for communication, but it can't read the content of the communication. While the implementation details are beyond the scope of this article, it's a powerful technology. If you want to learn more about this approach, a great place to start is the GitHub repo for the open-sourced Signal project.

Conclusion

With all the new privacy laws such as GDPR, security is ever more important. It's often a neglected aspect of mobile app development.

In this tutorial, you've covered the security best practices, including using HTTPS, certificate pinning, data sanitization and end-to-end encryption. These best practices should serve as a foundation for security when developing your mobile app. If you have any questions, feel free to leave them below, and while you're here, check out some of my other tutorials about Android app security! 

2018-09-21T13:00:00.000Z2018-09-21T13:00:00.000ZCollin Stuart
Viewing all 1836 articles
Browse latest View live