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

How to Pass Data Between Activities With Android Parcelable

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

Introduction

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

Why Parcelable?

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

Creating the Main Activity and Layout

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

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

It should look like this:

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

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

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

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

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

Create the Book Class

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

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

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

Write to the Parcel

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

Here is how you do it.

Read Data Back From the Parcel

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

Here's how it should look:

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

Parcelable.Creator

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

This binds everything together. Its job is simple—it generates instances of your Parcelable class from a Parcel using the parcel data provided. The creator calls the constructor you defined above, passing it a Parcel object, and the constructor initializes the class attributes.

If your Parcelable class will have child classes, you'll need to take some extra care with the describeContents() method. This will let you identify the specific child class that should be created by the Parcelable.Creator. You can read more about how this works on Stack Overflow.

Book Activity and Layout

Now we can complete our app with the book Activity. Go ahead and create a new empty activity called BookActivity. Make the layout look like what I have below.

In the activity_book.xml, you only need two TextView widgets, which will be used to show the title and author of the books.

Now let's set up our activity. Your activity should already look like this:

In this activity, you want to receive the data that was passed from your main Activity and display it on your views. Thus you will retrieve the instances of your TextView using the id of the TextView set in your layout.

Then, of course, you'll call getIntent() because you will be retrieving data in this activity. The data you will be retrieving are collected from the Book class using getParcelableExtra(). Next, you set the values of the TextViews to the data you collected. Here is how it is done.

Build your application and launch it, and you should see the little beauty you have just built.

The completed app

Conclusion

In this post, you've seen how you can easily move objects from one activity to another. You no longer have to retrieve each data field you passed to the Intent object separately, and you don't have to remember the name that you passed each field under. Not only that, but this process is faster than Java's serialize functionality.

In this tutorial, you have learned how to use Parcelable to pass data from one activity to another. You can dive deeper into Parcelable by checking the official documentation

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

2017-10-02T15:00:00.000Z2017-10-02T15:00:00.000ZChinedu Izuchukwu

Command Line Basics and Useful Tricks With the Terminal

$
0
0

We've all seen that little black icon labeled "Terminal" hidden in a utilities folder on our Mac, but what really is it? Well, it is a very important part of how your computer functions, and it's crucial for you to understand if you want to call yourself a professional developer. 

In this post, we'll go over what the command line is, as well as some commands to get started using it.

About Terminal

What Is Terminal?

Terminal is an interface for you to execute text-based commands, and it gives you direct access to the underlying operating system, via a shell, on your Mac. A long time ago, before computers had graphical user interfaces (GUIs), the only way to operate a computer was through the command line. Needing to run the computer through the command line helped users better understand what was going on inside their computer.

Ever since GUIs became more commonplace, we have almost forgotten about the command line, and the typical Mac user probably doesn't even know that it exists. This may be okay for the layperson, but as software developers, it's still crucial that we know how to use the terminal.

Why Use the Terminal?

Wasn't the whole point of graphical user interfaces to eliminate the need for a command line? Well, not really. There are still several reasons that you should learn how to use the Terminal if you are a developer, or even a user who cares about performance:

  • Certain things simply cannot be done without the command line (especially as a developer). These include installing CocoaPods, using a git repository, and more.
  • You can easily make changes to your computer's settings which would be tedious or even impossible to do using the user interface only.
  • The terminal is very flexible, and once you learn to use it, it is quite simple and straightforward.
  • It is a very direct way of telling your computer what to do, whereas a GUI is akin to controlling the computer from a distance.

Those are just a few of the reasons that the Terminal is still a useful tool today. It's a practical and functional tool to improve and enhance your daily interactions with your computer.

Getting Started

Open Terminal

Terminal is located in your Applications folder within a subfolder called Utilities. If you cannot find it, activate Spotlight search by pressing Command-Spacebar and search for Terminal. Once you have it open, you should see something which looks like this:

Figure 1 New Terminal Window

This is called the "command prompt"—you'll see the current directory, then your username followed by a $.

Executing Commands

To run a command, simply type it in at the command prompt and press Enter. Try it now with the command ls—this will list all the files in the current directory. Often, online instructions will write commands to be entered starting with a $. You don't need to type this out. For example: 

For the command above, you would just type cd ~/Desktop, omitting the $.

Basic Commands Cheat Sheet

Here is a list of some of the basic commands that you'll need to know in order to use the terminal effectively. This is a handy cheat sheet for the most important and most commonly used commands.

Help

  • help—as the name suggests, you can type this command into the Terminal to get a list of different commands.
  • man <command name>—similar to the previous command, this command tells you exactly what a command does (and gives you full documentation) without you having to search Google for it.

File Management

  • ls—lists all of the contents in the current directory. This command comes in handy if you don't want to use the Finder to browse files—you can simply list them using this command in your Terminal.
  • cd <directory name>—this command is used to change directories. If you write cd alone, you will move out of the current directory. After using ls (to see the directories), you can write the name of the directory you want to enter.

Changing Preferences

  • defaults <setting to change>—this command is used to modify default system settings, some of which cannot be changed without using the terminal.
  • caffeinate—as the name suggests, this command is used to prevent your Mac from dimming, turning off, or sleeping. To end this, all you need to do is press Control-C.

Text Editing

  • vim <file name>—this is one of my favorites. You can edit text files using the default TextEdit (or any GUI based editor), but vim is basically a command-line text editor—that is, it works entirely within the terminal.

Networking

  • ping <URL or IP Address>—this command allows you to check the server response time of a specified URL or IP Address. This may not be useful for every developer, but it is nice to know.

Admin

  • sudo <action to perform>—a way to override your user's privileges and become a superuser of the computer. You will be prompted for an admin password when you use it.

In Depth

Now that you know a few of the basic commands, let's go a little bit more in depth to take a closer look at five of the things you can do with the Terminal. 

1. Change the Default Format for Screenshots

We all know about using Command-Option-4 to take screenshots on our Macs. And although it's great that these screenshots are taken in high-quality PNG files, we don't necessarily want 15 MB to 20 MB of our precious storage taken up for every single screenshot. Luckily, you can change this default with the Terminal.

After your prompt (remember, it's that $ sign), type in the following command:

Figure 3 Stress Test

After you press Enter, you will notice that the file type of your screenshots has changed to what you just set it to. You can use any format such as PDF, JPG, and more, but for this example I have used JPG. 

2. Stress Test Your Mac

There is a simple command which many Apple technicians use when your computer is acting up. This command stresses your CPU by simply printing the letter "y" over and over. If you open your Activity Monitor, you will soon see that this process takes up most of your CPU!

In order to do this, after the prompt, all you need to do is type the following command:

This seemingly innocent command will stress your Mac's CPU to the max, and will easily help you check if your computer is crashing under pressure.

3. Stop Your Mac From Sleeping

Isn't it annoying when you are installing or uploading something on your Mac, and your Mac keeps going to sleep? This amusingly named command will make sure that doesn't happen. 

All you need to do is type the following command after the prompt:

Figure 4 Caffeinate

Press Enter, and your Mac won't sleep, dim, or turn off. Once you're ready to disable this, all you need to do is press Control-from the terminal.

4. Show Hidden Files

By default, your computer hides certain important files for its user, but as developers, sometimes we need access to these files. This prevents amateur users from messing with the computer's internal settings, but as developers, we understand how to handle these files.

To make all hidden files visible, enter the following command after the prompt:

And then, type this command to reset Finder after the prompt:

Figure 5 Show Hidden Files

If you want to hide them again, enter the following command after the prompt:

And then reset Finder again:

Figure 6 Hide Hidden Files

5. Downloading Files

We've all gone through the process of downloading files, unzipping them, and using them. But that can be a hassle, especially when you need to do this multiple times. Using the terminal, you can do this with the URL of your download file.

To do this, use the curl command as follows:

This will download the file at the given URL to the current folder.

This is a pretty complicated command, with lots of options, so take a look at the man page for more details. To open the manual page for curl, run the following command:

Conclusion

Although it may seem daunting at first, the command line is an extremely powerful tool that, in some cases, is easier to use than the GUI. I hope you enjoyed this tutorial and found it helpful.

For more about coding for Mac and iOS, check out some of our other tutorials here on Envato Tuts+.

2017-10-03T16:00:00.000Z2017-10-03T16:00:00.000ZVardhan Agrawal

Command Line Basics and Useful Tricks With the Terminal

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

We've all seen that little black icon labeled "Terminal" hidden in a utilities folder on our Mac, but what really is it? Well, it is a very important part of how your computer functions, and it's crucial for you to understand if you want to call yourself a professional developer. 

In this post, we'll go over what the command line is, as well as some commands to get started using it.

About Terminal

What Is Terminal?

Terminal is an interface for you to execute text-based commands, and it gives you direct access to the underlying operating system, via a shell, on your Mac. A long time ago, before computers had graphical user interfaces (GUIs), the only way to operate a computer was through the command line. Needing to run the computer through the command line helped users better understand what was going on inside their computer.

Ever since GUIs became more commonplace, we have almost forgotten about the command line, and the typical Mac user probably doesn't even know that it exists. This may be okay for the layperson, but as software developers, it's still crucial that we know how to use the terminal.

Why Use the Terminal?

Wasn't the whole point of graphical user interfaces to eliminate the need for a command line? Well, not really. There are still several reasons that you should learn how to use the Terminal if you are a developer, or even a user who cares about performance:

  • Certain things simply cannot be done without the command line (especially as a developer). These include installing CocoaPods, using a git repository, and more.
  • You can easily make changes to your computer's settings which would be tedious or even impossible to do using the user interface only.
  • The terminal is very flexible, and once you learn to use it, it is quite simple and straightforward.
  • It is a very direct way of telling your computer what to do, whereas a GUI is akin to controlling the computer from a distance.

Those are just a few of the reasons that the Terminal is still a useful tool today. It's a practical and functional tool to improve and enhance your daily interactions with your computer.

Getting Started

Open Terminal

Terminal is located in your Applications folder within a subfolder called Utilities. If you cannot find it, activate Spotlight search by pressing Command-Spacebar and search for Terminal. Once you have it open, you should see something which looks like this:

Figure 1 New Terminal Window

This is called the "command prompt"—you'll see the current directory, then your username followed by a $.

Executing Commands

To run a command, simply type it in at the command prompt and press Enter. Try it now with the command ls—this will list all the files in the current directory. Often, online instructions will write commands to be entered starting with a $. You don't need to type this out. For example: 

For the command above, you would just type cd ~/Desktop, omitting the $.

Basic Commands Cheat Sheet

Here is a list of some of the basic commands that you'll need to know in order to use the terminal effectively. This is a handy cheat sheet for the most important and most commonly used commands.

Help

  • help—as the name suggests, you can type this command into the Terminal to get a list of different commands.
  • man <command name>—similar to the previous command, this command tells you exactly what a command does (and gives you full documentation) without you having to search Google for it.

File Management

  • ls—lists all of the contents in the current directory. This command comes in handy if you don't want to use the Finder to browse files—you can simply list them using this command in your Terminal.
  • cd <directory name>—this command is used to change directories. If you write cd alone, you will move out of the current directory. After using ls (to see the directories), you can write the name of the directory you want to enter.

Changing Preferences

  • defaults <setting to change>—this command is used to modify default system settings, some of which cannot be changed without using the terminal.
  • caffeinate—as the name suggests, this command is used to prevent your Mac from dimming, turning off, or sleeping. To end this, all you need to do is press Control-C.

Text Editing

  • vim <file name>—this is one of my favorites. You can edit text files using the default TextEdit (or any GUI based editor), but vim is basically a command-line text editor—that is, it works entirely within the terminal.

Networking

  • ping <URL or IP Address>—this command allows you to check the server response time of a specified URL or IP Address. This may not be useful for every developer, but it is nice to know.

Admin

  • sudo <action to perform>—a way to override your user's privileges and become a superuser of the computer. You will be prompted for an admin password when you use it.

In Depth

Now that you know a few of the basic commands, let's go a little bit more in depth to take a closer look at five of the things you can do with the Terminal. 

1. Change the Default Format for Screenshots

We all know about using Command-Option-4 to take screenshots on our Macs. And although it's great that these screenshots are taken in high-quality PNG files, we don't necessarily want 15 MB to 20 MB of our precious storage taken up for every single screenshot. Luckily, you can change this default with the Terminal.

After your prompt (remember, it's that $ sign), type in the following command:

Figure 3 Stress Test

After you press Enter, you will notice that the file type of your screenshots has changed to what you just set it to. You can use any format such as PDF, JPG, and more, but for this example I have used JPG. 

2. Stress Test Your Mac

There is a simple command which many Apple technicians use when your computer is acting up. This command stresses your CPU by simply printing the letter "y" over and over. If you open your Activity Monitor, you will soon see that this process takes up most of your CPU!

In order to do this, after the prompt, all you need to do is type the following command:

This seemingly innocent command will stress your Mac's CPU to the max, and will easily help you check if your computer is crashing under pressure.

3. Stop Your Mac From Sleeping

Isn't it annoying when you are installing or uploading something on your Mac, and your Mac keeps going to sleep? This amusingly named command will make sure that doesn't happen. 

All you need to do is type the following command after the prompt:

Figure 4 Caffeinate

Press Enter, and your Mac won't sleep, dim, or turn off. Once you're ready to disable this, all you need to do is press Control-from the terminal.

4. Show Hidden Files

By default, your computer hides certain important files for its user, but as developers, sometimes we need access to these files. This prevents amateur users from messing with the computer's internal settings, but as developers, we understand how to handle these files.

To make all hidden files visible, enter the following command after the prompt:

And then, type this command to reset Finder after the prompt:

Figure 5 Show Hidden Files

If you want to hide them again, enter the following command after the prompt:

And then reset Finder again:

Figure 6 Hide Hidden Files

5. Downloading Files

We've all gone through the process of downloading files, unzipping them, and using them. But that can be a hassle, especially when you need to do this multiple times. Using the terminal, you can do this with the URL of your download file.

To do this, use the curl command as follows:

This will download the file at the given URL to the current folder.

This is a pretty complicated command, with lots of options, so take a look at the man page for more details. To open the manual page for curl, run the following command:

Conclusion

Although it may seem daunting at first, the command line is an extremely powerful tool that, in some cases, is easier to use than the GUI. I hope you enjoyed this tutorial and found it helpful.

For more about coding for Mac and iOS, check out some of our other tutorials here on Envato Tuts+.

2017-10-03T16:00:00.000Z2017-10-03T16:00:00.000ZVardhan Agrawal

15 Best Android App Templates of 2017

$
0
0

Android app templates have been gaining in popularity over the past few years, and that’s no wonder. They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

App templates are also an indispensable learning tool for novice developers who want to improve their coding skills by studying the building blocks of an app while building their own.

We've combed through the thousands of Android app templates available at CodeCanyon to find the 15 best available.

The templates we’ve chosen reflect the most popular Android app categories. Almost all are made with Android Studio, use Google Material Design, support AdMob, give users the option of removing banners and interstitial ads, and come with step-by-step instructions and/or video tutorials on how to configure the templates from scratch.  

1. Universal Android App

Hands down one of the best and most popular Android app templates is Universal Android App. This awesome app lets users create just about any app they want by pulling in unlimited content from blogs, timelines, feeds, channels, playlists, webpages etc. and easily combining them into one customisable app.

 Universal Android App

The template supports the most popular web content sources, like WordPress, YouTube, Facebook, RSS, etc.

Customers say Universal Android App is “packed with lots of features, easily adaptable” with “good support service from developer”.

2. The City

Cities are complex spaces, and any app that helps locals and visitors alike navigate them is bound to be a hit. The City is a great app template for developers who want to create an app for their city featuring the most interesting sights, the best restaurants, cafés, bars, shops, and more.

The City

All the app data is stored in a local SQLite database, so the app works in offline mode. And the template has some great features: like MapView to show place location, a featured category for recommended places, ability to filter searches, a save history of searches and much more.

Customers say of The City app template: 

The code is very well structured and clean, the documentation is excellent.

3. E-Commerce App

As online shopping becomes more and more popular, e-commerce businesses are constantly working to improve their customer’s online shopping experience. 

The E-Commerce App template aims to make it easy for developers to create efficient and easy to use e-commerce mobile apps. The template allows users to create category and product menus, add currencies and taxes, user profiles and more.

 E-Commerce App

User ManoharOfficial says of the E-commerce App template:  

Awesome and organized code/documentation. Would like to purchase more in the future.

4. Dating App

Love in the 21st century often involves the Internet, and the appropriately named template Dating App is just what you need if you want to try your hand at creating your own app for those looking for love online.

Dating App

Built with Android Studio, the template's notable features include a beautiful gallery and user profiles. Users have the ability to comment, like, reply and send gifts, see potential dates that are nearby, make in-app purchases, send real-time direct messages with photos, and of course can block other users.

Users say of the app: “My app has been updated to Google Play Store and is running fine” and “Very good documentation, easy to setup, perfect code quality, outstanding design.”

5. Universal Android WebView App

There seem to be no end of amazing content-rich websites on the internet, and though most of them are responsive and show well on mobile phones and tablets, some clients will want to convert their sites into beautiful apps that allow their visitors to access key features easily and seamlessly.

Universal Android WebView App

Universal Android WebView App allows developers to do just that. It is compatible with WordPress and other web frameworks, is highly customisable and packed with features, and it supports HTML5, CSS3, JavaScript, jQuery, Bootstrap, and other web technologies.

Customers say Universal Android WebView is a “great template”, with “fast support and excellent documentation”.

6. Store Finder

When you’re out and about and you need to find the closest store to you for a particular item, having a store finder app on your mobile app is a godsend. This kind of indispensability has made the Store Finder app template popular among developers.

Store Finder

Made with Android Studio, the app features a long list of must-have features like voice call, email and SMS integration, Google directions, and social media logins. Users also have the ability to draw in the map, use map pins and share to Facebook and Twitter, and more.

Customer Seolio says of Store Finder, “The app design and code quality is second to none.”

7. Android News App

Android News App template is the go-to template for those looking to create a mobile news app for Android devices. Users can view the latest news in different categories, save articles as favourites, get notified about the latest articles, and more. It comes with an easy-to-use admin dashboard for modifying the news categories and other details.

Android News App

User jadeofheavens says of Android News App: 

5 Stars: not just for the customer support but definitely for the code quality, features and documentation. A person like me who knows nothing about Android Studio made an app within half hour.

8. Android Live TV

The Android Live TV app template allows users to create apps that show live TV on Android devices. The app supports a wide selection of video formats and all streaming protocols. The application is extremely easy to configure, and detailed documentation is provided.

Android Live TV

User kenwenr says of Android Live TV: 

The Application is very good and easy to customize. I had some issue with Google Play Store when it was uploaded, but thanks to the support I was able to fix the problems and now I am LIVE on Play Store.”

9. My Social Network

My Social Network template allows you to create your own personal social network app where you can publish posts, read the posts of friends, have a personal conversation with friends in real time, and more.

My Social Network

User Joespace says of My Social Network: 

Very good app, well coded and well documented. It's easy to install if you follow the steps.

10. FlappyBot

Games are without a doubt one of the most popular app categories on Android devices, and the FlappyBot game app template is one of our most popular games. It's written in Java with Eclipse, and a narrated video tutorial is included for a quick start. The player touches the screen to move the flappy bird up and the aim is to keep it alive as long as possible. The game saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

FlappyBot

The template allows developers to edit the game by adding more obstacle columns, change bird speeds or delays, etc.  

User Neogoapp says of  FlappyBot: “Good documentation and tutorial”.

11. Jumper

Another great game template is the native Android jumping game, Jumper, also written in Java with Eclipse. The aim of the player is to keep the figure jumping as high as possible. This game also saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

Jumper

This game can be re-skinned and edited to add more bars, more special items, more coins, etc.

12. Your Radio App

Your Radio App template allows you to create your own mobile Internet radio-streaming app. With a powerful admin panel, the app can manage unlimited radio stations and categories and supports many formats.

Your Radio App

User Owindrich says of Your Radio App: “Very nice app, works well, lot of options and nice interface.”

13. Cookbook Recipe App

Create your own recipe application with the Cookbook Recipe App template. This native Android app template gives experienced and novice developers alike an easy way to make their own recipe app, as it doesn’t require programming skills and the code is easy to configure and customise.

Cookbook Recipe App

The app has many great built-in features like a drawer menu with categories, shopping list, favourites, a powerful search, Google Analytics, various animations and effects, and more.

Cookbook Recipe App stores recipes in a local SQLite database so users can run the app without an Internet connection.

14. HD Wallpaper

If you’ve been searching for the perfect template to create a great wallpaper app, look no further. The HD Wallpaper app template allows developers to create an app which delivers gorgeous wallpapers and backgrounds to the user’s Android device. 

The app features multiple galleries of high-resolution images, easy tap, swipe and scroll functions, and offline caching of wallpapers.

HD Wallpaper

Users say of HD Wallpaper: “Superb app with good support” and “nice app and good design too”.

15. xMusic

xMusic will appeal to Android developers who are looking for a template to help them create an online-offline music player app. This app plays millions of free songs from SoundCloud via the SoundCloud API, but can switch to music from the user’s own library if they prefer. 

xMusic

Some of the great features the template offers are a powerful Equalizer with many pre-set music styles, support for sleep mode and a number of playlists, a powerful search, and much more.

Reviewers praise the well-written code and excellent support.

Conclusion

These 15 best Android app templates of 2017 are just a small selection of 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.

2017-10-05T09:00:00.000Z2017-10-05T09:00:00.000ZNona Blackman

15 Best Android App Templates of 2017

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

Android app templates have been gaining in popularity over the past few years, and that’s no wonder. They’re a huge time saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

App templates are also an indispensable learning tool for novice developers who want to improve their coding skills by studying the building blocks of an app while building their own.

We've combed through the thousands of Android app templates available at CodeCanyon to find the 15 best available.

The templates we’ve chosen reflect the most popular Android app categories. Almost all are made with Android Studio, use Google Material Design, support AdMob, give users the option of removing banners and interstitial ads, and come with step-by-step instructions and/or video tutorials on how to configure the templates from scratch.  

1. Universal Android App

Hands down one of the best and most popular Android app templates is Universal Android App. This awesome app lets users create just about any app they want by pulling in unlimited content from blogs, timelines, feeds, channels, playlists, webpages etc. and easily combining them into one customisable app.

 Universal Android App

The template supports the most popular web content sources, like WordPress, YouTube, Facebook, RSS, etc.

Customers say Universal Android App is “packed with lots of features, easily adaptable” with “good support service from developer”.

2. The City

Cities are complex spaces, and any app that helps locals and visitors alike navigate them is bound to be a hit. The City is a great app template for developers who want to create an app for their city featuring the most interesting sights, the best restaurants, cafés, bars, shops, and more.

The City

All the app data is stored in a local SQLite database, so the app works in offline mode. And the template has some great features: like MapView to show place location, a featured category for recommended places, ability to filter searches, a save history of searches and much more.

Customers say of The City app template: 

The code is very well structured and clean, the documentation is excellent.

3. E-Commerce App

As online shopping becomes more and more popular, e-commerce businesses are constantly working to improve their customer’s online shopping experience. 

The E-Commerce App template aims to make it easy for developers to create efficient and easy to use e-commerce mobile apps. The template allows users to create category and product menus, add currencies and taxes, user profiles and more.

 E-Commerce App

User ManoharOfficial says of the E-commerce App template:  

Awesome and organized code/documentation. Would like to purchase more in the future.

4. Dating App

Love in the 21st century often involves the Internet, and the appropriately named template Dating App is just what you need if you want to try your hand at creating your own app for those looking for love online.

Dating App

Built with Android Studio, the template's notable features include a beautiful gallery and user profiles. Users have the ability to comment, like, reply and send gifts, see potential dates that are nearby, make in-app purchases, send real-time direct messages with photos, and of course can block other users.

Users say of the app: “My app has been updated to Google Play Store and is running fine” and “Very good documentation, easy to setup, perfect code quality, outstanding design.”

5. Universal Android WebView App

There seem to be no end of amazing content-rich websites on the internet, and though most of them are responsive and show well on mobile phones and tablets, some clients will want to convert their sites into beautiful apps that allow their visitors to access key features easily and seamlessly.

Universal Android WebView App

Universal Android WebView App allows developers to do just that. It is compatible with WordPress and other web frameworks, is highly customisable and packed with features, and it supports HTML5, CSS3, JavaScript, jQuery, Bootstrap, and other web technologies.

Customers say Universal Android WebView is a “great template”, with “fast support and excellent documentation”.

6. Store Finder

When you’re out and about and you need to find the closest store to you for a particular item, having a store finder app on your mobile app is a godsend. This kind of indispensability has made the Store Finder app template popular among developers.

Store Finder

Made with Android Studio, the app features a long list of must-have features like voice call, email and SMS integration, Google directions, and social media logins. Users also have the ability to draw in the map, use map pins and share to Facebook and Twitter, and more.

Customer Seolio says of Store Finder, “The app design and code quality is second to none.”

7. Android News App

Android News App template is the go-to template for those looking to create a mobile news app for Android devices. Users can view the latest news in different categories, save articles as favourites, get notified about the latest articles, and more. It comes with an easy-to-use admin dashboard for modifying the news categories and other details.

Android News App

User jadeofheavens says of Android News App: 

5 Stars: not just for the customer support but definitely for the code quality, features and documentation. A person like me who knows nothing about Android Studio made an app within half hour.

8. Android Live TV

The Android Live TV app template allows users to create apps that show live TV on Android devices. The app supports a wide selection of video formats and all streaming protocols. The application is extremely easy to configure, and detailed documentation is provided.

Android Live TV

User kenwenr says of Android Live TV: 

The Application is very good and easy to customize. I had some issue with Google Play Store when it was uploaded, but thanks to the support I was able to fix the problems and now I am LIVE on Play Store.”

9. My Social Network

My Social Network template allows you to create your own personal social network app where you can publish posts, read the posts of friends, have a personal conversation with friends in real time, and more.

My Social Network

User Joespace says of My Social Network: 

Very good app, well coded and well documented. It's easy to install if you follow the steps.

10. FlappyBot

Games are without a doubt one of the most popular app categories on Android devices, and the FlappyBot game app template is one of our most popular games. It's written in Java with Eclipse, and a narrated video tutorial is included for a quick start. The player touches the screen to move the flappy bird up and the aim is to keep it alive as long as possible. The game saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

FlappyBot

The template allows developers to edit the game by adding more obstacle columns, change bird speeds or delays, etc.  

User Neogoapp says of  FlappyBot: “Good documentation and tutorial”.

11. Jumper

Another great game template is the native Android jumping game, Jumper, also written in Java with Eclipse. The aim of the player is to keep the figure jumping as high as possible. This game also saves the top ten high scores on the user’s device, and users can share their scores on Facebook.

Jumper

This game can be re-skinned and edited to add more bars, more special items, more coins, etc.

12. Your Radio App

Your Radio App template allows you to create your own mobile Internet radio-streaming app. With a powerful admin panel, the app can manage unlimited radio stations and categories and supports many formats.

Your Radio App

User Owindrich says of Your Radio App: “Very nice app, works well, lot of options and nice interface.”

13. Cookbook Recipe App

Create your own recipe application with the Cookbook Recipe App template. This native Android app template gives experienced and novice developers alike an easy way to make their own recipe app, as it doesn’t require programming skills and the code is easy to configure and customise.

Cookbook Recipe App

The app has many great built-in features like a drawer menu with categories, shopping list, favourites, a powerful search, Google Analytics, various animations and effects, and more.

Cookbook Recipe App stores recipes in a local SQLite database so users can run the app without an Internet connection.

14. HD Wallpaper

If you’ve been searching for the perfect template to create a great wallpaper app, look no further. The HD Wallpaper app template allows developers to create an app which delivers gorgeous wallpapers and backgrounds to the user’s Android device. 

The app features multiple galleries of high-resolution images, easy tap, swipe and scroll functions, and offline caching of wallpapers.

HD Wallpaper

Users say of HD Wallpaper: “Superb app with good support” and “nice app and good design too”.

15. xMusic

xMusic will appeal to Android developers who are looking for a template to help them create an online-offline music player app. This app plays millions of free songs from SoundCloud via the SoundCloud API, but can switch to music from the user’s own library if they prefer. 

xMusic

Some of the great features the template offers are a powerful Equalizer with many pre-set music styles, support for sleep mode and a number of playlists, a powerful search, and much more.

Reviewers praise the well-written code and excellent support.

Conclusion

These 15 best Android app templates of 2017 are just a small selection of 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.

2017-10-05T09:00:00.000Z2017-10-05T09:00:00.000ZNona Blackman

What’s New in Xcode 9?

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

This year’s WWDC announcements focused on the exciting new SDKs, such as ARKit, and the changes to iOS 11. However, Apple has also made significant improvements to Xcode with Xcode 9. Not to be outshone by the other announcements, the new version of Xcode is a leap forward for coders. Developers are sure to be happy!

Included in this year’s improvements:

  • updated support for Swift 4, including parallel support for Swift 4.0 and 3.2
  • super-charged speed improvements to Xcode Project Navigator and Editor, from indexing to refactoring tools
  • a completely rebuilt source code management (SCM) component, with seamless Git and GitHub integration
  • ability to run multiple concurrent simulators, as well as wirelessly debug on physical devices such as the iPhone and Apple TV
  • a new Main Thread Checker tool to ensure UIKit and AppKit thread compliance
  • improved Interface Builder rendering of UI components.

Certainly this is a very exciting list of changes, so let’s go them one by one, starting with Swift 4.

Support for Swift 4

Swift is steadily evolving year over year, and this year Xcode is supporting the latest major Swift release, Swift 4. While the latest open-source iteration isn’t as big a jump as the previous versions were, Xcode 9 has made the process even more convenient. 

For starters, Xcode 9 now supports the ability to compile both Swift 4.0 and Swift 3.2 targets simultaneously, meaning that as a developer, you can choose to migrate your project gradually rather than all at once, and you can have your project targets written in either the latest or previous language version.

Picking a Swift language version

Xcode 9's compiler understands both versions, and through the Xcode Migration Assistant, will now ask users to cherry-pick which targets to migrate to version 4.0. 

In fact, Xcode 9 evaluates your code and provides insights into your project modernization compliance status and best practices, through the Editor > Validate menu option. 

Selecting targets to convert

Project Navigator and Editor Improvements

Next up, Xcode 9 gets some needed improvements to the IDE itself—in particular to the Project Navigator and Source Editor components, starting with a faster indexing engine that supercharges your ability to search and returns results quicker. 

Developers can search a large code base and get results instantly, since the indexing engine now also indexes files as they are compiled, whereas previously files in a compilation state were not subject to indexing. This gives developers the ability to quickly jump between and search files from linked projects and libraries seamlessly, a welcome benefit, especially when you work with CocoaPods and multi-project workspaces. 

The Editor itself has also been rebuilt, enabling—as Apple says—a “fast structure-based editor that lets you intelligently highlight and navigate your code”. What this means is a new highlighting engine that recognizes logically grouped blocks better, and that gives you smart tools for navigating between related parts of your codebase.

Xcodes new intelligent highlighting engine

Refactoring

In addition to allowing developers to navigate easily from class to class, or from method to method, Xcode also provides an all-new refactoring feature. The refactoring tool provides a modal editor pane to compare all possible changes as you extract and refactor Swift methods. This makes refactoring easy, even between Swift and Objective-C methods. 

Refactoring preview

You can now update symbols, modify getters and setters, synthesize iVars, and auto-fill mandatory protocol methods for conformance, all with a single click. 

Markdown Editing

Other minor improvements include native support for Markdown files (rendered with the Markdown stylings) in the editor. This improvement makes sense considering Xcode’s deeper integration with GitHub, and it's helpful to be able to access README.md files more visually within the editor. 

Markdown editor

Swift Playgrounds

Xcode 9 also provides new iOS Playground templates that you can actually test out not only in Xcode but also on Swift Playgrounds for iPad!

Swift playgrounds

Other Small Editor Improvements

Also, it's a small improvement, but the editor now lets users increase or decrease the editor font size using the macOS-conforming or shortcuts. 

Font size shortcuts

Another small improvement is with creating, renaming and deleting groups in the Project Navigator. Making changes to a group will now be reflected in the associated folder, ensuring naming consistency and eliminating an annoyance many developers had with how Xcode works with file system folders. 

Finally, improvements to Xcode’s Asset Catalog add support for the new HEIF image open standard that is part of iOS 11.

Source Control Management Improvements 

One of the most notable improvements to Xcode has been with the integrated source control management, which until now had been neglected. In place of the previous semi-baked SCM that never really felt part of Xcode, Xcode 9 now includes a completely revamped SCM integration.

SCM integration

From a new SCM navigator that is more seamlessly integrated, you also get more powerful ways of working with branches and tags. Not only that, but Xcode now features deep integration with GitHub that lets you manage your account directly from Xcode preferences, create GitHub repositories with a single click, and browse public repos from within the editor. 

For a closer look at new SCM features in Xcode 9, check out our post What’s New with Git Support in Xcode 9.

Debugging & Simulator Improvements

Not to be left behind, Debugging got a lot of attention in Xcode 9 as well. We'll start by looking into what’s new in Xcode Simulator.

Xcode Simulator

Previously, when launching Xcode Simulator, you could only launch one Simulator at a time. So, if you had to test on multiple device types, you would have to run each in turn. This made testing slower, whether for manual or automated testing.

This has changed in Xcode 9. Developers can for the first time run multiple Simulators concurrently, with automated testing tools now being able to run tests in parallel. 

Running multiple Simulators

There are a few other minor but useful tweaks to Simulator that Apple has introduced. One is that you can hold down the Option key to close the Simulator window but yet keep it running in the background. You can also start Simulator from the command line, which is useful for automated testing and delivery tools. 

Developers can also record videos of Simulators, in addition to taking screenshots, which is useful for App Store publishing. 

Last but not least, developers graduating from Simulator to testing on real devices no longer need to plug in their devices physically. Apple now lets developers cut the cord and debug iOS and Apple TV devices wirelessly, with a feature called Network Debugging.

Main Thread Checker

A new standalone debug utility Apple has introduced together with Xcode 9, Main Thread Checker is able to detect non-compliant usage of prominent SDKs such as AppKit and UIKit from a background thread. For instance, developers could be using UITableView actions in the background thread, which could result in strange visual effects and faulty updates. The Main Thread Checker is enabled by default and is configurable via the Scheme Editor. 

Built-in Xcode Server

Xcode 9 now has Xcode Server bots built in and standard, eliminating the need for developers to have an installation of macOS Server. This means developers can run Xcode Server bots on any machine and take advantage of continuous integration best practices. 

Interface Builder Improvements

Developers have been seeing gradual changes and improvements to Interface Builder (IB) over the years, with ongoing improvements to the rendering of screens. Xcode 9 continues to refine IB by rendering UI components on the canvas more accurately. Improved components include Navigation, Tab, and the Toolbars. 

Another new feature is that Xcode and IB will now warn developers when view constraints could potentially cause localization problems. For example, you will be alerted when a change to a view could cause words in another language, such as German, to be truncated or clipped. This is certainly going to save a lot of time for developers who support multiple languages. 

Speaking of layouts, Interface Builder now also supports Auto Layout safe-area guides, which are hints that help developers arrange UI elements. This deprecates the top and bottom layout guides in previous versions of Xcode.

Conclusion

The latest installment of Xcode provides a plethora of new features that will improve developer productivity. In tandem with the announcement of Swift 4, Xcode makes migration from Swift 3.2 to the latest version a lot more palatable, thanks to its support for gradual migration. Xcode has also received timely and noticeable speed improvements to search indexing and a completely rebuilt editor which is more contextually aware, with new support for refactoring. 

SCM has now been made a first-class citizen, meaning developers no longer have to toggle between Xcode and a third-party SCM editor for their git-management needs. The simulator has benefited from some of the most notable improvements, with the ability to run multiple concurrent Simulators to test across multiple devices more expeditiously, as well as the convenience of being able to cut the cord and debug on physical devices wirelessly. 

Whereas iOS 11 has invigorated the development community thanks to its exciting new SDK features, Xcode 9 provides the perfect development vehicle for delivering innovation to their users. Stay tuned for some hands-on tutorials about using the new iOS SDKs. And check out some of our other posts on iOS app development!

2017-10-09T15:00:00.000Z2017-10-09T15:00:00.000ZDoron Katz

What’s New in Xcode 9?

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

This year’s WWDC announcements focused on the exciting new SDKs, such as ARKit, and the changes to iOS 11. However, Apple has also made significant improvements to Xcode with Xcode 9. Not to be outshone by the other announcements, the new version of Xcode is a leap forward for coders. Developers are sure to be happy!

Included in this year’s improvements:

  • updated support for Swift 4, including parallel support for Swift 4.0 and 3.2
  • super-charged speed improvements to Xcode Project Navigator and Editor, from indexing to refactoring tools
  • a completely rebuilt source code management (SCM) component, with seamless Git and GitHub integration
  • ability to run multiple concurrent simulators, as well as wirelessly debug on physical devices such as the iPhone and Apple TV
  • a new Main Thread Checker tool to ensure UIKit and AppKit thread compliance
  • improved Interface Builder rendering of UI components.

Certainly this is a very exciting list of changes, so let’s go them one by one, starting with Swift 4.

Support for Swift 4

Swift is steadily evolving year over year, and this year Xcode is supporting the latest major Swift release, Swift 4. While the latest open-source iteration isn’t as big a jump as the previous versions were, Xcode 9 has made the process even more convenient. 

For starters, Xcode 9 now supports the ability to compile both Swift 4.0 and Swift 3.2 targets simultaneously, meaning that as a developer, you can choose to migrate your project gradually rather than all at once, and you can have your project targets written in either the latest or previous language version.

Picking a Swift language version

Xcode 9's compiler understands both versions, and through the Xcode Migration Assistant, will now ask users to cherry-pick which targets to migrate to version 4.0. 

In fact, Xcode 9 evaluates your code and provides insights into your project modernization compliance status and best practices, through the Editor > Validate menu option. 

Selecting targets to convert

Project Navigator and Editor Improvements

Next up, Xcode 9 gets some needed improvements to the IDE itself—in particular to the Project Navigator and Source Editor components, starting with a faster indexing engine that supercharges your ability to search and returns results quicker. 

Developers can search a large code base and get results instantly, since the indexing engine now also indexes files as they are compiled, whereas previously files in a compilation state were not subject to indexing. This gives developers the ability to quickly jump between and search files from linked projects and libraries seamlessly, a welcome benefit, especially when you work with CocoaPods and multi-project workspaces. 

The Editor itself has also been rebuilt, enabling—as Apple says—a “fast structure-based editor that lets you intelligently highlight and navigate your code”. What this means is a new highlighting engine that recognizes logically grouped blocks better, and that gives you smart tools for navigating between related parts of your codebase.

Xcodes new intelligent highlighting engine

Refactoring

In addition to allowing developers to navigate easily from class to class, or from method to method, Xcode also provides an all-new refactoring feature. The refactoring tool provides a modal editor pane to compare all possible changes as you extract and refactor Swift methods. This makes refactoring easy, even between Swift and Objective-C methods. 

Refactoring preview

You can now update symbols, modify getters and setters, synthesize iVars, and auto-fill mandatory protocol methods for conformance, all with a single click. 

Markdown Editing

Other minor improvements include native support for Markdown files (rendered with the Markdown stylings) in the editor. This improvement makes sense considering Xcode’s deeper integration with GitHub, and it's helpful to be able to access README.md files more visually within the editor. 

Markdown editor

Swift Playgrounds

Xcode 9 also provides new iOS Playground templates that you can actually test out not only in Xcode but also on Swift Playgrounds for iPad!

Swift playgrounds

Other Small Editor Improvements

Also, it's a small improvement, but the editor now lets users increase or decrease the editor font size using the macOS-conforming or shortcuts. 

Font size shortcuts

Another small improvement is with creating, renaming and deleting groups in the Project Navigator. Making changes to a group will now be reflected in the associated folder, ensuring naming consistency and eliminating an annoyance many developers had with how Xcode works with file system folders. 

Finally, improvements to Xcode’s Asset Catalog add support for the new HEIF image open standard that is part of iOS 11.

Source Control Management Improvements 

One of the most notable improvements to Xcode has been with the integrated source control management, which until now had been neglected. In place of the previous semi-baked SCM that never really felt part of Xcode, Xcode 9 now includes a completely revamped SCM integration.

SCM integration

From a new SCM navigator that is more seamlessly integrated, you also get more powerful ways of working with branches and tags. Not only that, but Xcode now features deep integration with GitHub that lets you manage your account directly from Xcode preferences, create GitHub repositories with a single click, and browse public repos from within the editor. 

For a closer look at new SCM features in Xcode 9, check out our post What’s New with Git Support in Xcode 9.

Debugging & Simulator Improvements

Not to be left behind, Debugging got a lot of attention in Xcode 9 as well. We'll start by looking into what’s new in Xcode Simulator.

Xcode Simulator

Previously, when launching Xcode Simulator, you could only launch one Simulator at a time. So, if you had to test on multiple device types, you would have to run each in turn. This made testing slower, whether for manual or automated testing.

This has changed in Xcode 9. Developers can for the first time run multiple Simulators concurrently, with automated testing tools now being able to run tests in parallel. 

Running multiple Simulators

There are a few other minor but useful tweaks to Simulator that Apple has introduced. One is that you can hold down the Option key to close the Simulator window but yet keep it running in the background. You can also start Simulator from the command line, which is useful for automated testing and delivery tools. 

Developers can also record videos of Simulators, in addition to taking screenshots, which is useful for App Store publishing. 

Last but not least, developers graduating from Simulator to testing on real devices no longer need to plug in their devices physically. Apple now lets developers cut the cord and debug iOS and Apple TV devices wirelessly, with a feature called Network Debugging.

Main Thread Checker

A new standalone debug utility Apple has introduced together with Xcode 9, Main Thread Checker is able to detect non-compliant usage of prominent SDKs such as AppKit and UIKit from a background thread. For instance, developers could be using UITableView actions in the background thread, which could result in strange visual effects and faulty updates. The Main Thread Checker is enabled by default and is configurable via the Scheme Editor. 

Built-in Xcode Server

Xcode 9 now has Xcode Server bots built in and standard, eliminating the need for developers to have an installation of macOS Server. This means developers can run Xcode Server bots on any machine and take advantage of continuous integration best practices. 

Interface Builder Improvements

Developers have been seeing gradual changes and improvements to Interface Builder (IB) over the years, with ongoing improvements to the rendering of screens. Xcode 9 continues to refine IB by rendering UI components on the canvas more accurately. Improved components include Navigation, Tab, and the Toolbars. 

Another new feature is that Xcode and IB will now warn developers when view constraints could potentially cause localization problems. For example, you will be alerted when a change to a view could cause words in another language, such as German, to be truncated or clipped. This is certainly going to save a lot of time for developers who support multiple languages. 

Speaking of layouts, Interface Builder now also supports Auto Layout safe-area guides, which are hints that help developers arrange UI elements. This deprecates the top and bottom layout guides in previous versions of Xcode.

Conclusion

The latest installment of Xcode provides a plethora of new features that will improve developer productivity. In tandem with the announcement of Swift 4, Xcode makes migration from Swift 3.2 to the latest version a lot more palatable, thanks to its support for gradual migration. Xcode has also received timely and noticeable speed improvements to search indexing and a completely rebuilt editor which is more contextually aware, with new support for refactoring. 

SCM has now been made a first-class citizen, meaning developers no longer have to toggle between Xcode and a third-party SCM editor for their git-management needs. The simulator has benefited from some of the most notable improvements, with the ability to run multiple concurrent Simulators to test across multiple devices more expeditiously, as well as the convenience of being able to cut the cord and debug on physical devices wirelessly. 

Whereas iOS 11 has invigorated the development community thanks to its exciting new SDK features, Xcode 9 provides the perfect development vehicle for delivering innovation to their users. Stay tuned for some hands-on tutorials about using the new iOS SDKs. And check out some of our other posts on iOS app development!

2017-10-09T15:00:00.000Z2017-10-09T15:00:00.000ZDoron Katz

Java 8 for Android: Cleaner Code With Lambda Expressions

$
0
0

Lambda expressions can help you remove boilerplate code from your projects and process huge amounts of data with ease. See how with this in-depth look at the Java 8 features you can start using in your Android projects today. 

Java 8 for Android

Java 8, which debuted way back in March 2014, was a big step forward for the programming language, introducing a list of features that promised to make coding in Java easier and more concise than ever before.

Unfortunately, Android developers wouldn’t feel the benefits of these features for a while, as Google experimented with bringing Java 8 to the Android platform via Jack (Java Android Compiler Kit) before deprecating Jack in favour of supporting Java 8 natively in Android Studio.

Now, with the release of Android Studio 3.0, we finally have a version of the Android toolchain that has built-in support for some of Java 8’s most important features.

In this series, I’m going to show you how to remove a ton of boilerplate code from your projects, process huge amounts of data with ease, and even embrace a more functional style in your Java programing with Java 8. We'll be taking an in-depth look at the Java 8 features that you can start using today.

By the time you’ve completed this series, you’ll be ready to use all of the following Java 8 features in your Android projects:

  • lambda expressions
  • method references
  • default methods
  • static interface methods
  • type annotations
  • repeating annotations
  • functional interfaces
  • the Stream API

In this first post, we’re going to look at the feature that generated the most buzz when Java 8 was first released, and that has the potential to make the most difference to Android developers: lambda expressions.

Preparing Your Development Environment

Before you can start using any Java 8 features, you need to make sure that your development environment is set up to support this version of Java.

If you don’t already have Java 8 installed, then you’ll need to download the latest JDK8 and update Android Studio’s JDK path so that it’s pointing at the JDK8 package:

  • Launch Android Studio.
  • Select File > Project Structure… from the Android Studio toolbar.
  • Update the JDK Location field so that it’s pointing at your newly downloaded JDK8 package.

If you’re not sure what version of Java you have installed, then you can check by opening a Terminal window (if you’re a Mac user), or a Command Prompt (if you’re on Windows) and then running the following command:

If it returns build 1.8 or higher, then you’re good to go!

You’ll also need to have Android Studio 3.0 Preview 1 or higher installed, although to reduce your chances of encountering bugs and other strange behaviour, it’s recommended that you install the latest version of Android Studio 3.0—whether that’s a beta or preview or, ideally, a stable version of Android Studio 3.0 (which wasn’t yet available at the time of writing). 

Next, you’ll need to make some changes to your project’s build.gradle files. Usually, you’ll just need to add a few lines of code specifying that this project should generate Java 8 bytecode. However, if you’ve previously experimented with Java 8 features using the Jack compiler or the popular Retrolambda project, then you’ll need to disable these tools before your project can use the new-and-improved Java 8 support provided by Android’s default toolchain.

In the following sections, I’ll show you how to enable Java 8 support, and how to disable Retrolambda and Jack, if required.

Adding Java 8 Support to a New Project

Assuming that you haven’t previously enabled Jack or added Retrolambda as a project dependency, the first step is opening your project-level build.gradle file and making sure that you’re using version 3.0.0-alpha1 (or higher) of the Gradle for Android plugin:

Next, open every module-level build.gradle file where you want to use Java 8 features, and set the language level of the source code and the version of the generated Java bytecode to JavaVersion.VERSION_1_8:

If You’re Migrating From Jack

The Jack compiler may be deprecated, but as long as it’s enabled, your project is going to use the Java 8 support provided by Jack, rather than the support provided by Android’s default toolchain.

Using a deprecated tool is never a good idea, but there are some additional reasons why you should migrate from the Jack compiler, if you haven’t already.

Firstly, Jack may support a subset of Java 8 features, but unlike the default toolchain it doesn’t support third-party libraries that use these features, so by using Jack you’re immediately limiting your options when it comes to third-party libraries.

Secondly, the Jack compiler takes Java code and converts it directly into dex, without producing any intermediate bytecode. As long as Jack is enabled, you’ll be unable to use any of the tools that rely on this intermediate output, such as annotation processors and bytecode analyzers.

To disable the Jack compiler, open your module-level build.gradle file and remove the jackOptions section, but make sure you leave the compileOptions block intact:

If You’re Migrating From Retrolambda

Similar to Jack, Retrolambda doesn’t support third-party libraries that use Java 8 language features. If your project is set up to use the Retrolambda plugin, then you should remove this plugin so that your project can revert to the default toolchain.

Open your project-level build.gradle file and remove Retrolambda as a project dependency:

Then, remove the Retrolambda plugin from each of your module-level build.gradle files:  

Test Your Java 8 Support

The easiest way of verifying that your project can now support Java 8 is to write a quick lambda expression and see whether your project still compiles.

Add a button to your user interface (or use a button that already exists) and then implement an onClickListener for this button, using a lambda expression. Don’t worry if the following code doesn’t make much sense now—it will by the end of this article!

Test your lambda expression by triggering the Java 8 toast

Check that your project still compiles, either by selecting Sync from the banner that appears, or by selecting Tools > Android > Sync Project with Gradle Files from the Android Studio toolbar.

If Android Studio doesn’t throw any errors, then you’re ready to start using all the features we listed at the start of this article, including lambda expressions!

Why Are Lambda Expressions So Important?

Lambda expressions were easily Java 8’s biggest new feature, and can have a huge impact on the amount of boilerplate code you need to write when creating pretty much any Android app.

Essentially, a lambda expression represents a function that doesn’t belong to any class, and that you can pass around with ease and then execute on demand.

This feature removes a long-standing frustration many Android developers have experienced with Java: as an object-oriented language, passing around blocks of code has always felt more difficult than it should be. For example, if you wanted to create a new thread and then pass some code to that thread, then you’d typically have to instantiate a thread with an anonymous implementation of the Runnable interface—that’s a lot of work just to pass some code! By providing an easy way of passing a function to a method, lambda expressions have the potential to simplify some of the most common tasks that you’ll perform as an Android developer.

Lambda expressions will also be a welcome addition for any Java developers who want to take a more functional approach to their programming. Prior to Java 8, coding in a functional style would inevitably require you to write lots of boilerplate code, but now that you can pass functions around using lambda expressions, writing your Java code in a less object-oriented way doesn’t have to involve writing a ton of anonymous classes.

How Do I Create a Lambda Expression?

You create a lambda expression using the following syntax:

The arrow operator is pretty self-explanatory, but the rules for how you should structure the lambda's argument and expression can vary depending on what you’re trying to achieve, so let’s explore these two elements in more detail.

The Argument

The argument is one or more parameters, which are almost always enclosed in parentheses. Even if your lambda expression doesn’t have any parameters, you’ll still need to supply empty parentheses, for example:

The exception to this rule is when your method has a single parameter with its type inferred, in which case you can omit the parentheses:

You can use multiple parameters in your argument, by separating each parameter with a comma:

Type inference is possible in lambdas, so you can generally omit the data type from your argument. However, if the compiler cannot infer the data type, then you’ll need to add the type in front of your parameter(s):

The Expression Body

The expression body is the code that you want to execute, which can be a single expression or multiple lines of code. If you want to execute multiple lines, then you’ll need to create a statement block by surrounding this section of your code with curly braces:

If your expression returns a value, then it must be returned with a return statement, for example:

Using Lambda Expressions in Your Android Apps

Now we have an overview of the various ways that you can structure a lambda expression, let’s take a look at some of the most common scenarios where you can use lambda expressions in your Android development work.

Lambdas for Event Handling

Your typical Android app has to be able to respond to a wide range of user input events, and lambda expressions can make this event handling much more straightforward.

In the following code, we’re using an anonymous class to create an instance of onClickListener with an overridden onClick method. Chances are, you’ve written this kind of code countless times.

By rewriting the above code with a lambda expression, we can remove all of the following:

  • the class instantiation: new View.OnClickListener()
  • the access modifier, method name, and type: public void onClick(View view)
  • and the parameter types, so you don’t have to write View view

This means that we can implement exactly the same functionality, using a single line:

Lambdas for Multithreading

Multithreading is another common scenario where lambda expressions can help you write cleaner code. By default, Android has a single UI (user interface) thread that’s responsible for handling all user interaction, dispatching events to the appropriate UI widgets, and modifying the user interface. As soon as you block this UI thread with any long-running or intensive operations, your application is going to become unresponsive, and may even trigger Android’s ANR (Application Not Responding) dialog. So creating additional threads and assigning code to run on those threads is often an essential part of Android development.

Prior to Java 8, assigning code to run on an additional thread required you to create an anonymous class that implements the Runnable interface:

Alternatively, you could instantiate a new thread with an anonymous implementation of the Runnable interface:

Replacing this anonymous class with a lambda expression can make this frequently performed task much more concise:

Finally, if you’re using the RxJava or RxAndroid library, then you can use lambda expressions to help you create observables.

Here, we’re creating a simple Observable that emits the hello world stringto all of its Observers:

Using a lambda expression allows you to replace all of that Action1 code with a single line:

Using Lambda Expressions in Your Real-Life Code

After reading all the theory behind a new feature, the next challenge is getting into the habit of actually using this new feature. This can be particularly tough with something like lambdas, which are designed to be used instead of familiar boilerplate code, as there's always the temptation to simply fall back on what you know.

Android Studio has a few features that can help give you that final push to replace familiar-but-clunky code with shiny new lambda expressions.

The first feature is Android Studio’s intent actions menu, which can auto-convert any compatible anonymous class into the equivalent lambda expression. This is perfect if you’re ever unsure about how to write a particular piece of code in a lambda format: simply write it as usual, and then use the intent action menu’s auto-convert feature.

To auto-convert an anonymous class into a lambda expression:

  • Hover your cursor over the anonymous class, and Android Studio should display a tooltip informing you that it can convert this section of code into a lambda expression.
  • Press your Mac’s Alt/Option-Enter keys, or use the Alt-Enter shortcut if you’re a Windows or Linux user.
  • Select the Replace with lambda option from the context menu.

Select Replace with lambda from the context menu that appears

Alternatively, you can use Android Studio’s Inspection tool to flag every anonymous class that you could potentially replace with a lambda expression, across your entire project. You can then either rewrite each anonymous class manually or let Android Studio’s auto-convert feature show you how it’s done.

To highlight every anonymous class that Android Studio could potentially replace with a lambda expression:

  • Select Analyze > Run Inspection by Name from the Android Studio toolbar.
  • In the popup that appears, start typing Anonymous type can be replaced with lambda, and then select this option when it appears in the dropdown menu.

Select Anonymous type can be replaced with lambda from the Enter inspection name popup

  • In the subsequent window, select Whole project to flag every anonymous class across your project. Alternatively, you can specify individual modules or files where Android Studio should run this inspection.
  • Click OK.
  • Select Analyze > Inspect Code from the Android Studio toolbar.

The Inspection Results pane should now appear and display a list of all the anonymous classes that you can replace with a lambda expression. To take a closer look at an anonymous class, simply double-click that class in the Inspection Results window, and Android Studio will open the file and take you to the exact line that contains this particular anonymous class.

To replace the currently selected anonymous class with a lambda expression, give the Replace with lambda button a click.

In the Inspection Results window select the Replace with lambda button

If Android Studio doesn’t open the Inspection Results window automatically, then you can launch it manually by selecting View > Tool Windows > Inspection Results from the Android Studio toolbar. If Inspection Results doesn’t appear in the Tool Windows sub-menu, then you may need to select Analyze > Inspect Code… from the Android Studio toolbar first.

Testing Lambda Expressions

Despite the many benefits that lambda expressions have to offer, there’s one major drawback that you should be aware of before adding them to your code. Since lambdas don’t have a name, you can’t call them directly from your test code, so adding a large number of lambdas to your project can make it more difficult to test.

Ideally, your lambda expressions should be too simple to break, so being unable to unit test them shouldn’t be too big of an issue. However, if you do need to test a lambda, then you can always treat it like a private method and unit test the outcome, rather than the lambda itself. Alternatively, you could refactor the lambda expression into its own method, so you can reference it directly and therefore test it as normal.  

Conclusion

In this first post on Java 8 language features, we looked at how to set up your Android projects to support Java 8, and how to cut down on boilerplate code by replacing anonymous classes with lambda expressions. 

In the next post, I’ll be showing you how to trim even more code from your Android projects by combining lambda expressions with method references, and how you can enhance your interfaces with default and static interface methods.

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

2017-10-11T11:47:29.926Z2017-10-11T11:47:29.926ZJessica Thornsby

Java 8 for Android: Cleaner Code With Lambda Expressions

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

Lambda expressions can help you remove boilerplate code from your projects and process huge amounts of data with ease. See how with this in-depth look at the Java 8 features you can start using in your Android projects today. 

Java 8 for Android

Java 8, which debuted way back in March 2014, was a big step forward for the programming language, introducing a list of features that promised to make coding in Java easier and more concise than ever before.

Unfortunately, Android developers wouldn’t feel the benefits of these features for a while, as Google experimented with bringing Java 8 to the Android platform via Jack (Java Android Compiler Kit) before deprecating Jack in favour of supporting Java 8 natively in Android Studio.

Now, with the release of Android Studio 3.0, we finally have a version of the Android toolchain that has built-in support for some of Java 8’s most important features.

In this series, I’m going to show you how to remove a ton of boilerplate code from your projects, process huge amounts of data with ease, and even embrace a more functional style in your Java programing with Java 8. We'll be taking an in-depth look at the Java 8 features that you can start using today.

By the time you’ve completed this series, you’ll be ready to use all of the following Java 8 features in your Android projects:

  • lambda expressions
  • method references
  • default methods
  • static interface methods
  • type annotations
  • repeating annotations
  • functional interfaces
  • the Stream API

In this first post, we’re going to look at the feature that generated the most buzz when Java 8 was first released, and that has the potential to make the most difference to Android developers: lambda expressions.

Preparing Your Development Environment

Before you can start using any Java 8 features, you need to make sure that your development environment is set up to support this version of Java.

If you don’t already have Java 8 installed, then you’ll need to download the latest JDK8 and update Android Studio’s JDK path so that it’s pointing at the JDK8 package:

  • Launch Android Studio.
  • Select File > Project Structure… from the Android Studio toolbar.
  • Update the JDK Location field so that it’s pointing at your newly downloaded JDK8 package.

If you’re not sure what version of Java you have installed, then you can check by opening a Terminal window (if you’re a Mac user), or a Command Prompt (if you’re on Windows) and then running the following command:

If it returns build 1.8 or higher, then you’re good to go!

You’ll also need to have Android Studio 3.0 Preview 1 or higher installed, although to reduce your chances of encountering bugs and other strange behaviour, it’s recommended that you install the latest version of Android Studio 3.0—whether that’s a beta or preview or, ideally, a stable version of Android Studio 3.0 (which wasn’t yet available at the time of writing). 

Next, you’ll need to make some changes to your project’s build.gradle files. Usually, you’ll just need to add a few lines of code specifying that this project should generate Java 8 bytecode. However, if you’ve previously experimented with Java 8 features using the Jack compiler or the popular Retrolambda project, then you’ll need to disable these tools before your project can use the new-and-improved Java 8 support provided by Android’s default toolchain.

In the following sections, I’ll show you how to enable Java 8 support, and how to disable Retrolambda and Jack, if required.

Adding Java 8 Support to a New Project

Assuming that you haven’t previously enabled Jack or added Retrolambda as a project dependency, the first step is opening your project-level build.gradle file and making sure that you’re using version 3.0.0-alpha1 (or higher) of the Gradle for Android plugin:

Next, open every module-level build.gradle file where you want to use Java 8 features, and set the language level of the source code and the version of the generated Java bytecode to JavaVersion.VERSION_1_8:

If You’re Migrating From Jack

The Jack compiler may be deprecated, but as long as it’s enabled, your project is going to use the Java 8 support provided by Jack, rather than the support provided by Android’s default toolchain.

Using a deprecated tool is never a good idea, but there are some additional reasons why you should migrate from the Jack compiler, if you haven’t already.

Firstly, Jack may support a subset of Java 8 features, but unlike the default toolchain it doesn’t support third-party libraries that use these features, so by using Jack you’re immediately limiting your options when it comes to third-party libraries.

Secondly, the Jack compiler takes Java code and converts it directly into dex, without producing any intermediate bytecode. As long as Jack is enabled, you’ll be unable to use any of the tools that rely on this intermediate output, such as annotation processors and bytecode analyzers.

To disable the Jack compiler, open your module-level build.gradle file and remove the jackOptions section, but make sure you leave the compileOptions block intact:

If You’re Migrating From Retrolambda

Similar to Jack, Retrolambda doesn’t support third-party libraries that use Java 8 language features. If your project is set up to use the Retrolambda plugin, then you should remove this plugin so that your project can revert to the default toolchain.

Open your project-level build.gradle file and remove Retrolambda as a project dependency:

Then, remove the Retrolambda plugin from each of your module-level build.gradle files:  

Test Your Java 8 Support

The easiest way of verifying that your project can now support Java 8 is to write a quick lambda expression and see whether your project still compiles.

Add a button to your user interface (or use a button that already exists) and then implement an onClickListener for this button, using a lambda expression. Don’t worry if the following code doesn’t make much sense now—it will by the end of this article!

Test your lambda expression by triggering the Java 8 toast

Check that your project still compiles, either by selecting Sync from the banner that appears, or by selecting Tools > Android > Sync Project with Gradle Files from the Android Studio toolbar.

If Android Studio doesn’t throw any errors, then you’re ready to start using all the features we listed at the start of this article, including lambda expressions!

Why Are Lambda Expressions So Important?

Lambda expressions were easily Java 8’s biggest new feature, and can have a huge impact on the amount of boilerplate code you need to write when creating pretty much any Android app.

Essentially, a lambda expression represents a function that doesn’t belong to any class, and that you can pass around with ease and then execute on demand.

This feature removes a long-standing frustration many Android developers have experienced with Java: as an object-oriented language, passing around blocks of code has always felt more difficult than it should be. For example, if you wanted to create a new thread and then pass some code to that thread, then you’d typically have to instantiate a thread with an anonymous implementation of the Runnable interface—that’s a lot of work just to pass some code! By providing an easy way of passing a function to a method, lambda expressions have the potential to simplify some of the most common tasks that you’ll perform as an Android developer.

Lambda expressions will also be a welcome addition for any Java developers who want to take a more functional approach to their programming. Prior to Java 8, coding in a functional style would inevitably require you to write lots of boilerplate code, but now that you can pass functions around using lambda expressions, writing your Java code in a less object-oriented way doesn’t have to involve writing a ton of anonymous classes.

How Do I Create a Lambda Expression?

You create a lambda expression using the following syntax:

The arrow operator is pretty self-explanatory, but the rules for how you should structure the lambda's argument and expression can vary depending on what you’re trying to achieve, so let’s explore these two elements in more detail.

The Argument

The argument is one or more parameters, which are almost always enclosed in parentheses. Even if your lambda expression doesn’t have any parameters, you’ll still need to supply empty parentheses, for example:

The exception to this rule is when your method has a single parameter with its type inferred, in which case you can omit the parentheses:

You can use multiple parameters in your argument, by separating each parameter with a comma:

Type inference is possible in lambdas, so you can generally omit the data type from your argument. However, if the compiler cannot infer the data type, then you’ll need to add the type in front of your parameter(s):

The Expression Body

The expression body is the code that you want to execute, which can be a single expression or multiple lines of code. If you want to execute multiple lines, then you’ll need to create a statement block by surrounding this section of your code with curly braces:

If your expression returns a value, then it must be returned with a return statement, for example:

Using Lambda Expressions in Your Android Apps

Now we have an overview of the various ways that you can structure a lambda expression, let’s take a look at some of the most common scenarios where you can use lambda expressions in your Android development work.

Lambdas for Event Handling

Your typical Android app has to be able to respond to a wide range of user input events, and lambda expressions can make this event handling much more straightforward.

In the following code, we’re using an anonymous class to create an instance of onClickListener with an overridden onClick method. Chances are, you’ve written this kind of code countless times.

By rewriting the above code with a lambda expression, we can remove all of the following:

  • the class instantiation: new View.OnClickListener()
  • the access modifier, method name, and type: public void onClick(View view)
  • and the parameter types, so you don’t have to write View view

This means that we can implement exactly the same functionality, using a single line:

Lambdas for Multithreading

Multithreading is another common scenario where lambda expressions can help you write cleaner code. By default, Android has a single UI (user interface) thread that’s responsible for handling all user interaction, dispatching events to the appropriate UI widgets, and modifying the user interface. As soon as you block this UI thread with any long-running or intensive operations, your application is going to become unresponsive, and may even trigger Android’s ANR (Application Not Responding) dialog. So creating additional threads and assigning code to run on those threads is often an essential part of Android development.

Prior to Java 8, assigning code to run on an additional thread required you to create an anonymous class that implements the Runnable interface:

Alternatively, you could instantiate a new thread with an anonymous implementation of the Runnable interface:

Replacing this anonymous class with a lambda expression can make this frequently performed task much more concise:

Finally, if you’re using the RxJava or RxAndroid library, then you can use lambda expressions to help you create observables.

Here, we’re creating a simple Observable that emits the hello world stringto all of its Observers:

Using a lambda expression allows you to replace all of that Action1 code with a single line:

Using Lambda Expressions in Your Real-Life Code

After reading all the theory behind a new feature, the next challenge is getting into the habit of actually using this new feature. This can be particularly tough with something like lambdas, which are designed to be used instead of familiar boilerplate code, as there's always the temptation to simply fall back on what you know.

Android Studio has a few features that can help give you that final push to replace familiar-but-clunky code with shiny new lambda expressions.

The first feature is Android Studio’s intent actions menu, which can auto-convert any compatible anonymous class into the equivalent lambda expression. This is perfect if you’re ever unsure about how to write a particular piece of code in a lambda format: simply write it as usual, and then use the intent action menu’s auto-convert feature.

To auto-convert an anonymous class into a lambda expression:

  • Hover your cursor over the anonymous class, and Android Studio should display a tooltip informing you that it can convert this section of code into a lambda expression.
  • Press your Mac’s Alt/Option-Enter keys, or use the Alt-Enter shortcut if you’re a Windows or Linux user.
  • Select the Replace with lambda option from the context menu.

Select Replace with lambda from the context menu that appears

Alternatively, you can use Android Studio’s Inspection tool to flag every anonymous class that you could potentially replace with a lambda expression, across your entire project. You can then either rewrite each anonymous class manually or let Android Studio’s auto-convert feature show you how it’s done.

To highlight every anonymous class that Android Studio could potentially replace with a lambda expression:

  • Select Analyze > Run Inspection by Name from the Android Studio toolbar.
  • In the popup that appears, start typing Anonymous type can be replaced with lambda, and then select this option when it appears in the dropdown menu.

Select Anonymous type can be replaced with lambda from the Enter inspection name popup

  • In the subsequent window, select Whole project to flag every anonymous class across your project. Alternatively, you can specify individual modules or files where Android Studio should run this inspection.
  • Click OK.
  • Select Analyze > Inspect Code from the Android Studio toolbar.

The Inspection Results pane should now appear and display a list of all the anonymous classes that you can replace with a lambda expression. To take a closer look at an anonymous class, simply double-click that class in the Inspection Results window, and Android Studio will open the file and take you to the exact line that contains this particular anonymous class.

To replace the currently selected anonymous class with a lambda expression, give the Replace with lambda button a click.

In the Inspection Results window select the Replace with lambda button

If Android Studio doesn’t open the Inspection Results window automatically, then you can launch it manually by selecting View > Tool Windows > Inspection Results from the Android Studio toolbar. If Inspection Results doesn’t appear in the Tool Windows sub-menu, then you may need to select Analyze > Inspect Code… from the Android Studio toolbar first.

Testing Lambda Expressions

Despite the many benefits that lambda expressions have to offer, there’s one major drawback that you should be aware of before adding them to your code. Since lambdas don’t have a name, you can’t call them directly from your test code, so adding a large number of lambdas to your project can make it more difficult to test.

Ideally, your lambda expressions should be too simple to break, so being unable to unit test them shouldn’t be too big of an issue. However, if you do need to test a lambda, then you can always treat it like a private method and unit test the outcome, rather than the lambda itself. Alternatively, you could refactor the lambda expression into its own method, so you can reference it directly and therefore test it as normal.  

Conclusion

In this first post on Java 8 language features, we looked at how to set up your Android projects to support Java 8, and how to cut down on boilerplate code by replacing anonymous classes with lambda expressions. 

In the next post, I’ll be showing you how to trim even more code from your Android projects by combining lambda expressions with method references, and how you can enhance your interfaces with default and static interface methods.

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

2017-10-11T11:47:29.926Z2017-10-11T11:47:29.926ZJessica Thornsby

Quick Tip: Theme Android With the Runtime Resource Overlay Framework

$
0
0

Not many know about it, and Google rarely advertises it, but the Android operating system has had a theming framework built into it for a few years now. It's called the Runtime Resource Overlay framework, RRO for short, and it dramatically reduces the effort needed to create custom themes for your phone.

With RRO, you can quickly create themes that can change the look and feel of almost every app that's installed on an Android device. Because Android's system user interface components, including the navigation bar, the status bar, the notifications tray, and the quick settings tray, themselves belong to an app, you can change their looks too. And the best part about it is that you don't have to write any Java code whatsoever.

What's the catch, you ask? Well, the framework can be used only by privileged apps. More specifically, by apps that are installed in a location that can be accessed only by the root user, or by someone who's creating a custom ROM.

In this quick tip, I'll be showing you how to use the framework to create a simple theme that changes the looks of the quick settings tray.

Prerequisites

To be able to follow along, you'll need the following:

  • an Android emulator running Android Marshmallow or higher
  • the latest version of the Android SDK

If you've never used the Android SDK from the command line and are not familiar with Android firmware, reading the following tutorials would be a good idea:

What Does RRO Really Do?

Although an Android app's business logic is written in Java or Kotlin, its user interface is primarily created using XML files. A well-written Android app will have separate XML resources that define its layouts, colors, strings, and attributes. The RRO framework, as its name suggests, lets you overlay those XML resources with your own custom XML resources. It's not limited to just XML resources, though. It also allows you to change an app's drawables and fonts.

An app that uses the RRO framework usually doesn't contain any Java code. It is composed only of XML files and, if necessary, fonts and images. Nevertheless, like all Android apps, it must be a valid and signed APK.

1. Create a New Project

We won't need Android Studio to create a project that uses the RRO framework. For now, all you need is a new project directory and an AndroidManifest.xml file. You are free to create them either with a file explorer or a terminal.

The manifest file must contain the package name of your application, and the package name of the application that you are creating overlays for. Because we want to change the looks of the quick settings tray today, we must use com.android.systemui as the target package name.

At this point, we are ready to start theming the quick settings tray—and any other components of the Android system UI.

2. Create a Theme

To overlay a resource of the target application, your application must have a resource with the same name. For example, if you want to change the colors of the target application, you will usually have to overlay its colors.xml file with your own colors.xml file.

To make things easy for you, the RRO framework doesn't expect the overlay to be comprehensive and capable of handling all the details present in the original resource. In other words, your overlay needs to have only those details that you want to change.

To make things clearer, let's say we want to change the background color of the quick settings tray from the default blue-grey to a deep orange. The value of the color is specified in the res/values/colors.xml file of the system UI app. If you are curious about its contents, you can take a look at the file on the official Android Git repository.

To change the color, you must now create a res/values/colors.xml file in your project.

Inside the colors.xml file, to change the background color of the tray, we must target a color named system_primary_color. Therefore, add the following XML to the file:

It's worth noting that the above XML is no different from the XML you'd use while creating normal apps with Android Studio.

Our simple theme is ready! If you want to, you can add more <color> tags to the file to change other colors of the system UI.

3. Generate an APK

We'll now be using the Android Asset Packaging Tool, aapt for short, which is a part of the Android SDK, to convert our simple project into an APK file that can be used by the Android platform.

To generate the APK, you must simply point aapt to the manifest file, the res directory, and the target platform's android.jar file. Of course, you must also specify the name you want to give to the APK file.

In the above command, you can see that I've chosen to name the APK file myoverlays.apk.u. That's because our APK is currently both unsigned and unaligned.

To sign it, you must use the jarsigner tool. For now, I suggest you sign it with the default Android debug keystore. 

Finally, you must align—and thus optimize—the APK using the zipalign tool. As inputs, the tool expects the names of the unaligned and aligned APKs, along with a number that specifies the alignment boundaries. As of 2017, the number can be nothing else but 4.

4. Install the APK

To install an APK that uses the RRO framework, you must simply place it inside the /system/vendor/overlay directory. The directory, by default, belongs to a read-only filesystem and is only accessible to the root user. If you are a custom ROM developer, or have rooted your Android device, you should have no trouble installing the APK.

In this quick tip, however, I'll be showing you how to install the APK on an emulator. This way, you can test the overlay without jeopardizing your phone.

Start by firing up an emulator in the writable filesystem mode using the emulator command-line tool.

You can now use the adb tool to gain root privileges on the emulator, if you don't have them already.

Next, remount the /system filesystem as writeable, again using adb.

The /system/vendor/overlay directory doesn't exist on the emulator. You must create it manually yourself. The easiest way to do so is by starting a shell on the emulator.

Finally, push the APK to the directory using adb.

Wait for a few seconds for Android to detect and install the APK, and then restart the emulator for the theme to take effect.

After the restart, if you pull down the quick settings tray, you should be able to see the theme in action.

The quick settings tray before and after applying the theme

Conclusion

In this quick tip, you learned how to use the Runtime Resource Overlay framework to create themes for Android. Although the theme we created was extremely simple, you can apply the skills you gained today to create far more complex themes. For example, you can overlay the strings.xml file to change the labels of the UI elements an app displays. Similarly, you can overlay the dimens.xml file to change the sizes of an app's UI elements.

Documentation about the RRO framework is very scarce. Nonetheless, there's a lot you can learn about it by poring over the Android platform's source code.

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

2017-10-12T12:00:00.000Z2017-10-12T12:00:00.000ZAshraff Hathibelagal

Quick Tip: Theme Android With the Runtime Resource Overlay Framework

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

Not many know about it, and Google rarely advertises it, but the Android operating system has had a theming framework built into it for a few years now. It's called the Runtime Resource Overlay framework, RRO for short, and it dramatically reduces the effort needed to create custom themes for your phone.

With RRO, you can quickly create themes that can change the look and feel of almost every app that's installed on an Android device. Because Android's system user interface components, including the navigation bar, the status bar, the notifications tray, and the quick settings tray, themselves belong to an app, you can change their looks too. And the best part about it is that you don't have to write any Java code whatsoever.

What's the catch, you ask? Well, the framework can be used only by privileged apps. More specifically, by apps that are installed in a location that can be accessed only by the root user, or by someone who's creating a custom ROM.

In this quick tip, I'll be showing you how to use the framework to create a simple theme that changes the looks of the quick settings tray.

Prerequisites

To be able to follow along, you'll need the following:

  • an Android emulator running Android Marshmallow or higher
  • the latest version of the Android SDK

If you've never used the Android SDK from the command line and are not familiar with Android firmware, reading the following tutorials would be a good idea:

What Does RRO Really Do?

Although an Android app's business logic is written in Java or Kotlin, its user interface is primarily created using XML files. A well-written Android app will have separate XML resources that define its layouts, colors, strings, and attributes. The RRO framework, as its name suggests, lets you overlay those XML resources with your own custom XML resources. It's not limited to just XML resources, though. It also allows you to change an app's drawables and fonts.

An app that uses the RRO framework usually doesn't contain any Java code. It is composed only of XML files and, if necessary, fonts and images. Nevertheless, like all Android apps, it must be a valid and signed APK.

1. Create a New Project

We won't need Android Studio to create a project that uses the RRO framework. For now, all you need is a new project directory and an AndroidManifest.xml file. You are free to create them either with a file explorer or a terminal.

The manifest file must contain the package name of your application, and the package name of the application that you are creating overlays for. Because we want to change the looks of the quick settings tray today, we must use com.android.systemui as the target package name.

At this point, we are ready to start theming the quick settings tray—and any other components of the Android system UI.

2. Create a Theme

To overlay a resource of the target application, your application must have a resource with the same name. For example, if you want to change the colors of the target application, you will usually have to overlay its colors.xml file with your own colors.xml file.

To make things easy for you, the RRO framework doesn't expect the overlay to be comprehensive and capable of handling all the details present in the original resource. In other words, your overlay needs to have only those details that you want to change.

To make things clearer, let's say we want to change the background color of the quick settings tray from the default blue-grey to a deep orange. The value of the color is specified in the res/values/colors.xml file of the system UI app. If you are curious about its contents, you can take a look at the file on the official Android Git repository.

To change the color, you must now create a res/values/colors.xml file in your project.

Inside the colors.xml file, to change the background color of the tray, we must target a color named system_primary_color. Therefore, add the following XML to the file:

It's worth noting that the above XML is no different from the XML you'd use while creating normal apps with Android Studio.

Our simple theme is ready! If you want to, you can add more <color> tags to the file to change other colors of the system UI.

3. Generate an APK

We'll now be using the Android Asset Packaging Tool, aapt for short, which is a part of the Android SDK, to convert our simple project into an APK file that can be used by the Android platform.

To generate the APK, you must simply point aapt to the manifest file, the res directory, and the target platform's android.jar file. Of course, you must also specify the name you want to give to the APK file.

In the above command, you can see that I've chosen to name the APK file myoverlays.apk.u. That's because our APK is currently both unsigned and unaligned.

To sign it, you must use the jarsigner tool. For now, I suggest you sign it with the default Android debug keystore. 

Finally, you must align—and thus optimize—the APK using the zipalign tool. As inputs, the tool expects the names of the unaligned and aligned APKs, along with a number that specifies the alignment boundaries. As of 2017, the number can be nothing else but 4.

4. Install the APK

To install an APK that uses the RRO framework, you must simply place it inside the /system/vendor/overlay directory. The directory, by default, belongs to a read-only filesystem and is only accessible to the root user. If you are a custom ROM developer, or have rooted your Android device, you should have no trouble installing the APK.

In this quick tip, however, I'll be showing you how to install the APK on an emulator. This way, you can test the overlay without jeopardizing your phone.

Start by firing up an emulator in the writable filesystem mode using the emulator command-line tool.

You can now use the adb tool to gain root privileges on the emulator, if you don't have them already.

Next, remount the /system filesystem as writeable, again using adb.

The /system/vendor/overlay directory doesn't exist on the emulator. You must create it manually yourself. The easiest way to do so is by starting a shell on the emulator.

Finally, push the APK to the directory using adb.

Wait for a few seconds for Android to detect and install the APK, and then restart the emulator for the theme to take effect.

After the restart, if you pull down the quick settings tray, you should be able to see the theme in action.

The quick settings tray before and after applying the theme

Conclusion

In this quick tip, you learned how to use the Runtime Resource Overlay framework to create themes for Android. Although the theme we created was extremely simple, you can apply the skills you gained today to create far more complex themes. For example, you can overlay the strings.xml file to change the labels of the UI elements an app displays. Similarly, you can overlay the dimens.xml file to change the sizes of an app's UI elements.

Documentation about the RRO framework is very scarce. Nonetheless, there's a lot you can learn about it by poring over the Android platform's source code.

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

2017-10-12T12:00:00.000Z2017-10-12T12:00:00.000ZAshraff Hathibelagal

Kotlin From Scratch: Advanced Properties and Classes

$
0
0

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

In the previous article, you learned about classes and objects in Kotlin. In this tutorial, we'll continue to learn more about properties and also look into advanced types of classes in Kotlin by exploring the following:

  • late-initialized properties
  • inline properties 
  • extension properties
  • data, enum, nested, and sealed classes

1. Late-Initialized Properties

We can declare a non-null property in Kotlin as late-initialized. This means that a non-null property won't be initialized at declaration time with a value—actual initialization won't happen via any constructor—but instead, it will be late initialized by a method or dependency injection.

Let's look at an example to understand this unique property modifier. 

In the code above, we declared a mutable nullable repository property which is of type Repository—inside the class Presenter—and we then initialized this property to null during declaration. We have a method initRepository() in the Presenter class that reinitializes this property later with an actual Repository instance. Note that this property can also be assigned a value using a dependency injector like Dagger.     

Now for us to invoke methods or properties on this repository property, we have to do a null check or use the safe call operator. Why? Because the repository property is of nullable type (Repository?).  (If you need a refresher on nullability in Kotlin, kindly visit Nullability, Loops, and Conditions).

To avoid having to do null checks every time we need to invoke a property's method, we can mark that property with the lateinit modifier—this means we have declared that property (which is an instance of another class) as late-initialized (meaning the property will be initialized later).  

Now, as long as we wait until the property has been given a value, we're safe to access the property's methods without doing any null checks. The property initialization can happen either in a setter method or through dependency injection. 

Note that if we try to access methods of the property before it has been initialized, we will get a kotlin.UninitializedPropertyAccessException instead of a NullPointerException. In this case, the exception message will be "lateinit property repository has not been initialized". 

Note also the following restrictions placed when delaying a property initialization with lateinit:

  • It must be mutable (declared with var).
  • The property type cannot be a primitive type—for example, Int, Double, Float, and so on. 
  • The property cannot have a custom getter or setter.

2. Inline Properties

In Advanced Functions, I introduced the inline modifier for higher-order functions—this helps optimize any higher-order functions that accept a lambda as a parameter. 

In Kotlin, we can also use this inline modifier on properties. Using this modifier will optimize access to the property.

Let's see a practical example. 

In the code above, we have a normal property, nickName, that doesn't have the inline modifier.  If we decompile the code snippet, using the Show Kotlin Bytecode feature (if you're in IntelliJ IDEA or Android Studio, use Tools > Kotlin > Show Kotlin Bytecode), we'll see the following Java code:

In the generated Java code above (some elements of the generated code were removed for brevity's sake), you can see that inside the main() method the compiler created a Student object, called the getNickName() method, and then printed its return value.  

Let's now specify the property as inline instead, and compare the generated bytecode.

We just insert the inline modifier before the variable modifier: var or valHere's the bytecode generated for this inline property:

Again some code was removed, but the key thing to note is the main() method. The compiler has copied the property get() function body and pasted it into the call site (this mechanism is similar to inline functions). 

Our code has been optimized because of no need to create an object and call the property getter method. But, as discussed in the inline functions post, we would have a larger bytecode than before—so use with caution. 

Note also that this mechanism will work for properties that don't have a backing field (remember, a backing field is just a field that is used by properties when you want to modify or use that field data). 

3. Extension Properties 

In Advanced Functions I also discussed extension functions—these give us the ability to extend a class with new functionality without having to inherit from that class. Kotlin also provides a similar mechanism for properties, called extension properties

In the Advanced Functions post we defined a uppercaseFirstLetter() extension function with receiver type String. Here, we've converted it into a top-level extension property instead. Note that you have to define a getter method on your property for this to work. 

So with this new knowledge about extension properties, you'll know that if you ever wished that a class should have a property that was not available, you are free to create an extension property of that class. 

4. Data Classes

Let's start off with a typical Java class or POJO (Plain Old Java Object). 

As you can see, we need to explicitly code the class property accessors: the getter and setter, as well as hashcodeequals, and toString methods (though IntelliJ IDEA, Android Studio, or the AutoValue library can help us generate them). We see this kind of boilerplate code mostly in the data layer of a typical Java project. (I removed the field accessors and constructor for brevity's sake). 

The cool thing is that the Kotlin team provided us with the data modifier for classes to eliminate writing these boilerplate.

Let's now write the preceding code in Kotlin instead.

Awesome! We just specify the data modifier before the class keyword to create a data class—just like what we did in our BlogPost Kotlin class above. Now the equalshashcodetoStringcopy, and multiple component methods will be created under the hood for us. Note that a data class can extend other classes (this is a new feature of Kotlin 1.1). 

The equals Method

This method compares two objects for equality, and returns true if they're equal or false otherwise. In other words, it compares if the two class instances contain the same data. 

In Kotlin, using the equality operator == will call the equals method behind the scenes.

The hashCode Method 

This method returns an integer value used for fast storage and retrieval of data stored in a hash-based collection data structure, for example in the HashMap and HashSet collection types.  

The toString Method

This method returns a String representation of an object. 

By just calling the class instance, we get a string object returned to us—Kotlin calls the object toString() under the hood for us. But if we don't put the data keyword in, see what our object string representation would be: 

Much less informative!

The copy Method

This method allows us to create a new instance of an object with all the same property values. In other words, it creates a copy of the object. 

One cool thing about the copy method in Kotlin is the ability to change properties during copying. 

If you're a Java coder, this method is similar to the clone() method you are already familiar with. But the Kotlin copy method has more powerful features. 

Destructive Declaration

In the Person class, we also have two methods auto-generated for us by the compiler because of the data keyword placed in the class. These two methods are prefixed with "component", then followed by a number suffix: component1()component2(). Each of these methods represents the individual properties of the type. Note that the suffix corresponds to the order of the properties declared in the primary constructor.

So, in our example calling component1() will return the first name, and calling component2() will return the last name.

Calling the properties using this style is difficult to understand and read, though, so calling the property name explicitly is much better. However, these implicitly created properties do have a very useful purpose: they let us do a destructuring declaration, in which we can assign each component to a local variable.

What we have done here is to directly assign the first and second properties (firstName and lastName) of the Person type to the variables firstName and lastName respectively. I also discussed this mechanism knows as destructuring declaration in the last section of the Packages and Basic Functions post. 

5. Nested Classes

In the More Fun With Functions post, I told you that Kotlin has support for local or nested functions—a function that is declared inside another function. Well, Kotlin also similarly supports nested classes—a class created inside another class. 

We even call the nested class's public functions as seen below—a nested class in Kotlin is equivalent to a static nested class in Java. Note that nested classes can't store a reference to their outer class. 

We're also free to set the nested class as private—this means we can only create an instance of the NestedClass within the scope of the OuterClass

Inner Class

Inner classes, on the other hand, can reference the outer class it was declared in. To create an inner class, we place the inner keyword before the class keyword in a nested class. 

Here we reference the OuterClass from the InnerClass by using  this@OuterClass.

6. Enum Classes

An enum type declares a set of constants represented by identifiers. This special kind of class is created by the keyword enum that is specified before the class keyword. 

To retrieve an enum value based on its name (just like in Java), we do this:

Or we can use the Kotlin enumValueOf<T>() helper method to access constants in a generic way:

Also, we can get all the values (like for a Java enum) like this:

Finally, we can use the Kotlin enumValues<T>() helper method to get all enum entries in a generic way:

This returns an array containing the enum entries.  

Enum Constructors

Just like a normal class, the enum type can have its own constructor with properties associated to each enum constant. 

In the Country enum type primary constructor, we defined the immutable property callingCodes for each enum constant. In each of the constants, we passed an argument to the constructor. 

We can then access the constants property like this:

7. Sealed Classes

A sealed class in Kotlin is an abstract class (you never intend to create objects from it) which other classes can extend. These subclasses are defined inside the sealed class body—in the same file. Because all of these subclasses are defined inside the sealed class body, we can know all the possible subclasses by simply viewing the file. 

Let's see a practical example. 

To declare a class as sealed, we insert the sealed modifier before the class modifier in the class declaration header—in our case, we declared the Shape class as sealed. A sealed class is incomplete without its subclasses—just like a typical abstract class—so we have to declare the individual subclasses inside the same file (shape.kt in this case). Note that you can't define a subclass of a sealed class from another file. 

In our code above, we have specified that the Shape class can be extended only by the classes CircleTriangle, and Rectangle.

Sealed classes in Kotlin have the following additional rules:

  • We can add the modifier abstract to a sealed class, but this is redundant because sealed classes are abstract by default.
  • Sealed classes cannot have the open or final modifier. 
  • We are also free to declare data classes and objects as subclasses to a sealed class (they still need to be declared in the same file). 
  • Sealed classes are not allowed to have public constructors—their constructors are private by default. 

Classes which extend subclasses of a sealed class can be placed either in the same file or another file. The sealed class subclass has to be marked with the open modifier (you'll learn more about inheritance in Kotlin in the next post). 

A sealed class and its subclasses are really handy in a when expression. For example:

Here the compiler is smart to ensure we covered all possible when cases. That means there is no need to add the else clause. 

If we were to do the following instead:

The code wouldn't compile, because we have not included all possible cases. We'd have the following error:

So we could either include the is Rectangle case or include the else clause to complete the when expression. 

Conclusion

In this tutorial, you learned more about classes in Kotlin. We covered the following about class properties:

  • late initialization
  • inline properties 
  • extension properties

Also, you learned about some cool and advanced classes such as data, enum, nested, and sealed classes. In the next tutorial in the Kotlin From Scratch series, you'll be introduced to interfaces and inheritance in Kotlin. See you soon!

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

2017-10-13T13:00:00.000Z2017-10-13T13:00:00.000ZChike Mgbemena

Kotlin From Scratch: Advanced Properties and Classes

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

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

In the previous article, you learned about classes and objects in Kotlin. In this tutorial, we'll continue to learn more about properties and also look into advanced types of classes in Kotlin by exploring the following:

  • late-initialized properties
  • inline properties 
  • extension properties
  • data, enum, nested, and sealed classes

1. Late-Initialized Properties

We can declare a non-null property in Kotlin as late-initialized. This means that a non-null property won't be initialized at declaration time with a value—actual initialization won't happen via any constructor—but instead, it will be late initialized by a method or dependency injection.

Let's look at an example to understand this unique property modifier. 

In the code above, we declared a mutable nullable repository property which is of type Repository—inside the class Presenter—and we then initialized this property to null during declaration. We have a method initRepository() in the Presenter class that reinitializes this property later with an actual Repository instance. Note that this property can also be assigned a value using a dependency injector like Dagger.     

Now for us to invoke methods or properties on this repository property, we have to do a null check or use the safe call operator. Why? Because the repository property is of nullable type (Repository?).  (If you need a refresher on nullability in Kotlin, kindly visit Nullability, Loops, and Conditions).

To avoid having to do null checks every time we need to invoke a property's method, we can mark that property with the lateinit modifier—this means we have declared that property (which is an instance of another class) as late-initialized (meaning the property will be initialized later).  

Now, as long as we wait until the property has been given a value, we're safe to access the property's methods without doing any null checks. The property initialization can happen either in a setter method or through dependency injection. 

Note that if we try to access methods of the property before it has been initialized, we will get a kotlin.UninitializedPropertyAccessException instead of a NullPointerException. In this case, the exception message will be "lateinit property repository has not been initialized". 

Note also the following restrictions placed when delaying a property initialization with lateinit:

  • It must be mutable (declared with var).
  • The property type cannot be a primitive type—for example, Int, Double, Float, and so on. 
  • The property cannot have a custom getter or setter.

2. Inline Properties

In Advanced Functions, I introduced the inline modifier for higher-order functions—this helps optimize any higher-order functions that accept a lambda as a parameter. 

In Kotlin, we can also use this inline modifier on properties. Using this modifier will optimize access to the property.

Let's see a practical example. 

In the code above, we have a normal property, nickName, that doesn't have the inline modifier.  If we decompile the code snippet, using the Show Kotlin Bytecode feature (if you're in IntelliJ IDEA or Android Studio, use Tools > Kotlin > Show Kotlin Bytecode), we'll see the following Java code:

In the generated Java code above (some elements of the generated code were removed for brevity's sake), you can see that inside the main() method the compiler created a Student object, called the getNickName() method, and then printed its return value.  

Let's now specify the property as inline instead, and compare the generated bytecode.

We just insert the inline modifier before the variable modifier: var or valHere's the bytecode generated for this inline property:

Again some code was removed, but the key thing to note is the main() method. The compiler has copied the property get() function body and pasted it into the call site (this mechanism is similar to inline functions). 

Our code has been optimized because of no need to create an object and call the property getter method. But, as discussed in the inline functions post, we would have a larger bytecode than before—so use with caution. 

Note also that this mechanism will work for properties that don't have a backing field (remember, a backing field is just a field that is used by properties when you want to modify or use that field data). 

3. Extension Properties 

In Advanced Functions I also discussed extension functions—these give us the ability to extend a class with new functionality without having to inherit from that class. Kotlin also provides a similar mechanism for properties, called extension properties

In the Advanced Functions post we defined a uppercaseFirstLetter() extension function with receiver type String. Here, we've converted it into a top-level extension property instead. Note that you have to define a getter method on your property for this to work. 

So with this new knowledge about extension properties, you'll know that if you ever wished that a class should have a property that was not available, you are free to create an extension property of that class. 

4. Data Classes

Let's start off with a typical Java class or POJO (Plain Old Java Object). 

As you can see, we need to explicitly code the class property accessors: the getter and setter, as well as hashcodeequals, and toString methods (though IntelliJ IDEA, Android Studio, or the AutoValue library can help us generate them). We see this kind of boilerplate code mostly in the data layer of a typical Java project. (I removed the field accessors and constructor for brevity's sake). 

The cool thing is that the Kotlin team provided us with the data modifier for classes to eliminate writing these boilerplate.

Let's now write the preceding code in Kotlin instead.

Awesome! We just specify the data modifier before the class keyword to create a data class—just like what we did in our BlogPost Kotlin class above. Now the equalshashcodetoStringcopy, and multiple component methods will be created under the hood for us. Note that a data class can extend other classes (this is a new feature of Kotlin 1.1). 

The equals Method

This method compares two objects for equality, and returns true if they're equal or false otherwise. In other words, it compares if the two class instances contain the same data. 

In Kotlin, using the equality operator == will call the equals method behind the scenes.

The hashCode Method 

This method returns an integer value used for fast storage and retrieval of data stored in a hash-based collection data structure, for example in the HashMap and HashSet collection types.  

The toString Method

This method returns a String representation of an object. 

By just calling the class instance, we get a string object returned to us—Kotlin calls the object toString() under the hood for us. But if we don't put the data keyword in, see what our object string representation would be: 

Much less informative!

The copy Method

This method allows us to create a new instance of an object with all the same property values. In other words, it creates a copy of the object. 

One cool thing about the copy method in Kotlin is the ability to change properties during copying. 

If you're a Java coder, this method is similar to the clone() method you are already familiar with. But the Kotlin copy method has more powerful features. 

Destructive Declaration

In the Person class, we also have two methods auto-generated for us by the compiler because of the data keyword placed in the class. These two methods are prefixed with "component", then followed by a number suffix: component1()component2(). Each of these methods represents the individual properties of the type. Note that the suffix corresponds to the order of the properties declared in the primary constructor.

So, in our example calling component1() will return the first name, and calling component2() will return the last name.

Calling the properties using this style is difficult to understand and read, though, so calling the property name explicitly is much better. However, these implicitly created properties do have a very useful purpose: they let us do a destructuring declaration, in which we can assign each component to a local variable.

What we have done here is to directly assign the first and second properties (firstName and lastName) of the Person type to the variables firstName and lastName respectively. I also discussed this mechanism knows as destructuring declaration in the last section of the Packages and Basic Functions post. 

5. Nested Classes

In the More Fun With Functions post, I told you that Kotlin has support for local or nested functions—a function that is declared inside another function. Well, Kotlin also similarly supports nested classes—a class created inside another class. 

We even call the nested class's public functions as seen below—a nested class in Kotlin is equivalent to a static nested class in Java. Note that nested classes can't store a reference to their outer class. 

We're also free to set the nested class as private—this means we can only create an instance of the NestedClass within the scope of the OuterClass

Inner Class

Inner classes, on the other hand, can reference the outer class it was declared in. To create an inner class, we place the inner keyword before the class keyword in a nested class. 

Here we reference the OuterClass from the InnerClass by using  this@OuterClass.

6. Enum Classes

An enum type declares a set of constants represented by identifiers. This special kind of class is created by the keyword enum that is specified before the class keyword. 

To retrieve an enum value based on its name (just like in Java), we do this:

Or we can use the Kotlin enumValueOf<T>() helper method to access constants in a generic way:

Also, we can get all the values (like for a Java enum) like this:

Finally, we can use the Kotlin enumValues<T>() helper method to get all enum entries in a generic way:

This returns an array containing the enum entries.  

Enum Constructors

Just like a normal class, the enum type can have its own constructor with properties associated to each enum constant. 

In the Country enum type primary constructor, we defined the immutable property callingCodes for each enum constant. In each of the constants, we passed an argument to the constructor. 

We can then access the constants property like this:

7. Sealed Classes

A sealed class in Kotlin is an abstract class (you never intend to create objects from it) which other classes can extend. These subclasses are defined inside the sealed class body—in the same file. Because all of these subclasses are defined inside the sealed class body, we can know all the possible subclasses by simply viewing the file. 

Let's see a practical example. 

To declare a class as sealed, we insert the sealed modifier before the class modifier in the class declaration header—in our case, we declared the Shape class as sealed. A sealed class is incomplete without its subclasses—just like a typical abstract class—so we have to declare the individual subclasses inside the same file (shape.kt in this case). Note that you can't define a subclass of a sealed class from another file. 

In our code above, we have specified that the Shape class can be extended only by the classes CircleTriangle, and Rectangle.

Sealed classes in Kotlin have the following additional rules:

  • We can add the modifier abstract to a sealed class, but this is redundant because sealed classes are abstract by default.
  • Sealed classes cannot have the open or final modifier. 
  • We are also free to declare data classes and objects as subclasses to a sealed class (they still need to be declared in the same file). 
  • Sealed classes are not allowed to have public constructors—their constructors are private by default. 

Classes which extend subclasses of a sealed class can be placed either in the same file or another file. The sealed class subclass has to be marked with the open modifier (you'll learn more about inheritance in Kotlin in the next post). 

A sealed class and its subclasses are really handy in a when expression. For example:

Here the compiler is smart to ensure we covered all possible when cases. That means there is no need to add the else clause. 

If we were to do the following instead:

The code wouldn't compile, because we have not included all possible cases. We'd have the following error:

So we could either include the is Rectangle case or include the else clause to complete the when expression. 

Conclusion

In this tutorial, you learned more about classes in Kotlin. We covered the following about class properties:

  • late initialization
  • inline properties 
  • extension properties

Also, you learned about some cool and advanced classes such as data, enum, nested, and sealed classes. In the next tutorial in the Kotlin From Scratch series, you'll be introduced to interfaces and inheritance in Kotlin. See you soon!

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

2017-10-13T13:00:00.000Z2017-10-13T13:00:00.000ZChike Mgbemena

Java 8 for Android Development: Default and Static Methods

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

Java 8 was a huge step forward for the programming language and now, with the release of Android Studio 3.0, Android developers finally have access to built-in support for some of Java 8’s most important features.

In this three-part series, we’ve been exploring the Java 8 features you can start using in your Android projects today. In Cleaner Code With Lambda Expressions, we set up our development to use the Java 8 support provided by Android’s default toolchain, before taking an in-depth look at lambda expressions.

In this post, we’ll look at two different ways that you can declare non-abstract methods in your interfaces (something that wasn’t possible in earlier versions of Java). We'll also answer the question of, now that interfaces can implement methods, what exactly is the difference between abstract classes and interfaces?

We’ll also be covering a Java 8 feature that gives you the freedom to use the same annotation as many times as you want in the same location, while remaining backwards compatible with earlier versions of Android.

But first, let’s take a look at a Java 8 feature that’s designed to be used in combination with the lambda expressions we saw in the previous post.

Write Cleaner Lambda Expressions, With Method References

In the last post, you saw how you can use lambda expressions to remove lots of boilerplate code from your Android applications. However, when a lambda expression is simply calling a single method that already has a name, you can cut even more code from your project by using a method reference.

For example, this lambda expression is really just redirecting work to an existing handleViewClick method:

In this scenario, we can refer to this method by name, using the :: method reference operator. You create this kind of method reference, using the following format:

In our Floating Action Button example, we can use a method reference as the body of our lambda expression:

Note that the referenced method must take the same parameters as the interface—in this instance, that’s View.

You can use the method reference operator (::) to reference any of the following:

A Static Method

If you have a lambda expression that calls a static method:

Then you can turn it into a method reference:

For example, if you had a static method PrintMessage in a MyClass class, then your method reference would look something like this:

An Instance Method of a Specific Object

This is an instance method of an object that’s known ahead of time, allowing you to replace:

With:

So, if you had the following lambda expression:

Then introducing a method reference would give you the following:

An Instance Method of an Arbitrary Object of a Particular Type

This is an instance method of an arbitrary object that will be supplied later, and written in the following format:

Constructor References

Constructor references are similar to method references, except that you use the keyword new to invoke the constructor. For example, Button::new is a constructor reference for the class Button, although the exact constructor that’s invoked depends on the context.

Using constructor references, you can turn:

Into:

For example, if you had the following MyInterface interface:

Then you could use constructor references to create new Student instances:

It’s also possible to create constructor references for array types. For example, a constructor reference for an array of ints is int[]::new.

Add Default Methods to Your Interfaces

Prior to Java 8, you could only include abstract methods in your interfaces (i.e. methods without a body), which made it difficult to evolve interfaces, post-publication.

Every time you added a method to an interface definition, any classes that implemented this interface would suddenly be missing an implementation. For example, if you had an interface (MyInterface) that was used by MyClass, then adding a method to MyInterface would break compatibility with MyClass.

In the best case scenario where you were responsible for the small number of classes that used MyInterface, this behaviour would be annoying but manageable—you’d just have to set aside some time to update your classes with the new implementation. However, things could become much more complicated if a large number of classes implemented MyInterface, or if the interface was used in classes that you weren’t responsible for.

While there were a number of workarounds for this problem, none of them were ideal. For example, you could include new methods in an abstract class, but this would still require everyone to update their code to extend this abstract class; and, while you could extend the original interface with a new interface, anyone who wanted to use these new methods would then need to rewrite all their existing interface references.

With the introduction of default methods in Java 8, it’s now possible to declare non-abstract methods (i.e. methods with a body) inside your interfaces, so you can finally create default implementations for your methods.

When you add a method to your interface as a default method, any class that implements this interface doesn’t necessarily need to provide its own implementation, which gives you a way of updating your interfaces without breaking compatibility. If you add a new method to an interface as a default method, then every class that uses this interface but doesn’t provide its own implementation will simply inherit the method’s default implementation. Since the class isn’t missing an implementation, it’ll continue to function as normal.

In fact, the introduction of default methods was the reason that Oracle was able to make such a large number of additions to the Collections API in Java 8.

Collection is a generic interface that’s used in many different classes, so adding new methods to this interface had the potential to break countless lines of code. Rather than adding new methods to the Collection interface and breaking every class that was derived from this interface, Oracle created the default method feature, and then added these new methods as default methods. If you take a look at the new Collection.Stream() method (which we’ll be exploring in detail in part three), you’ll see that it was added as a default method:

Creating a default method is simple—just add the default modifier to your method signature:

Now, if MyClass uses MyInterface but doesn’t provide its own implementation of defaultMethod, it’ll just inherit the default implementation provided by MyInterface. For example, the following class will still compile:

An implementing class can override the default implementation provided by the interface, so classes are still in complete control of their implementations.

While default methods are a welcome addition for API designers, they can occasionally cause a problem for developers who are trying to use multiple interfaces in the same class. 

Imagine that in addition to MyInterface, you have the following:

Both MyInterface and SecondInterface contain a default method with exactly the same signature (defaultMethod). Now imagine you try to use both of these interfaces in the same class:

At this point you have two conflicting implementations of defaultMethod, and the compiler has no idea which method it should use, so you’re going to encounter a compiler error.

One way to resolve this problem is to override the conflicting method with your own implementation:

The other solution is to specify which version of defaultMethod you want to implement, using the following format:

So if you wanted to call the MyInterface#defaultMethod() implementation, then you’d use the following:

Using Static Methods in Your Java 8 Interfaces

Similar to default methods, static interface methods give you a way of defining methods inside an interface. However, unlike default methods, an implementing class cannot override an interface’s static methods.

If you have static methods that are specific to an interface, then Java 8’s static interface methods give you a way of placing these methods inside the corresponding interface, rather than having to store them in a separate class.

You create a static method by placing the keyword static at the beginning of the method signature, for example:

When you implement an interface that contains a static interface method, that static method is still part of the interface and isn’t inherited by the class implementing it, so you’ll need to prefix the method with the interface name, for example:

This also means that a class and an interface can have a static method with the same signature. For example, using MyClass.staticMethod and MyInterface.staticMethod in the same class won’t cause a compile-time error.

So, Are Interfaces Essentially Just Abstract Classes?

The addition of static interface methods and default methods has led some developers to question whether Java interfaces are becoming more like abstract classes. However, even with the addition of default and static interface methods, there are still some notable differences between interfaces and abstract classes:

  • Abstract classes can have final, non-final, static and non-static variables, whereas an interface can only have static and final variables.
  • Abstract classes allow you to declare fields that are not static and final, whereas an interface’s fields are inherently static and final.
  • In interfaces, all methods that you declare or define as default methods are inherently public, whereas in abstract classes you can define public, protected, and private concrete methods.
  • Abstract classes are classes, and therefore can have state; interfaces cannot have state associated with them.
  • You can define constructors inside an abstract class, something that’s not possible inside Java interfaces.
  • Java only allows you to extend one class (regardless of whether it’s abstract), but you’re free to implement as many interfaces as you require. This means that interfaces typically have the edge when you require multiple inheritance, although you do need to beware the deadly diamond of death!

Apply the Same Annotation as Many Times as You Want

Traditionally, one of the limitations of Java annotations has been that you cannot apply the same annotation more than once in the same location. Try to use the same annotation multiple times, and you’re going to encounter a compile-time error.

However, with the introduction of Java 8’s repeating annotations, you’re now free to use the same annotation as many times as you want in the same location.

In order to ensure your code remains compatible with earlier versions of Java, you’ll need to store your repeating annotations in a container annotation.

You can tell the compiler to generate this container, by completing the following steps:

  • Mark the annotation in question with the @Repeatablemeta-annotation (an annotation that’s used to annotate an annotation). For example, if you wanted to make the @ToDo annotation repeatable, you’d use: @Repeatable(ToDos.class). The value in parentheses is the type of container annotation that the compiler will eventually generate.
  • Declare the containing annotation type. This must have an attribute that’s an array of the repeating annotation type, for example:

Attempting to apply the same annotation multiple times without first declaring that it’s repeatable will result in an error at compile-time. However, once you’ve specified that this is a repeatable annotation, you can use this annotation multiple times in any location where you’d use a standard annotation.

Conclusion

In this second part of our series on Java 8, we saw how you can cut even more boilerplate code from your Android projects by combining lambda expressions with method references, and how to enhance your interfaces with default and static methods.

In the third and final installment, we’ll be looking at a new Java 8 API that lets you process huge amounts of data in a more efficient, declarative manner, without having to worry about concurrency and thread management. We’ll also be tying together a few of the different features we’ve discussed throughout this series, by exploring the role that Functional Interfaces have to play in lambda expressions, static interface methods, default methods, and more.

And finally, even though we’re still waiting for Java 8’s new Date and Time API to officially arrive on Android, I’ll show how you can start using this new API in your Android projects today, with the help of some third-party libraries.

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

2017-10-17T13:25:56.737Z2017-10-17T13:25:56.737ZJessica Thornsby

New Course: Kotlin Fundamentals

$
0
0

Do you want to get started using one of the hottest new programming languages out there? Then check out our new course, Kotlin Fundamentals.

Kotlin website

What You’ll Learn

In this course, Android developer Annapurna Agrawal will teach you everything you need to know to develop Android apps in the Kotlin language. 

You'll start from scratch, with a brief overview of Kotlin and its advantages, and a look at how to set up the IDE. Then you'll move on to writing your first Kotlin code and dig deeper into its method of execution. 

Screenshot from Kotlin Fundamentals

You'll learn the basic syntax before moving on to fundamental topics such as functions and classes, loops and iterators. You'll also get a sneak peek at some advanced features of Kotlin like lambdas, higher-order functions, and using Java and Kotlin together in the same app.

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

Write Your First Kotlin Code

In this lesson, you'll write your first Kotlin program and execute it in IntelliJ IDEA. You'll also learn how classes are automatically created.

 

Classes and Functions

Learn how to call other functions from Kotlin main(). You'll see how to call a function inside a class and how to use field variables and class properties outside the class.

 

String Templates and Interpolation

In this video, you'll learn how to use string interpolation, with some examples to explain the concept.

 

Take the Course

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

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

2017-10-18T09:37:35.000Z2017-10-18T09:37:35.000ZAndrew Blackman

New Course: Kotlin Fundamentals

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

Do you want to get started using one of the hottest new programming languages out there? Then check out our new course, Kotlin Fundamentals.

Kotlin website

What You’ll Learn

In this course, Android developer Annapurna Agrawal will teach you everything you need to know to develop Android apps in the Kotlin language. 

You'll start from scratch, with a brief overview of Kotlin and its advantages, and a look at how to set up the IDE. Then you'll move on to writing your first Kotlin code and dig deeper into its method of execution. 

Screenshot from Kotlin Fundamentals

You'll learn the basic syntax before moving on to fundamental topics such as functions and classes, loops and iterators. You'll also get a sneak peek at some advanced features of Kotlin like lambdas, higher-order functions, and using Java and Kotlin together in the same app.

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

Write Your First Kotlin Code

In this lesson, you'll write your first Kotlin program and execute it in IntelliJ IDEA. You'll also learn how classes are automatically created.

 

Classes and Functions

Learn how to call other functions from Kotlin main(). You'll see how to call a function inside a class and how to use field variables and class properties outside the class.

 

String Templates and Interpolation

In this video, you'll learn how to use string interpolation, with some examples to explain the concept.

 

Take the Course

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

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

2017-10-18T09:37:35.000Z2017-10-18T09:37:35.000ZAndrew Blackman

Kotlin From Scratch: Abstract Classes, Interfaces, Inheritance, and Type Alias

$
0
0

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

In the previous article, you learned more about Kotlin properties such as late-initialization, extension, and inline properties. Not only that, you also learned about advanced classes such as data, enum, nested, and sealed classes in Kotlin. 

In this post, you'll continue to learn about object-oriented programming in Kotlin by learning about abstract classes, interfaces, and inheritance. For a bonus, you'll also learn about type aliases. 

1. Abstract Classes

Kotlin supports abstract classes—just like Java, these are classes which you never intend to create objects from. An abstract class is incomplete or useless without some concrete (non-abstract) subclasses, from which you can instantiate objects. A concrete subclass of an abstract class implements all the methods and properties defined in the abstract class—otherwise that subclass is also an abstract class!

We create an abstract class with the abstract modifier (similar to Java). 

Note that not all members have to be abstract. In other words, we can have method default implementation in an abstract class. 

Here we created the non-abstract function fullName() in an abstract class Employee. Concrete classes (subclasses of the abstract class) can override an abstract method's default implementation—but only if the method has the open modifier specified (you will learn more about this shortly). 

We can also store state in abstract classes. 

Even if the abstract class doesn't define any methods, we need to create a subclass before we can instantiate it, as in the example below.

Our Programmer class extends the Employee abstract class. In Kotlin we use a single colon character (:) instead of the Java extends keyword to extend a class or implement an interface. 

We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).  

One thing that might surprise you is that we have the ability to override a val (immutable) property with var (mutable). 

Make sure you use this functionality wisely! Be aware that we can't do the reverse—override a var property with val

2. Interfaces

An interface is simply a collection of related methods that typically enable you to tell objects what to do and also how to do it by default. (Default methods in interfaces are a new feature added to Java 8.) In other words, an interface is a contract that implementing classes must abide by. 

An interface is defined using the interface keyword in Kotlin (similar to Java). 

In the code above, we've declared a StudentRepository interface. This interface contains two abstract methods: getById() and getResultsById(). Note that including the abstract keyword is redundant in an interface method because they are already abstract implicitly. 

An interface is useless without one or more implementers—so let's create a class that will implement this interface. 

Here we created a class StudentLocalDataSource that implements the StudentRepository interface.

We use the override modifier to label the methods and properties we want to redefine from the interface or superclass—this is similar to the @Override annotation in Java.

Note the following additional rules of interfaces in Kotlin:

  • A class can implement as many interfaces as you want, but it can only extend a single class (similar to Java).
  • The override modifier is compulsory in Kotlin—unlike in Java. 
  • Along with methods, we can also declare properties in a Kotlin interface. 
  • A Kotlin interface method can have a default implementation (similar to Java 8). 

Let's see an example of an interface method with a default implementation.

In the preceding code, we added a new method delete() with a default implementation (though I did not add the actual implementation code for demonstration purposes). 

We also have the freedom to override the default implementation if we want.

As stated, a Kotlin interface can have properties—but note that it can't maintain state. (However, remember abstract classes can maintain state.) So the following interface definition with a property declaration will work.

But if we try to add some state to the interface by assigning a value to the property, it will not work.

However, an interface property in Kotlin can have getter and setter methods (though only the latter if the property is mutable). Note also that property in an interface cannot have a backing field. 

We can also override an interface property if you want, so as to redefine it. 

Let's look at a case where we have a class implementing multiple interfaces with the same method signature. How does the class decide which interface method to call?

Here we have two interfaces that have a method with the same signature funD(). Let's create a class that implements these two interfaces and overrides the funD() method. 

The compiler is confused about calling the super.funD() method because the two interfaces that the class implements have the same method signature. 

To solve this problem, we wrap the interface name for which we want to call the method in angle brackets <InterfaceName>. (IntelliJ IDEA or Android Studio will give you a hint about solving this issue when it crops up.)

Here we are going to call the funD()  method of InterfaceA. Problem solved! 

3. Inheritance

A new class (subclass) is created by acquiring an existing class's (superclass) members and perhaps redefining their default implementation. This mechanism is known as inheritance in object-oriented programming (OOP). One of the things that make Kotlin so awesome is that it encompasses both the OOP and functional programming paradigms—all in one language.

The base class for all classes in Kotlin is Any

The Any type is equivalent to the Object type we have in Java. 

The Any type contains the following members: equals(), hashcode(), and also toString() methods (similar to Java). 

Our classes don't need to explicitly extend this type. If you don't explicitly specify which class a new class extends, the class extends Any implicitly. For this reason, you typically don't need to include : Any in your code—we do so in the code above for demonstration purposes. 

 Let's now look into creating classes in Kotlin with inheritance in mind. 

In the code above, the GraduateStudent class extends the superclass Student. But this code won't compile. Why? Because classes and methods are final by default in Kotlin. In other words, they cannot be extended by default—unlike in Java where classes and methods are open by default. 

Software engineering best practice recommends that you to begin making your classes and methods final by default—i.e. if they aren't specifically intended to be redefined or overridden in subclasses. The Kotlin team (JetBrains) applied this coding philosophy and many more development best practices in developing this modern language. 

For us to allow subclasses to be created from a superclass, we have to explicitly mark the superclass with the open modifier. This modifier also applies to any superclass property or method that should be overridden by subclasses.

We simply put the open modifier before the class keyword. We have now instructed the compiler to allow our Student class to be open for extension. 

As stated earlier, members of a Kotlin class are also final by default. 

In the preceding code, we marked the schoolFees function as open—so that subclasses can override it. 

Here, the open schoolFees function from the superclass Student is overridden by the GraduateStudent class—by adding the override modifier before the fun keyword. Note that if you override a member of a superclass or interface, the overriding member will also be open by default, as in the example below:

Even though we didn't mark the schoolFees() method in the GraduateStudent class with the open modifier, we can still override it—as we did in the ComputerScienceStudent class. For us to prevent this, we have to mark the overriding member as final

Remember that we can add new functionality to a class—even if it's final—by the use of extension functions in Kotlin. For a refresher on extension functions, check out my Advanced Functions in Kotlin post. Also, if you need a refresher on how to give even a final class new properties without inheriting from it, read the section on extension Properties in my Advanced Properties and Classes post. 

If our superclass has a primary constructor like this:

Then any subclass has to call the primary constructor of the superclass. 

We can simply create an object of the GraduateStudent class as usual:

If the subclass wants to call the superclass constructor from its secondary constructor, we use the super keyword (similar to how superclass constructors are invoked in Java). 

If you need a refresher on class constructors in Kotlin, kindly visit my Classes and Objects post. 

4. Bonus: Type Alias

Another awesome thing we can do in Kotlin is to give a type an alias. 

Let's see an example.

In the class above, we can assign the String and Int types for the Person properties aliases using the typealias modifier in Kotlin. This modifier is used to create an alias of any type in Kotlin—including the ones you have created. 

As you can see, we have created an alias Name and Age for both the String and Int types respectively. We have now replaced the firstName and lastName property type to our alias Name—and also Int type to Age alias. Note that we didn't create any new types—we instead created an alias for the types. 

These can be handy when you want to provide a better meaning or semantic to types in your Kotlin codebase. So use them wisely! 

Conclusion

In this tutorial, you learned more about object-oriented programming in Kotlin. We covered the following:

  • abstract classes
  • interfaces 
  • inheritance
  • type alias

If you have been learning Kotlin through our Kotlin From Scratch series, make sure you have been typing the code you see and running it on your IDE. One great tip to really grasp a new programming language (or any programming concept) you're learning is to make sure you don't just only read the learning resource or guide, but also type the actual code and run it!

In the next tutorial in the Kotlin From Scratch series, you'll be introduced to exception handling in Kotlin. See you soon!

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


2017-10-18T14:00:00.000Z2017-10-18T14:00:00.000ZChike Mgbemena

Kotlin From Scratch: Abstract Classes, Interfaces, Inheritance, and Type Alias

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

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

In the previous article, you learned more about Kotlin properties such as late-initialization, extension, and inline properties. Not only that, you also learned about advanced classes such as data, enum, nested, and sealed classes in Kotlin. 

In this post, you'll continue to learn about object-oriented programming in Kotlin by learning about abstract classes, interfaces, and inheritance. For a bonus, you'll also learn about type aliases. 

1. Abstract Classes

Kotlin supports abstract classes—just like Java, these are classes which you never intend to create objects from. An abstract class is incomplete or useless without some concrete (non-abstract) subclasses, from which you can instantiate objects. A concrete subclass of an abstract class implements all the methods and properties defined in the abstract class—otherwise that subclass is also an abstract class!

We create an abstract class with the abstract modifier (similar to Java). 

Note that not all members have to be abstract. In other words, we can have method default implementation in an abstract class. 

Here we created the non-abstract function fullName() in an abstract class Employee. Concrete classes (subclasses of the abstract class) can override an abstract method's default implementation—but only if the method has the open modifier specified (you will learn more about this shortly). 

We can also store state in abstract classes. 

Even if the abstract class doesn't define any methods, we need to create a subclass before we can instantiate it, as in the example below.

Our Programmer class extends the Employee abstract class. In Kotlin we use a single colon character (:) instead of the Java extends keyword to extend a class or implement an interface. 

We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).  

One thing that might surprise you is that we have the ability to override a val (immutable) property with var (mutable). 

Make sure you use this functionality wisely! Be aware that we can't do the reverse—override a var property with val

2. Interfaces

An interface is simply a collection of related methods that typically enable you to tell objects what to do and also how to do it by default. (Default methods in interfaces are a new feature added to Java 8.) In other words, an interface is a contract that implementing classes must abide by. 

An interface is defined using the interface keyword in Kotlin (similar to Java). 

In the code above, we've declared a StudentRepository interface. This interface contains two abstract methods: getById() and getResultsById(). Note that including the abstract keyword is redundant in an interface method because they are already abstract implicitly. 

An interface is useless without one or more implementers—so let's create a class that will implement this interface. 

Here we created a class StudentLocalDataSource that implements the StudentRepository interface.

We use the override modifier to label the methods and properties we want to redefine from the interface or superclass—this is similar to the @Override annotation in Java.

Note the following additional rules of interfaces in Kotlin:

  • A class can implement as many interfaces as you want, but it can only extend a single class (similar to Java).
  • The override modifier is compulsory in Kotlin—unlike in Java. 
  • Along with methods, we can also declare properties in a Kotlin interface. 
  • A Kotlin interface method can have a default implementation (similar to Java 8). 

Let's see an example of an interface method with a default implementation.

In the preceding code, we added a new method delete() with a default implementation (though I did not add the actual implementation code for demonstration purposes). 

We also have the freedom to override the default implementation if we want.

As stated, a Kotlin interface can have properties—but note that it can't maintain state. (However, remember abstract classes can maintain state.) So the following interface definition with a property declaration will work.

But if we try to add some state to the interface by assigning a value to the property, it will not work.

However, an interface property in Kotlin can have getter and setter methods (though only the latter if the property is mutable). Note also that property in an interface cannot have a backing field. 

We can also override an interface property if you want, so as to redefine it. 

Let's look at a case where we have a class implementing multiple interfaces with the same method signature. How does the class decide which interface method to call?

Here we have two interfaces that have a method with the same signature funD(). Let's create a class that implements these two interfaces and overrides the funD() method. 

The compiler is confused about calling the super.funD() method because the two interfaces that the class implements have the same method signature. 

To solve this problem, we wrap the interface name for which we want to call the method in angle brackets <InterfaceName>. (IntelliJ IDEA or Android Studio will give you a hint about solving this issue when it crops up.)

Here we are going to call the funD()  method of InterfaceA. Problem solved! 

3. Inheritance

A new class (subclass) is created by acquiring an existing class's (superclass) members and perhaps redefining their default implementation. This mechanism is known as inheritance in object-oriented programming (OOP). One of the things that make Kotlin so awesome is that it encompasses both the OOP and functional programming paradigms—all in one language.

The base class for all classes in Kotlin is Any

The Any type is equivalent to the Object type we have in Java. 

The Any type contains the following members: equals(), hashcode(), and also toString() methods (similar to Java). 

Our classes don't need to explicitly extend this type. If you don't explicitly specify which class a new class extends, the class extends Any implicitly. For this reason, you typically don't need to include : Any in your code—we do so in the code above for demonstration purposes. 

 Let's now look into creating classes in Kotlin with inheritance in mind. 

In the code above, the GraduateStudent class extends the superclass Student. But this code won't compile. Why? Because classes and methods are final by default in Kotlin. In other words, they cannot be extended by default—unlike in Java where classes and methods are open by default. 

Software engineering best practice recommends that you to begin making your classes and methods final by default—i.e. if they aren't specifically intended to be redefined or overridden in subclasses. The Kotlin team (JetBrains) applied this coding philosophy and many more development best practices in developing this modern language. 

For us to allow subclasses to be created from a superclass, we have to explicitly mark the superclass with the open modifier. This modifier also applies to any superclass property or method that should be overridden by subclasses.

We simply put the open modifier before the class keyword. We have now instructed the compiler to allow our Student class to be open for extension. 

As stated earlier, members of a Kotlin class are also final by default. 

In the preceding code, we marked the schoolFees function as open—so that subclasses can override it. 

Here, the open schoolFees function from the superclass Student is overridden by the GraduateStudent class—by adding the override modifier before the fun keyword. Note that if you override a member of a superclass or interface, the overriding member will also be open by default, as in the example below:

Even though we didn't mark the schoolFees() method in the GraduateStudent class with the open modifier, we can still override it—as we did in the ComputerScienceStudent class. For us to prevent this, we have to mark the overriding member as final

Remember that we can add new functionality to a class—even if it's final—by the use of extension functions in Kotlin. For a refresher on extension functions, check out my Advanced Functions in Kotlin post. Also, if you need a refresher on how to give even a final class new properties without inheriting from it, read the section on extension Properties in my Advanced Properties and Classes post. 

If our superclass has a primary constructor like this:

Then any subclass has to call the primary constructor of the superclass. 

We can simply create an object of the GraduateStudent class as usual:

If the subclass wants to call the superclass constructor from its secondary constructor, we use the super keyword (similar to how superclass constructors are invoked in Java). 

If you need a refresher on class constructors in Kotlin, kindly visit my Classes and Objects post. 

4. Bonus: Type Alias

Another awesome thing we can do in Kotlin is to give a type an alias. 

Let's see an example.

In the class above, we can assign the String and Int types for the Person properties aliases using the typealias modifier in Kotlin. This modifier is used to create an alias of any type in Kotlin—including the ones you have created. 

As you can see, we have created an alias Name and Age for both the String and Int types respectively. We have now replaced the firstName and lastName property type to our alias Name—and also Int type to Age alias. Note that we didn't create any new types—we instead created an alias for the types. 

These can be handy when you want to provide a better meaning or semantic to types in your Kotlin codebase. So use them wisely! 

Conclusion

In this tutorial, you learned more about object-oriented programming in Kotlin. We covered the following:

  • abstract classes
  • interfaces 
  • inheritance
  • type alias

If you have been learning Kotlin through our Kotlin From Scratch series, make sure you have been typing the code you see and running it on your IDE. One great tip to really grasp a new programming language (or any programming concept) you're learning is to make sure you don't just only read the learning resource or guide, but also type the actual code and run it!

In the next tutorial in the Kotlin From Scratch series, you'll be introduced to exception handling in Kotlin. See you soon!

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


2017-10-18T14:00:00.000Z2017-10-18T14:00:00.000ZChike Mgbemena

How You Can Support LGBTQ Youth as a Mobile App Developer

$
0
0

October 19th is Spirit Day, a day for supporting LGBTQ youth and speaking out against the bullying and harassment they too often face. Here at Envato Tuts+, we're proud to stand against bullying and discrimination of any kind, so we're going purple to show we stand with lesbian, gay, bisexual, transsexual and queer youth.

In this post, we'll take a quick look at some of the ways we can support LGBTQ youth as app developers.

Avoid Coding Assumptions About Your Users' Identities

It's really important that we as developers avoid coding assumptions about gender and sexual identity into our apps. Anyone in a gender or sexual minority will understand this point immediately, but for others it can be easy to let gender assumptions creep into our code without even realizing it.

Gender Mutability

In my role as editor of mobile content for Envato Tuts+, I see assumptions like this crop up occasionally when reviewing code snippets and examples. For instance, in the Swift language, you might model a person as follows.

Pretty straightforward, but there's one problem: the gender property of Person is immutable and set in the class initializer. But real people can change the gender they are identified with! 

This is a somewhat artificial example, and of course there could be provisions in other parts of the codebase or system for users to change their gender, but it demonstrates how gender assumptions can cause problems. Imagine if the assumption that gender is unchangeable were coded into a university enrollment or driver's license database. It would lead to a system that was unable to accurately model the people it represents!

Remember, in real life, gender is a var (mutable).

Modeling Gender

Similarly, how should we model the Gender type? In the past, a lot of devs and database designers have represented gender as an enum. Again, in Swift, we might have:

I'm sure you see the problem: a binary choice between "male" and "female" doesn't encompass the range of gender identities held by app users today. If you make your users choose between one of these alternatives, you will be sure to alienate a lot of them. 

The online dating app OkCupid had this problem in its early years, causing many potential users to be excluded—to be unable or feel uncomfortable to use the service. In 2014 though, OkCupid (along with social media giant Facebook) overhauled their gender and sexual orientation model.

OkCupid gender selection

OkCupid's is an example of a well-thought-out system for modeling gender and sexual orientation, and it's worth referencing if you need to provide for gender in your app. 

In Swift, then, we might implement a very inclusive Gender type as follows:

This would let users select from a broad range of established gender identities, choose multiple simultaneous identities, and even supply their own if the supplied options were not enough.

Non-Traditional Families

For a final example, suppose that we had the following properties in the Person class:

This assumes that a person has one mother and one father. For many people, raised in non-traditional families, that is simply not the case. For instance, I have a friend who was raised in a house with five mothers. How lucky for her! 

A better way to model parent relations might be:

Inclusive Apps

As mobile apps and software in general become more and more central to people's lives, we have a responsibility as developers to make sure that our apps are as inclusive as possible. If we make assumptions about gender or sexual identity, we exclude some potential users of our apps or limit their opportunity to use the service our apps provide. 

The same goes for other assumptions about users. Check out this great list of Falsehoods Programmers Believe About Names.

Tell Stories and Explore LGBTQ Themes in Your Game

If you are a mobile game developer, you have a great opportunity to support the LGBTQ community by including diverse characters in your game, and by allowing users to use their preferred gender identity and sexual orientation in the game.

For an overview of ways that LGBTQ issues can be and have been addressed in games, check out Michael James Williams' Spirit Day 2015 post.

Write an App to Support LGBTQ Youth

Whatever issue you are passionate about, you have a real opportunity to make a difference by developing a custom app to support that cause. Even if you're just learning to code apps or only setting out in your career, this can be a great way to get started. Let's face it, your app has a much better chance of getting noticed if it is connected to a social issue that people care about. 

Here is a list of some apps that have been created to help LGBTQ youth and other victims of bullying. Be inspired!

Verena

The title of this app means "protector", and it is intended to help its users find protection in times of crisis: directing them to police stations, hospitals, shelters and other places of refuge, as well as notifying a designated list of contacts in case of emergency.

Verena app

Verena was created by 15-year-old Amanda Southwith to support her friends in the LGBTQ community. One clever feature is that the app has an incognito mode, disguised to look like a homework helper. That way, youth who might not be able to be open about their sexual identity are safe to have and use the app on their phone.

You're Accepted

Coming out is an extremely difficult and even dangerous time for many LGBTQ youth. Many teens have faced cruel bullying, abuse, or disownment and expulsion from their family home. The creators of the You're Accepted app are trying to make this transition easier by helping users build a network of safety and support before coming out.

You're Accepted is a message platform that allows LGBTI youth to tell their friends their sexuality or gender identity, anonymously. You can see their responses and then decide who to tell. — You're Accepted
Youre Accepted app

The creators of the app believe that no one should live in fear of being themselves and have written this app to help counter online discrimination against LGBTQ youth.

PRIDE Study

This app was created by doctors and scientists at the University of California in San Francisco to investigate connections between being a gender or sexual minority and long-term health outcomes.

The PRIDE Study deeply explores how the experience of being LGBTQ is related to all aspects of health and life. — PRIDE Study

This will help doctors, governments and community groups understand how to support LGBTQ health.

The PRIDE Study is built on Apple's ResearchKit framework, announced at Apple's Spring Forward event in 2015. This technology allows researchers to easily enroll and collect data from participants in large-scale, longitudinal studies—studies that collect health information over time.

Know Bullying

While it's not a problem unique to LGBTQ youth, all too many LGBTQ youth experience some sort of bullying. This experience can be deeply painful and has driven many young people to depression, self-harm, and even suicide. The app is a tool to help parents and teachers check in with children and detect the signs of bullying. Some of the features of the app include:

  • tips about the kinds of bullying experienced in specific age groups
  • warning signs that a child might be bullied or be engaged in bullying
  • conversation starters to help engage with children
Know Bullying conversation starters

Know Bullying was created by the US Substance Abuse and Mental Health Services Administration (SAMHSA), and it's packed with information for parents and educators to help them detect and prevent bullying.

Quist

Quist, short for "quistory" or "queer history", was created to celebrate and educate young people in the history of the struggle for LGBTQ rights. Every day, the app shows users a collection of events from that day in history so that users can see:

How far the LGBTQ community has come over time—how we have been treated, how we have reacted, how our allies have supported us, and how others have worked vehemently to stop the progress. — Quist 

With this youth-friendly app, the Quist team is trying to educate and inform the world about the deep history of LGBTQ communities, and to provide support to individuals by showing how others throughout history have shared their struggle.

Quist app

Circle of 6

Circle of 6 is an easy-to-use tool designed to help teenagers and college students prevent sexual violence and get out of bad situations.

Need help getting home? Need an interruption? Two taps lets your circle know where you are and how they can help. Circle of 6 app for iPhone and Android makes it quick and easy to reach the 6 people you choose. — Circle of 6

The Circle of 6 app was created for the 2011 Apps Against Abuse White House challenge. And won! With more than 150,000 students in 32 countries, the app has received press from around the world. 

The app creators say that they are inspired to make the world a better place with "technology that enhances friendship and trust". 

Conclusion

Bullying of LGBTQ youth is a huge problem, with 85% of LGBTQ youth reporting having been verbally harassed, 48% reporting experiencing cyberbullying, and 13% reporting having been physically assaulted—all because of their gender identity. 

Spirit Day gives us a chance to support the LGBTQ community and show that we are against bullying. You can help out by wearing purple today and talking to your friends or young people in your life. As a mobile app developer, though, you have a special opportunity to help—by ensuring your apps are inclusive and perhaps even by creating an app to help youth at risk of bullying!

2017-10-19T08:30:30.000Z2017-10-19T08:30:30.000ZAdam Brown

How You Can Support LGBTQ Youth as a Mobile App Developer

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

October 19th is Spirit Day, a day for supporting LGBTQ youth and speaking out against the bullying and harassment they too often face. Here at Envato Tuts+, we're proud to stand against bullying and discrimination of any kind, so we're going purple to show we stand with lesbian, gay, bisexual, transsexual and queer youth.

In this post, we'll take a quick look at some of the ways we can support LGBTQ youth as app developers.

Avoid Coding Assumptions About Your Users' Identities

It's really important that we as developers avoid coding assumptions about gender and sexual identity into our apps. Anyone in a gender or sexual minority will understand this point immediately, but for others it can be easy to let gender assumptions creep into our code without even realizing it.

Gender Mutability

In my role as editor of mobile content for Envato Tuts+, I see assumptions like this crop up occasionally when reviewing code snippets and examples. For instance, in the Swift language, you might model a person as follows.

Pretty straightforward, but there's one problem: the gender property of Person is immutable and set in the class initializer. But real people can change the gender they are identified with! 

This is a somewhat artificial example, and of course there could be provisions in other parts of the codebase or system for users to change their gender, but it demonstrates how gender assumptions can cause problems. Imagine if the assumption that gender is unchangeable were coded into a university enrollment or driver's license database. It would lead to a system that was unable to accurately model the people it represents!

Remember, in real life, gender is a var (mutable).

Modeling Gender

Similarly, how should we model the Gender type? In the past, a lot of devs and database designers have represented gender as an enum. Again, in Swift, we might have:

I'm sure you see the problem: a binary choice between "male" and "female" doesn't encompass the range of gender identities held by app users today. If you make your users choose between one of these alternatives, you will be sure to alienate a lot of them. 

The online dating app OkCupid had this problem in its early years, causing many potential users to be excluded—to be unable or feel uncomfortable to use the service. In 2014 though, OkCupid (along with social media giant Facebook) overhauled their gender and sexual orientation model.

OkCupid gender selection

OkCupid's is an example of a well-thought-out system for modeling gender and sexual orientation, and it's worth referencing if you need to provide for gender in your app. 

In Swift, then, we might implement a very inclusive Gender type as follows:

This would let users select from a broad range of established gender identities, choose multiple simultaneous identities, and even supply their own if the supplied options were not enough.

Non-Traditional Families

For a final example, suppose that we had the following properties in the Person class:

This assumes that a person has one mother and one father. For many people, raised in non-traditional families, that is simply not the case. For instance, I have a friend who was raised in a house with five mothers. How lucky for her! 

A better way to model parent relations might be:

Inclusive Apps

As mobile apps and software in general become more and more central to people's lives, we have a responsibility as developers to make sure that our apps are as inclusive as possible. If we make assumptions about gender or sexual identity, we exclude some potential users of our apps or limit their opportunity to use the service our apps provide. 

The same goes for other assumptions about users. Check out this great list of Falsehoods Programmers Believe About Names.

Tell Stories and Explore LGBTQ Themes in Your Game

If you are a mobile game developer, you have a great opportunity to support the LGBTQ community by including diverse characters in your game, and by allowing users to use their preferred gender identity and sexual orientation in the game.

For an overview of ways that LGBTQ issues can be and have been addressed in games, check out Michael James Williams' Spirit Day 2015 post.

Write an App to Support LGBTQ Youth

Whatever issue you are passionate about, you have a real opportunity to make a difference by developing a custom app to support that cause. Even if you're just learning to code apps or only setting out in your career, this can be a great way to get started. Let's face it, your app has a much better chance of getting noticed if it is connected to a social issue that people care about. 

Here is a list of some apps that have been created to help LGBTQ youth and other victims of bullying. Be inspired!

Verena

The title of this app means "protector", and it is intended to help its users find protection in times of crisis: directing them to police stations, hospitals, shelters and other places of refuge, as well as notifying a designated list of contacts in case of emergency.

Verena app

Verena was created by 15-year-old Amanda Southworth to support her friends in the LGBTQ community. One clever feature is that the app has an incognito mode, disguised to look like a homework helper. That way, youth who might not be able to be open about their sexual identity are safe to have and use the app on their phone.

You're Accepted

Coming out is an extremely difficult and even dangerous time for many LGBTQ youth. Many teens have faced cruel bullying, abuse, or disownment and expulsion from their family home. The creators of the You're Accepted app are trying to make this transition easier by helping users build a network of safety and support before coming out.

You're Accepted is a message platform that allows LGBTI youth to tell their friends their sexuality or gender identity, anonymously. You can see their responses and then decide who to tell. — You're Accepted
Youre Accepted app

The creators of the app believe that no one should live in fear of being themselves and have written this app to help counter online discrimination against LGBTQ youth.

PRIDE Study

This app was created by doctors and scientists at the University of California in San Francisco to investigate connections between being a gender or sexual minority and long-term health outcomes.

The PRIDE Study deeply explores how the experience of being LGBTQ is related to all aspects of health and life. — PRIDE Study

This will help doctors, governments and community groups understand how to support LGBTQ health.

The PRIDE Study is built on Apple's ResearchKit framework, announced at Apple's Spring Forward event in 2015. This technology allows researchers to easily enroll and collect data from participants in large-scale, longitudinal studies—studies that collect health information over time.

Know Bullying

While it's not a problem unique to LGBTQ youth, all too many LGBTQ youth experience some sort of bullying. This experience can be deeply painful and has driven many young people to depression, self-harm, and even suicide. The app is a tool to help parents and teachers check in with children and detect the signs of bullying. Some of the features of the app include:

  • tips about the kinds of bullying experienced in specific age groups
  • warning signs that a child might be bullied or be engaged in bullying
  • conversation starters to help engage with children
Know Bullying conversation starters

Know Bullying was created by the US Substance Abuse and Mental Health Services Administration (SAMHSA), and it's packed with information for parents and educators to help them detect and prevent bullying.

Quist

Quist, short for "quistory" or "queer history", was created to celebrate and educate young people in the history of the struggle for LGBTQ rights. Every day, the app shows users a collection of events from that day in history so that users can see:

How far the LGBTQ community has come over time—how we have been treated, how we have reacted, how our allies have supported us, and how others have worked vehemently to stop the progress. — Quist 

With this youth-friendly app, the Quist team is trying to educate and inform the world about the deep history of LGBTQ communities, and to provide support to individuals by showing how others throughout history have shared their struggle.

Quist app

Circle of 6

Circle of 6 is an easy-to-use tool designed to help teenagers and college students prevent sexual violence and get out of bad situations.

Need help getting home? Need an interruption? Two taps lets your circle know where you are and how they can help. Circle of 6 app for iPhone and Android makes it quick and easy to reach the 6 people you choose. — Circle of 6

The Circle of 6 app was created for the 2011 Apps Against Abuse White House challenge. And won! With more than 150,000 students in 32 countries, the app has received press from around the world. 

The app creators say that they are inspired to make the world a better place with "technology that enhances friendship and trust". 

Conclusion

Bullying of LGBTQ youth is a huge problem, with 85% of LGBTQ youth reporting having been verbally harassed, 48% reporting experiencing cyberbullying, and 13% reporting having been physically assaulted—all because of their gender identity. 

Spirit Day gives us a chance to support the LGBTQ community and show that we are against bullying. You can help out by wearing purple today and talking to your friends or young people in your life. As a mobile app developer, though, you have a special opportunity to help—by ensuring your apps are inclusive and perhaps even by creating an app to help youth at risk of bullying!

2017-10-19T08:30:30.000Z2017-10-19T08:30:30.000ZAdam Brown
Viewing all 1836 articles
Browse latest View live