David Greenhalgh - Big Nerd Ranch Mon, 28 Feb 2022 11:51:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Looking Forward to KotlinConf 2018 https://bignerdranch.com/blog/looking-forward-to-kotlinconf-2018/ https://bignerdranch.com/blog/looking-forward-to-kotlinconf-2018/#respond Sun, 30 Sep 2018 09:10:00 +0000 https://nerdranchighq.wpengine.com/blog/looking-forward-to-kotlinconf-2018/ Returning for a second year, KotlinConf is _the_ place to learn about new Kotlin language advancements straight from the source - the language designers themselves.

The post Looking Forward to KotlinConf 2018 appeared first on Big Nerd Ranch.

]]>

Last year, we were excited to attend KotlinConf 2017, JetBrains’ official Kotlin developer conference.
Returning for a second year, KotlinConf is the place to learn about new Kotlin language advancements straight from the source – the language designers themselves.

It’s been a great year for Kotlin: Kotlin adoption continues to grow on Android, and Kotlin is being used in more domains than ever before, thanks to Kotlin/JS and Kotlin/Native.

We’ll once again be at KotlinConf, and this time, we’re official partners!
We’ve been working with JetBrains to deliver a unique track at KotlinConf 2018 with Q/A sessions, code labs, and great giveaways.

Josh Skeen will be talking about his experience building a modular synthesizer using Kotlin/Native and will be helping folks onboard onto Kotlin/Native in our Intro to Kotlin/Native session.
David Greenhalgh, Nikki Porter, and Chris Stewart will be on site for the Big Nerd Ranch track, featuring topics that you need to know if you’re adopting Kotlin: higher-order functions, interoperability, and how to make the most of Kotlin and RxJava.

If you’re in Amsterdam on October 4-5, 2018, stop by the conference and say hello!
We’d love to talk to you about the language that our Android team has fallen in love with.

The post Looking Forward to KotlinConf 2018 appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/looking-forward-to-kotlinconf-2018/feed/ 0
Kotlin Programming: The Big Nerd Ranch Guide https://bignerdranch.com/blog/kotlin-programming-the-big-nerd-ranch-guide/ https://bignerdranch.com/blog/kotlin-programming-the-big-nerd-ranch-guide/#respond Thu, 12 Jul 2018 09:00:00 +0000 https://nerdranchighq.wpengine.com/blog/kotlin-programming-the-big-nerd-ranch-guide/ The day is finally here: our guide to the Kotlin programming language will soon be on store shelves

The post Kotlin Programming: The Big Nerd Ranch Guide appeared first on Big Nerd Ranch.

]]>

The day is finally here: our guide to the Kotlin programming language will soon be on store shelves and in your hands, dear reader.
About a year ago, Josh Skeen and I sat down to start work full-time on a guide to the language that we had grown to love.

Kotlin went mainstream in May 2017 thanks to a welcome assist from Google, but Big Nerd Ranch’s Kotlin journey started in 2015 with an internal app called KoffeeKüp.
In our focus on delivering high-quality courses, books, and applications, it sometimes became easy to pass menial tasks like refilling the coffee carafe onto the next under-caffeinated developer.
We needed a way to encourage each other to refill the coffee, and KoffeeKüp was born.

KoffeeKüp provided us with a playground for playing with some of the technologies that were piquing our interest at the time: MVVM, data binding, Slack bots, and most importantly, Kotlin.
From that point forward, we started building internal apps and experiments in Kotlin.
We offered Kotlin work on our consulting projects, and once Google announced their official support, our clients were the ones starting the Kotlin conversation.

The Book

Our books are the result of our combined experience in application development and in teaching our courses.
By the time it gets to you, the content in Kotlin Programming: The Big Nerd Ranch Guide has been taught in numerous classes, where we take your feedback and hear the problems that you’re running into as developers.

In Kotlin Programming: The Big Nerd Ranch Guide, we start from core principles that you may know from other languages: basic data types, conditionals, collections etc. and introduce them within the context of the Kotlin programming language.
If you’re a Java developer, some of this will be familiar to you.
Kotlin adds useful twists to these tried-and-true standards; once you use conditional expressions, for example, you’ll see opportunities to clean up lots of existing code.

With that foundation set, we dive deep into object-oriented programming principles in Kotlin.
Kotlin gives you remarkable power in how you initialize objects – we have a whole chapter on it!
You’re not limited to object-oriented programming in Kotlin, though – we’ll also walk through how Kotlin gives you the flexibility to integrate functional programming into your workflow.

Kotlin Programming: The Big Nerd Ranch Guide is platform-agnostic, but we make sure to take some time to highlight common patterns on Android.

There’s so much more to cover, from anonymous functions to extensions and beyond.
We do this all in Big Nerd Ranch’s example-driven style: we introduce concepts within the context of a project that you get to build throughout the book.
If you’ve ever wanted to build your own text adventure, then this is the book for you.

We humbly hope that you love the book as much as we love the language that spawned it.

The post Kotlin Programming: The Big Nerd Ranch Guide appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/kotlin-programming-the-big-nerd-ranch-guide/feed/ 0
An Introduction to Kotlin on Android https://bignerdranch.com/blog/an-introduction-to-kotlin-on-android/ https://bignerdranch.com/blog/an-introduction-to-kotlin-on-android/#respond Thu, 18 May 2017 14:00:53 +0000 https://nerdranchighq.wpengine.com/blog/an-introduction-to-kotlin-on-android/ Google surprised many at its 2017 I/O keynote by introducing [Kotlin](https://kotlinlang.org/) as a first-party language. This day has been long-awaited at Big Nerd Ranch—we've been writing Kotlin apps internally and have fallen in love with its concise syntax and safety. Now that Kotlin has the official seal of approval, let's talk about what it can do for you.

The post An Introduction to Kotlin on Android appeared first on Big Nerd Ranch.

]]>

Google I/O 2017 logo

Google surprised many at its 2017 I/O keynote by introducing Kotlin as a first-party language.
This day has been long-awaited at Big Nerd Ranch—we’ve been writing Kotlin apps internally and have fallen in love with its concise syntax and safety.
Now that Kotlin has the official seal of approval, let’s talk about what it can do for you.

What is Kotlin?

Kotlin is a JVM language developed at JetBrains, reaching 1.0 in February of 2016.
Up to this point, it’s primarily gathered steam in the Android community, providing relief to developers whose language growth had stagnated.

The first question people often ask about Kotlin’s introduction as an official language is, “Is this Android’s Swift?”
This is a natural reaction, given the similarity of their syntax and the relative recency of Swift’s unveiling.
I’ll leave the answer up to you, but Kotlin’s impact is worth considering as you decide which language to invest your time into.
If you’re interested in learning more about Kotlin, we’d love to help you out.

Your First Kotlin App

KlickerActivity.kt

In order to understand Kotlin, it may be useful to see it used to write an Android app.
We won’t touch on the syntax details of each line of code with a direct parallel in Java, but we will take a look at some of the more unique concepts.
Let’s look at KlickerHero, a small clicker game that I’ve written entirely in Kotlin for Android.

KlickerHero screenshot

Our only activity simply contains a TextView (with ID kounter) representing the player’s score and a button for the player to click repeatedly (with ID klicker).
To listen for click events and update the screen accordingly, we’ll need to obtain references to these views.
Let’s take a look at how we do this in KlickerActivity.kt.

class KlickerActivity : AppCompatActivity() {

    private lateinit var kounterTextView : TextView
    private lateinit var klickerButton : Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_klicker)

        kounterTextView = findViewById(R.id.kounter) as TextView
        klickerButton = findViewById(R.id.klicker) as Button
    }
}

There are a couple of things to note here.
Let’s first look at kounterTextView and klickerButton.
One of the advantages of Kotlin is its null safety.
Every variable must be initialized in Kotlin, helping you avoid the pesky NullPointerException that plagues the lives of many Java developers.
This isn’t to say that variables can’t ever be null, but a variable that is assigned a null value must broadcast this state to any object that interacts with it.

In our case above, we bend the rule that variables should immediately be initialized by using the lateinit keyword.
lateinit is a contract stating that we can declare a variable without initializing it, but we’ll see an UninitializedPropertyAccessException if we try to use it before initialization.
It’s great for declaring member variables such as views in Android that need to be initialized in onCreate.

Kareer.kt

Our KlickerHero game is simple—click the button and your score goes up.
In order to really hook our players in, though, we need career progression.
We’ll track two statistics about our player:

  1. How many times they’ve clicked the button
  2. Which “tier” they’ve achieved based on their number of clicks

Let’s look at a simple Kotlin data class (with no Android code):

data class Kareer(var kount: Int = 0, var tier: Tier = Tier.Baby) {

    fun incrementKount() {
        kount++
        if (kount > tier.maxKlicks) {
            tier = getTierForLevel(tier.level + 1)
        }
    }
}

Kareer has two fields, kount and tier.
Classes in Kotlin can include constructor declarations directly in their header.
We can even define default arguments in case we aren’t passed a value for kount or tier.
Note that we declare kount and tier to be vars as a part of our constructor header.
This gives us member variable without any extra work.

Also note that Kareer is a data class.
Specifying a class as a data class in Kotlin gets us a number of method implementations for free, including equals/hashCode, toString, and more.

Kareer has one function, incrementKount.
When kount is incremented, we also want to check to see if the player has levelled up to a new Tier.
Let’s look at the player’s Tier, represented by an enumerated type:

enum class Tier(var level : Int = 0, val maxKlicks : Int, @ColorRes val kolorResId : Int) {
    Baby(0, 5, R.color.baby_blue),
    Novice(1, 15, R.color.light_green),
    Pro(2, 30, R.color.light_red),
    Master(3, 100, R.color.light_yellow),
    Grandmaster(4, Int.MAX_VALUE, R.color.grandmaster_purple);

    companion object {
        fun getTierForLevel(level: Int) : Tier {
            Tier.values()
                    .asSequence()
                    .filter { it.level == level }
                    .forEach { return it }

            throw IllegalArgumentException()
        }
    }
}

Enumerated types in Kotlin look pretty similar to other classes, and they may be familiar to Java developers.
One thing stands out against the rest of the implementation, and that’s the companion object keyword.
Companion objects are singletons declared within a class, and their usage is often similar to that of statics in Java.
In this case we’ve defined a method getTierForLevel that will return a Tier value for a specific level integer.

getTierForLevel could iterate through each value in Tier and return a value matching a specific value, but Kotlin provides functional constructs as a part of the language.
We won’t dig into them as a part of this post, but functional programming can be exceptionally useful when working with data.

Using our Kareer Model Object

Now that we have a data model expressed via the Kareer data class, let’s use it to display the user’s clicking prowess.

class KlickerActivity : AppCompatActivity() {
    ...

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        val kareer = Kareer()

        klickerButton.setOnClickListener { updateKount(kareer) }
    }
    
    private fun updateKount(kareer: Kareer) {
        kareer.incrementKount()
        val tierColor = ContextCompat.getColor(this, kareer.tier.kolorResId)
        
        kounterTextView.apply {
            text = "Count: ${kareer.kount}"
            setBackgroundColor(tierColor)
        }
    }
}

In our KlickerActivity’s onCreate method, we’ll instantiate our Kareer object—no new keyword is necessary.
We’ll then set a click listener on the klicker button so that we update the count text and background color of the kounter TextView whenever the button is clicked.

The last niceties to introduce here are in the apply block.
apply passes whatever instance it is called on into a block in which you can sequentially invoke methods on it.
In this case, we call setText and setBackgroundColor on kounterTextView without repeatedly referencing kounterTextView.
It’s a sort of tiny scope change, and it’s great for invoking multiple methods on a single instance.

Lastly, note here that we directly assign to text rather than calling setText.
Getters and setters are hidden away from you with some syntactic sugar, saving you time spent writing and maintaining these methods.

What’s Next?

Google’s support of Kotlin solidifies a movement that was already building growing with significant momentum.
We can’t wait to see more people embrace Kotlin as a part of their everyday workflow in everything from small side projects to production applications at scale.

We’ve only scratched the surface in this post of what Kotlin has to offer.
We’ll be posting more blog content in Kotlin from here on. If you’re interested to learn more about Kotlin Programming, stay updated with our books & bootcamps.

Learn more about what Kotlin means for your Android apps. Download our ebook for a deeper look into how this new first-party language will affect your business.

The post An Introduction to Kotlin on Android appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/an-introduction-to-kotlin-on-android/feed/ 0
Google I/O 2017: AI, Democratized https://bignerdranch.com/blog/google-i-o-2017-ai-democratized/ https://bignerdranch.com/blog/google-i-o-2017-ai-democratized/#respond Wed, 17 May 2017 10:00:53 +0000 https://nerdranchighq.wpengine.com/blog/google-i-o-2017-ai-democratized/ Google has made a lot of interesting announcements at this year's Google I/O. Here's what we're most excited about.

The post Google I/O 2017: AI, Democratized appeared first on Big Nerd Ranch.

]]>

Google I/O 2017 logo

Google I/O’s 2017 keynote had a clear, unifying message: artificial intelligence and machine learning have arrived for everyone.

Juxtaposed with announcements of specialized, AI-focused data centers was a constant reminder that the work that Google is doing in artificial intelligence and machine learning can be condensed down to simple, everyday examples.
We saw how Google Lens can be used to contextually identify places and things.
We saw how advancements in Google Photos can help us automate sharing of photos with our friends and family.
And we saw how all of this (and more) is made possible at scale with the introduction of Cloud TPU and AutoML.

Assistant and Home

Last year’s Google I/O keynote introduced a series of products designed to embed Google’s services into your life (such as Home and Assistant), and this year’s keynote capitalized on that traction.

Google, Amazon, Apple and Microsoft continue to bolster their investments in conversational assistants, a competition that is driving innovation across the industry. Assistant can now be interacted with in text in addition to voice, and the Assistant SDK is now being opened up to third-party developers. We can’t wait to build more Actions for Google Home, and we look forward to teaching others to do the same. As the variety of Assistant interaction models grows, the message is clear: Assistant is the future of Google Search. And Assistant is now available on iOS, a shot across Siri’s bow.

While the keynote was light on hardware announcements, Google Home saw a number of software upgrades introduced.
Hands-free calling and enhanced entertainment options are crowd pleasers that add value when compared with Home’s competitors.
The biggest Google Home announcement, however, was “Proactive Assistance.”
In Proactive Assistance, Google Home now has something akin to a contextual notification, a concept that we haven’t seen much of in its competitors.
This is perhaps for good reason—notifications are very difficult to get right.
Too many, and your user is annoyed.
Too little, and your user doesn’t get information that they may want or need.

We’ll see how it plays out, but Google is betting that the Assistant’s contextual awareness of you will enable it to achieve a level of usefulness that outweighs the load of an added stimulus.

Android

As an Android developer, I was most excited to see more of the enhancements coming down the pipeline for Android O and beyond. The Android O Developer Preview suggested a largely incremental update with enough niceties to form a collectively solid whole. In actuality, Google I/O 2017 brought the greatest nicety of all: first-party Kotlin support! We’ve been using Kotlin in our internal applications since 2015 and have fallen in love with the language. We can’t wait to write more Kotlin applications for our clients and teach you to do the same.

Outside of the introduction of a new language and improved developer tools, Android O brings a number of optimizations to the core of Android.
Security is a key focus in Android O, represented in part by the introduction of Google Play Protect.
Significant performance optimizations have been made across the board, including halved boot times and more opinionated rules around background services to protect battery life.

All of the optimizations introduced can be summed up in the introduction of Android Go.
Android has now reached two billion monthly active users, in large part due to “emerging markets” such as China and India.
Those markets have in fact emerged; they’re a priority today, not tomorrow.
Android Go is a lightweight variant of Android focusing on running on less powerful devices than it ever has before.
Big Nerd Ranch is happy to help get your application down to a size and performance level that will earn it the Android Go seal of approval.

This year’s Google I/O was a hopeful expression of the potential of Google’s work over the past few years.
Android runs more performantly on more devices than ever before, bringing applied computer vision and more to the palm of your hand.
Advancements are being made in artificial intelligence and machine learning everyday, and Google has invested in articulating meaningful impacts for our everyday lives.
Let’s see where this next chapter of computing takes us.

We’re looking forward to working with the many great new things from Google I/O 2017, and we want to share them with you in our training and client app development. Fill out this form and we’ll be in touch with updates.

Learn more about what Kotlin means for your Android apps. Download our ebook for a deeper look into how this new first-party language will affect your business.

The post Google I/O 2017: AI, Democratized appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/google-i-o-2017-ai-democratized/feed/ 0
A View Divided: Adding Dividers to Your RecyclerView with ItemDecoration https://bignerdranch.com/blog/a-view-divided-adding-dividers-to-your-recyclerview-with-itemdecoration/ https://bignerdranch.com/blog/a-view-divided-adding-dividers-to-your-recyclerview-with-itemdecoration/#respond Thu, 25 Feb 2016 11:00:53 +0000 https://nerdranchighq.wpengine.com/blog/a-view-divided-adding-dividers-to-your-recyclerview-with-itemdecoration/ At Google I/O 2014, Google unveiled `RecyclerView`, a successor to `ListView`. `RecyclerView` sought to strip away much of the cruft that slowed down `ListView`, and in doing so, shipped without some of the conveniences we'd gotten used to. We've discussed how to responsibly add some of that functionality back in [previous blog posts](https://nerdranchighq.wpengine.com/blog/?q=recyclerview), and today we'll continue with a look at list dividers.

The post A View Divided: Adding Dividers to Your RecyclerView with ItemDecoration appeared first on Big Nerd Ranch.

]]>

At Google I/O 2014, Google unveiled RecyclerView, a successor to ListView. RecyclerView sought to strip away much of the cruft that slowed down ListView, and in doing so, shipped without some of the conveniences we’d gotten used to. We’ve discussed how to responsibly add some of that functionality back in previous blog posts, and today we’ll continue with a look at list dividers.

One common task that isn’t as convenient in RecyclerView is the addition of dividers or offsets between list items, but you can fortunately create your own dividers with ItemDecoration.

ItemDecoration

RecyclerView.ItemDecoration is a tool used to decorate the children of a RecyclerView. RecyclerView is a ViewGroup, with each of its children representing an item in a list. With ItemDecoration you can easily modify the appearance of these child views.

For example, let’s add dividers to a RecyclerView using a LinearLayoutManager, oriented vertically. In order to do so, we’ll subclass ItemDecoration, giving our new class a constructor that takes in a divider to be drawn between list items.

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private Drawable mDivider;

    public DividerItemDecoration(Drawable divider) {
        mDivider = divider;
    }
...

ItemDecoration features three methods for us to override, but we’ll only need two: getItemOffsets and onDraw.

First, getItemOffsets. We need to provide offsets between list items so that we’re not drawing dividers on top of our child views. getItemOffsets is called for each child of your RecyclerView.

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    if (parent.getChildAdapterPosition(view) == 0) {
        return;
    }

    outRect.top = mDivider.getIntrinsicHeight();
}

In getItemOffsets, we’re changing the shape of the Rect outRect, which determines the amount of padding on each side of the the list item. By default, this padding is 0. Here, we change the top field of outRect to the height of our divider so that it has room to be drawn without overlapping any other views.

Note that we skip this action for the first item in the list so that we don’t draw an offset above the RecyclerView.

Next, in onDraw, we determine the bounds of our divider and draw it onto the RecyclerView. onDraw is called just once.

@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
    int dividerLeft = parent.getPaddingLeft();
    int dividerRight = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount - 1; i++) {
        View child = parent.getChildAt(i);

        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

        int dividerTop = child.getBottom() + params.bottomMargin;
        int dividerBottom = dividerTop + mDivider.getIntrinsicHeight();

        mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom);
        mDivider.draw(canvas);
    }
}

We first calculate the left and right bounds of the parent RecyclerView, as they will be the left and right bounds of our divider between each child view. We then have to calculate the location of the top and bottom of each divider, as they’re unique for each child view.

Once we have these bounds calculated, we’re able to set the bounds of each divider and draw it on the screen.

Make sure your company is positioned for success with these mobile app tips!

Usage

Adding an ItemDecoration to your RecyclerView is fairly straightforward. Using the example above, get an instance of your new DividerItemDecoration, passing in the Drawable you’d like to use as a divider (in this case, dividerDrawable).

RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(dividerDrawable);
recyclerView.addItemDecoration(dividerItemDecoration);

You can even add multiple ItemDecorations to the same RecyclerView. They tend to play nicely, but they’ll draw on top of each other in the order in which they are added. You can change this drawing priority by passing in an index to your addItemDecoration call:

int decorPriorityIndex = 0;
recyclerView.addItemDecoration(dividerItemDecoration, decorPriorityIndex);

You can also remove an ItemDecoration at will:

recyclerView.removeItemDecoration(dividerItemDecoration);

SimpleItemDecoration

ItemDecorations are a quick, flexible way to customize your RecyclerView. I’ve provided six ItemDecoration implementations wrapped in a library that I’ve creatively named SimpleItemDecoration.

SimpleItemDecoration in Action

Let’s use SimpleItemDecoration to add a divider to a RecyclerView with a LinearLayoutManager.

Drawable dividerDrawable = ContextCompat.getDrawable(this, R.drawable.divider);

recyclerView.addItemDecoration(new DividerItemDecoration(dividerDrawable));

We get a reference to a divider to use as a Drawable and pass it to the constructor of our DividerItemDecoration. Then we simply attach the new DividerItemDecoration to our RecyclerView via RecyclerView#addItemDecoration.

If this looks eerily similar to the ItemDecoration example above, that’s because it is. The difference here is that you don’t have to supply the ItemDecoration implementations—I’ve taken care of that.

So far, I’ve written solutions for the following six ItemDecoration implementations:

Let me know if you think of other uses for ItemDecoration!

The post A View Divided: Adding Dividers to Your RecyclerView with ItemDecoration appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/a-view-divided-adding-dividers-to-your-recyclerview-with-itemdecoration/feed/ 0