Android Kotlin Basics – Lazy Loading Images with Picasso

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Find other posts in this series: Android Kotlin Basics

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Lazy Loading Images with Picasso

Loading images from remote sources without help can be a pain in Android development. You need to make the http request against the url, download the bytes of the image, create a Bitmap from those bytes, then render that BitMap in an ImageView. Not only is that tedious, but it also leaves room for tons of errors and especially the dreaded OutOfMemoryException that happens oh so often when trying to render large images in Android.

There are some really great libraries out there for helping face this issue that can also provide some other useful tools such as filtering, extensions, customizing, and more.

In the course we use Picasso which is a library by Square to help lazy load images. Find it here: http://square.github.io/picasso/

Picasso does a great job loading images asynchronously and handles rendering them with proper scale. It does a great job handling this performance in ListViews and RecyclerViews as well. This is exactly how we use it in our real-world app that we build in the course!

Picasso also has some great features with creating custom transformations or extending the functionality. In this post we will stick to the basics though. If you want to get into details check out the Java documentation at their website. Copy and pasting that into a Kotlin file in Android studio will also automatically translate it for you!

Installing

Picasso can be installed 3 ways:
– Gradle (what we use in the course)
– Maven
– Manual

To install with gradle, add:

implementation 'com.squareup.picasso:picasso:2.71828'

to your build.gradle config.

For maven use:

<dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>2.71828</version>
</dependency>

And if you want to do it manually, download the jar from http://square.github.io/picasso/ and reference it in your project.

Basic Image Loading

Now that you have Picasso in your project, lets look at how we can do simple image loading.

Let’s start with a simple layout:

activity_main.xml

<RelativeLayout 
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <ImageView android:id="@+id/myImageView"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />
</RelativeLayout>

Now in our Activity code, we can load the image from the url in the onCreate override.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // load the image with Picasso
        Picasso
            .with(this) // give it the context
            .load("https://i.imgur.com/H981AN7.jpg") // load the image
            .into(myImageView) // select the ImageView to load it into
    }
}

If you’re unsure of why we didn’t need to call

val myImageView = findViewByid<ImageView>(R.id.myImageView)

Check out my post on how Kotlin automatically maps views to properties by id: Android Kotlin Basics – Auto-mapping Views

And that’s it! Now you have automatically handled all performance concerns, caching needs, sizing and downloading, and so much more!

Using in a RecyclerView

So loading a single image into a single ImageView isn’t so bad on its own, but when you have to load high-res images into large lists that can change all the time, there are a lot of places this can go wrong doing it yourself. Developers often run into:
– Lag on new items appearing
– Mismatched images
– No images loading
– Images loading incorrectly
– Dreaded Out of Memory Exceptions

Because Picasso runs the image loading asynchronously and only touches the UI thread when it needs to render the image itself, it avoid the issues of locking the UI up when loading. Because it also caches the images locally, when the image needs to be loaded again (such as scrolling back up), it does so quickly and can void mismatching renderings. Also, because it renders the image in chunks before showing it, they avoid the easy to find Out of Memory Exception that we have all come to hate when trying to render a large image into an ImageView. Normally to avoid this, you have to manually load a scaled down image into memory and handle how you scale it per image. Picasso does all this for us too.

On top of all that, Picasso ships with some of the nice-to-haves such as:
– Transitions when images load or change
– Placeholder images to show while loading from a url
– Transformations on images once loaded
– Debugging indicators to show where the image loaded from

All these great features even scale to these large lists and RecyclerViews.

Before showing how to use it in your RecyclerView, be sure to check out the other post in this series: Android Kotlin Basics – RecyclerView and Adapters unless you’re already familiar with how RecyclerViews and Adapters work 🙂

We can create a layout for our item in our list:

image_item.xml

<ImageView android:id="@+id/myImageView"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

Then a ViewHolder for this image:

ImageHolder.kt

class ImageHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val myImageView: ImageView = itemView.findViewById<ImageView>(R.id.myImageView)

    fun updateWithUrl(url: String) {
        Picasso.with(itemView.context).load(url).into(myImageView)
    }
}

Now let’s create our Adapter with our datasource:

ImagesAdapter.kt

class ImageAdapter() : RecyclerView.Adapter<ImageHolder>() {
    val imageUrls: Array<string>

    init {
        imageUrls = arrayOf("https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg")
    }

    override fun getItemCount(): Int {
        return imageUrls.size;
    }

    override fun onBindViewHolder(holder: ImageHolder?, position: Int) {
        var imageUrl = imageUrls[position]
        holder?.updateWithUrl(imageUrl)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageHolder {
        var imageItem = LayoutInflater.from(parent?.context).inflate(R.layout.image_item, parent, false)
        return ImageHolder(imageItem)
    }
}

Last we just need to create our Activity and wireup the Adapter!

activity_main.xml

<RelativeLayout 
    android:layout_height="match_parent"
    android:layout_width="match_parent">    
    <android.support.v7.widget.RecyclerView
        android:id="@+id/imageRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imageRecycler.layoutManager = LinearLayoutManager(this)
        imageRecycler.adapter = ImageAdapter()
    }
}

Now we can quickly scroll through our list and see the images loaded quickly and properly into our view!

dogs


Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Passing Data Between Activities

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Passing Data Between Activities

This topic is covered in depth in the course above, but in this post, we’ll quickly go over this basic, but very important concept when developing your Android mobile apps.

Let’s break it down first –

I Have No Idea What an “Activity” Is

Not to worry! Here’s the basic idea – it’s a construct (and a class in your code) that represents an entry point for your app and can be called into by your other Activities. You can think of an Activity as a contextual “page”, and thus your app will likely have multiple Activities.

Activities can do a lot, but for simplicity sake, we’ll only talk about the most common implementation which is this idea of a drawing a window of your application.

Starting an Activity

When you create your application, you’ll have to register your Activities to your Android manifest. Doing this tells the operating system which Activities you have in your app, where to find them, what they can do, and some other information we won’t get into in this topic.

That looks something like this:

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.alexdunn.wikipedia">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:name=".WikiApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">
        <activity
            android:name=".activities.MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activities.ArticleDetailActivity"></activity>
        <activity android:name=".activities.SearchActivity"></activity>
    </application>

</manifest>

This is a manifest with 3 Activities, MainActivity, SearchActivity, and ArticleDetailActivity.

Once all Activities are registered in the Manifest, we can start any of them from any other.

Let’s look at a quick example where we are in the MainActivity and want to start the SearchActivity on a button click:

MainActivity.kt

class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        my_button.setOnClickListener {
            // create an "Intent"
            val searchIntent = Intent(this, SearchActivity::class.java)

            // start the activity with the intent
            startActivity(searchIntent)
        }
    }
}

So what’s this Intent object?

An Intent in Android is a construct to tell the operating system that your application is trying to execute something that needs to be communicated back to the application or a different application. This is used for many things outside just starting Activities – it can be used for executing Services, Activities, and BroadcastReceivers.

Here’s a quick diagram on how this works at a basic level:
Screen Shot 2018-03-23 at 11.02.59 AM.png

Adding Data to an Intent

So now we know we use Intents to start Activities (and do other things!), but how do we use them to actually send data to another Activity?

The Intent object has a the concept of a Extras . This means we can add different primitive datatypes to the Extras, or add Serializable data.

Here’s what that looks like in Kotlin!

// 1. create an intent from another activity
val intent = Intent(context, AnotherActivity::class.java)

// 2. put key/value data
intent.putExtra("message", "Hello From MainActivity")

// 3. start the activity with the intent
context.startActivity(intent)

The putExtra has many overloads, so play around with all the types of data you can add.

You can also add Bundles of data to group the data being sent up together:

// 1. create an intent from another activity
val intent = Intent(context, AnotherActivity::class.java)

// 2. put key/value data to bundle
val extras = Bundle()
extras.putString(“message”, “Hello from MainActivity”)
intent.putExtras(extras)

// 3. start the activity with the intent
context.startActivity(intent)

Reading Data From the Intent

Now when we use an intent to start an Activity, and add Extras, we need to be able to read those extras on the new Activity.

This works by using the intent property on the Activity. This intent property is set by the Operating System when starting the Activity, and sets it to the Intent that created it.

We usually use this data in the onCreate override, but you can use it wherever you want!

DetailActivity.kt

class DetailActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // In onCreate get the value from the auto-mapped “intent”
        val message = intent.getStringExtra(“message”)

        // Or get it from the bundle and auto-mapped “extras”
        val message = intent.extras.getString(“message”)

        // now do something with the message value
    }
}

Conclusion

There’s plenty more you can do with these data structures in Android such as sending over full datatypes and reference types, receiving data back from the detail Activity, and so much more. Be sure to check out my course: Building Android Apps with Kotlin: Getting Started to learn so much more!


Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Camel Case Or Underscore Notation

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Camel Case Or Underscore Notation

I get this type of question quite often – “If the Kotlin Android extensions allow for creating Kotlin members in my Activities, should I be using underscore IDs or camel case”?

If this question doesn’t make sense, first take a look at one of my earlier posts in this series: Android Kotlin Basics – Auto-mapping Views. The short version is that Kotlin ships with Android extensions to create properties in your Activity (and more) for your Views within the layout resource applied in the setContentView call in the onCreate override function.

Here’s the predicament – traditional Android development has set a standard for using underscores for Ids and other properties within xml resources (such as the layouts we are talking about). So that looks like this:

res/layout/activity_main.xml

...

...

Doing this would create a usable EditText property in the associated MainActivity whose name is first_name:

MainActivity.kt

class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        super.onCreate(savedInstance)
        setContentView(R.layout.activity_main)

        first_name.text = "My First Name!"
    }
}

So the underscore seems to look a bit off in your Kotlin code since every other member and function within a class is typically came cased. So the other option is to start camel casing your xml property values:

res/layout/activity_main.xml

...

...

Doing this would create a usable EditText property in the associated MainActivity whose name is firstName:

MainActivity.kt

class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        super.onCreate(savedInstance)
        setContentView(R.layout.activity_main)

        firstName.text = "My First Name!"
    }
}

Of course these are just semantics, and I’ve seen projects go either way. I personally use the underscore for Android resources simply because it is still habit, but I may find myself moving more toward camel casing. The argument I hear against moving in that direction is also that the file names themselves use the underscore naming convention, and THAT convention stemmed from an actual restriction in Android development where resource files couldn’t have any uppercased letters. That is no longer really enforced, so it should be fine to name your resource files with a camel case convention as well.

My final suggestion is to simply pick one, but stick to it. Meaning, choose up front when you start your project and be consistent throughout – including your file names. If you want to camelCase, do it everywhere. If you want to underscore_case, do it everywhere. This will allow for onboarding developers easily regardless of which you pick. But who knows… maybe this will sprout another tabs vs spaces type of debate.

Let me know which one you personally prefer!


Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – RecyclerView and Adapters

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

RecyclerView and Adapters

RecyclerViews are the latest way to display a dynamic collection of data in Android and are what have begun to replace the ListView control. This is because of their built in pattern to “recycle” views… the name makes sense. It also allows for more flexibility in layout and display which we will also talk about here.

In order to use a RecyclerView, you need at least the 4 main parts
1. The RecyclerView itself
2. The Adapter to control what data is tied to what view in the recycler.
3. The ViewHolder to control what view is being used within the recycler
4. The LayoutManager to determine how to layout each view in the recycler.

Together, this relationship looks like this:
Screen Shot 2018-03-01 at 11.13.38 AM

Meaning the RecyclerView needs it’s two root components set – the LayoutManager and Adapter. The adapter then uses the ViewHolder and appropriate data to manipulate the RecyclerView, and the ViewHolder uses an underlying Layout Resource to inflate the view.

In the end the process looks like this:
Screen Shot 2018-03-01 at 11.03.21 AM

Where a user scrolls the list, and as items fall out the top or bottom, they are recycled, cleaned, then re-hydrated with new data from the adapter.

So let’s break down an example of building one of these in Kotlin!

Create a RecyclerView in Your Activity

Let’s first create a simple layout for our MainActivity:
res/layout/activity_main.xml

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/article_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </RelativeLayout>

Then using the Kotlin Android Extensions talked about here: Android Kotlin Basics – Auto-mapping Views we can reference our RecyclerView by its id property.

MainActivity.kt

class MainActivity : Activity() {
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        article_recycler_view.adapter = ??? // we need to create an adapter!
        article_recycler_view.layoutManager = LinearLayoutManager(context)
        // note that in Java we would have to call .setLayoutManager, but Kotlin auto-maps this to a property
     }
}

We’ll come back to this MainActivity once we’ve created our Adapter. But for now we can use the pre-built LinearLayoutManager which will layout the subsequent recycled views Linearly (vertically by default, but it can be set to Horizontal as well).

Create a CardView and ViewHolder

Let’s create the layout resource for our actual article card items, and the ViewHolder to represent it.

res/layout/article_card_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_margin="16dp"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:background="@android:color/white"
        app:cardElevation="4dp">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp">
            <ImageView
                android:id="@+id/article_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_image_black_24dp"/>
            <TextView
                android:id="@+id/article_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:textAlignment="center"
                android:text="Hello World!"/>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

This is a simple card with an image and title in it that looks something like this:
Screen Shot 2018-03-01 at 2.40.41 PM

And with our view, we will need to create a ViewHolder that our Adapter will use to stick data in it:

CardHolder.kt

class CardHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val articleImageView: ImageView = itemView.findViewById<ImageView>(R.id.article_image)
    private val titleTextView: TextView = itemView.findViewById<TextView>(R.id.article_title)

    private var currentPage: WikiPage? = null

    fun updateWithPage(page: WikiPage){
        currentPage = page

        titleTextView.text = page.title

        // load image lazily with picasso
        if(page.thumbnail != null)
            Picasso.with(itemView.context).load(page.thumbnail!!.source).into(articleImageView)
    }
}

So here we create a ViewHolder subclass called CardHolder that references its ImageView and TextView that can be initialized right away by querying the passed in itemView property from the constructor. We also add a convenience function to update the ViewHolder and it’s included views with a given WikiPage model (this model is what represents an article from Wikipedia and looks something like this:

WikiPage.kt

class WikiPage {
    var pageid: Int? = null
    var title: String? = null
    var fullurl: String? = null
    var thumbnail: WikiThumbnail? = null
}

WikiThumbnail

class WikiThumbnail {
    val source: String? = null
}

This model is the datatype our Adapter will reference as well.

Lastly, I added a quick reference the the Picasso Library from Square in order to load an image from the thumbnail url into our ImageView.

Creating an Adapter

Now the last thing we need to do is connect our ViewHolder and Data to our RecyclerView by creating our Adapter. Here’s what that will look like:

ArticleCardRecyclerAdapter.kt

class ArticleCardRecyclerAdapter() : RecyclerView.Adapter<CardHolder>() {
    val currentResults: ArrayList<WikiPage> = ArrayList<WikiPage>()

    override fun getItemCount(): Int {
        return currentResults.size
    }

    override fun onBindViewHolder(holder: CardHolder?, position: Int) {
        var page = currentResults[position]
        holder?.updateWithPage(page)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CardHolder {
        var cardItem = LayoutInflater.from(parent?.context).inflate(R.layout.article_card_item, parent, false)
        return CardHolder(cardItem)
    }
}

You can see our ArticleCardRecyclerAdapter inherits from the RecyclerView.Adapter and passes in our CardHolder view holder we just created as the type of ViewHolder. This allows for our required override functions to use that CardHolder as its type.

The adapter requires only 3 functions to be overridden, but there are also other functions available to override.
The three required are:
– getItemCount() to return the number of items the RecyclerView will have within it
– onBindViewHolder() to bind the data of a given position to the CardHolder. Here is where we call that updateWithPage function we created in our CardHolder class.
– onCreateViewHolder() to create the initial view holder by inflating a given layout file (which we use to inflate the article_card_item.xml file.

Now that we have our adapter, we can go and update our MainActivity:

MainActivity.kt

class MainActivity : Activity() {
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val adapter = ArticleCardRecyclerAdapter()
        adapter.currentResults = ArrayList<WikiPage>()..... // you should load your cards here! 
        article_recycler_view.adapter = adapter
        article_recycler_view.layoutManager = LinearLayoutManager(context)
        // note that in Java we would have to call .setLayoutManager, but Kotlin auto-maps this to a property
     }
}

Now you should be able to run and see your list of cards if you’ve loaded a collection of WikiPage models into your currentResults property on the adapter.

Now we can also change the layoutManager property of our recycler to something that might fit our smaller cards a bit better such as the StaggeredGridLayoutManager.

article_recycler_view.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

This means we want 2 columns and we want to stack the cards vertically within those columns. If the direction is switched to HORIZONTAL then the number before it will represent the number of rows instead of columns.

Then with that we can have a view like this!

Screen Shot 2018-03-01 at 2.53.02 PM

And that’s pretty cool!


Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Auto-mapping Views

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Auto-mapping Views

We’ve talked in previous posts about how awesome Kotlin is and showed off some of the great features of the language on its own, but did you know Kotlin gets even better when building Android apps?

The Problem

Let’s talk about the obnoxious pattern in Android of having to find a view from the associated layout before using it. I’m talking about this:

// java
Button myButton = (Button)findViewById(R.id.myButton);

If you’re totally new to Android development as a whole, this is what you do in your Activities, Fragments, ViewHolders, etc. to get a reference to a control on your page that was created by a layout resource. This means that if you have a page with many controls and views, you will need to execute the above style code for every single one.

What does this mean?

Your code looks gross. You have massive blocks of properties in your class and an equally massive block of findViewById in your onCreate or other lifecycle method. It also means that you query your View Object far more than you should need to. Other platforms like iOS and UWP (or any other windows app) create outlets or partial properties that hide the creation of the view in your code, but allow you to use it, which means your code stays super clean.

Because of this awful practice in Android, people have come out with some seriously helpful projects (I’m looking at you Butterknife!) and libraries that will automatically handle mapping them to properties in your Activity and Fragment classes like this:

// Java with Butterknife
class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

That’s a little better, but still a lot of wire up before you can even use the controls in your code.

Kotlin to the Rescue

Kotlin, I cannot thank you enough for doing this…

Kotlin created an Android extension that allows for your Activities to auto-map their layout views by their id in to useable controls!

Here’s how it works: Let’s say you have a layout resource that looks like this:

activity_example.xml


    
    

In your Activity, you simply need to import the extension, and your Activity will automatically have a property it can use that will be pulled from the layout file:

import kotlinx.android.synthetic.main.activity_example.*

class ExampleActivity: Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        setContentView(R.layout.activity_example)
        detailTextView.text = "my new text that was set when auto-mapping"
    }
}

Beyond making the code so much cleaner, this Kotlin Android Plugin also uses built in caching of the views it finds in order to avoid re-querying the View Object since it can be cumbersome and slow.

For more details on how to customize this behavior, and use the extension more in depth, check out Kotlin’s documentation on it here: https://kotlinlang.org/docs/tutorials/android-plugin.html

Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Lambdas and Higher Order Functions

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Lambdas and Higher Order Functions

Lambdas and Higher Order Functions are a great tool to use in development to pass logic around between different blocks in our code. This allows us to pass functions into other functions and execute them when we need to, and there are a few different ways to do this, but let’s start with Higher Order Functions in general.

Higher Order Functions

Higher order functions are ones that consume another function as a parameter. This means the higher order function can execute the inner function any number of times. This is commonly used for wrapping function calls, manipulating collections with the given function, or executing a callback function. Here’s an example of what that looks like with a callback function:

fun makeHttpGetRequest(string url, callback: (data: String) -> String) {
    url.httpGet() // using Fuel library as an example
       .responseString { request, response, result ->
      //do something with response
      when (result) {
          is Result.Failure -> {
              error = result.getAs()
              callback(error) // executing the passed in function
          }
          is Result.Success -> {
              data = result.getAs()
              callback(error) // executing the passed in function
          }
    }
}

In this example, we created a wrapper function for making an HTTP GET request that executes the callback function with either the error string or data as a string. Even more, we use another higher order function from the Fuel library responseString that takes in a Triple or a lambda/function with three parameters.

We define our inner function like so:

(<parameters>) -> <return type>

If your inner function does not have a return type, you simply set the return type as the Kotlin Unit – the equivalent of void. If you’re coming from F#, that will look familiar. That means a lambda with no parameters and no return type would be:

() -> Unit

Ways to Use Lambdas and Higher Order Functions

Basically, there are a few different ways you can define a function and pass that in as the parameter of the higher order function.
You could:

  • Define the function ahead of time and pass the definition in
  • Construct a Lambda Expression or Anonymous Function when invoking the higher order function

Let’s look at the first example of predefining a function to pass in. Let’s use the higher order function map that is an extension function on a List:

fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

This method takes in a transform function to handle how to map the initial List of type T to a new List of type R, and the higher order function uses the transform function to execute against each item in the original list.
If you’re coming from C#, this is like the .Select() LINQ extension method.

Let’s now define our transform method we want to use and pass it in to a map call:

// define some simple classes
class Dog (val breed: String) { }
class Pet(val petType: String, val breed: String){ }

fun createPetFromDog(dog: Dog) : Pet {
    return Pet("dog", dog.breed)
}

var dogs = List<Dog>()
// fill with dogs

var pets = dogs.map(::createPetFromDog);

We use the :: prefix to inform the compiler that this is an existing function or other member.

Now let’s look at creating this same scenario, but using lambda expressions instead. There are even a few ways we can do this too!

// define some simple classes
class Dog (val breed: String) { }
class Pet(val petType: String, val breed: String){ }

var dogs = List<Dog>()
// fill with dogs

// define the transform function as an explicit lambda
var pets1 = dogs.map({dog -> Pet("dog", dog.breed));

// define the transform function, but outside the actual parameters
// this is a shortcut provided by Kotlin to help with readability
// note that the "()" after the map is not required when defining it this way
var pets2 = dogs.map(){ dog ->
    return Pet("dog", dog.breed) // note the return here is not technically required
}

// use the "it" keyword since we only have one parameter.
// the "it" keyword is another shortcut provided by Kotlin
// for lambdas with only 1 parameter
var pets3 = dogs.map { Pet("dog", it.breed) }

Notice how many different ways we can execute the exact same thing in the end. We see this in many places with Kotlin, and it gives us as developers the freedom to define a bit of our own style in the code of our projects, or to use different strategies at different times to help with readability.

Now get out there and start using nested functions!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Null Safety and Coalescing

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Kotlin Null Safety

The NullReferenceException and NullPointerException… The bane of many of our lives as developers… say “goodbye” in Kotlin!

Kotlin made the early decision to alleviate the pain of null checks in our code.
In Kotlin, your properties, return types, local variables or values, and everything else needs to be explicitly nullable – not just primitive types, but complex types like your own classes and interfaces too!

Here’s what I mean:

class Dog() {
    val name: String 
    // this won't compile! name is NOT a nullable string, 
    // so it MUST be initialized!
}

...

class Dog() {
    val name: String = null
    // this won't compile! name is NOT a nullable string, 
    // so it MUST be initialized with a non-null value!
}

...

class Dog() {
    val name: String? = null
    // This works! name is a nullable string and is initialized with
    // null
}

...

class Dog() {
    val name: String = "a name"
    // This works because the type is a non-nullable string 
    // and is initialized with a string literal
}

Okay, so now we know that variables and values must be initialized with either an explicit nullable type or a non-nullable value, but what about if we have a nullable type, and try to do something with it? Let’s take a look!

val dog: Dog? = null

println(dog.name) 
// This won't compile! dog is a nullable type, so you need
// access the name property either dangerously or safely with
// null coalescing

...

val dog: Dog? = null
println(dog?.name) // This works! it will print null
println(dog!!.name) // This will compile, but throw an exception!
println(dog?.name?: "a default name") // this works! it will print "a default name"

Kotlin takes null coalescing to the next level by allowing you to provide a default value if anywhere along the chain is null. This is what we do in the above example – this means that if dog or dog.name is null, we use the default provided value notated with the ?: notation.

This also works for invoking functions with null safety!

class Dog() {
    fun bark() {
        println("WOOF!")
    }
}

...

val dog: Dog? = null
dog?.bark() // this works! but nothing will happen since dog is null

...

val dog: Dog? = Dog()
dog?.bark() // this works and prints WOOF!

Those are the basics of handling your nulls in Kotlin! No more ugly code like this:

if(dog != null && dog.name != null) {
    println(dog.name);
}

Shorter – Simpler – Easier to read and follow. Once again, using Kotlin makes our lives so much easier while building our apps.

Coming up in future posts, we’ll start looking outside just the basics of the language, and start implementing them with Android common situations!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – “val” and “var”

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Kotlin “val” and “var”

This one is pretty simple, especially for those coming from Java, but seeing the left side of the argument when creating either a property or local variable as “val” or “var” can be pretty weird.

Here’s what I’m talking about – let’s create a class that has two properties, one that is a value and one that is a variable (see what I did there?).

class Dog() {
    val bark: String = "Bark"
    var name: String? = null // set this later

    fun speak() : String {
        // throw an error if name is null
        val log = name!! + " said " + bark
        prntln(log)
        return log
    }
}

The quick answer is that val – being a “value” can only be set once. This is just like using the final keyword in Java. var on the other hand is a “variable” and can be set later on or can have it’s value changed whenever.

Using val in your properties makes it readonly. If you’re coming from C#, it’s like adding the readonly keyword to your class’s property, since it is a val and properties need to have a value set during the init or constructor of the class. We’ll talk more about class initialization and constructors in another post of this series.

By using val and var in the Kotlin language, it allows us to always have our properties and local variables aligned vertically which makes the readability of our code that little bit better!

In the next post, we’ll look at how Kotlin handles null references and helps us write safer code and get rid of the dreaded NullPointerException or NullReferenceException!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Extension Functions and Properties

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Kotlin Extension Functions and Properties

If you’ve come from a C# background this introduction to Kotlin extensions will feel like home.

Kotlin extensions allow for us developers to extend the functionality of a given type, whether it be a class, interface, or object. These extensions are resolved statically meaning that they are essentially added as static functions and members of the given type that is being extended.

It’s important to note that Java does not have a way to build extension methods, so in this case, we won’t be able to compare how it is done in Kotlin and Java since this is only possible in Kotlin. However, it IS possible to use Kotlin extension methods in your Java code that is referencing it.

Extension Functions

Let’s take a look at what an extension function looks like. Let’s first define a simple class Dog, and then we will add extensions to it.

Dog.kt

class Dog {
    var name: String = ""
    var breed: String = ""
}

DogExtensions.kt

fun Dog.printNameAndBreed() {
    println(this.name + " " + this.breed)
}

Now in our consumer code, we can use it like so:

MainActivty.kt

class MainActivity: Activity() {
    override fun onCreate(savedInstance: Bundle?) {
        val dog = Dog()
        dog.printNameAndBreed()
    }
}

Note the use of the keyword this within our extension method. this refers to the instance of the class that the extension method is being invoked in. However, this is not required unless you have naming conflicts with other local variables. So it could also be written as:

DogExtensions.kt

fun Dog.printNameAndBreed() {
    println(name + " " + breed)
}

This allows for a shorter syntax for writing the extension. Compare that to a C# extension method:

DogExtensions.cs

public static class DogExtensions
{
    public static void PrintNameAndBreed(this Dog dog)
    {
        Console.WriteLine($"{dog.Name} {dog.Breed}");
    }
}

Skipping the need for the parameter for the extension type allows for the signature of the signature to be the same as when it is invoked, which C# does not do.

Extension Properties

Just like extension methods, Kotlin supports creating extension properties. However, these extension properties cannot contain intializers like we use when initializing our properties on a class. Extension properties do not create an actual member of the class and thus need explicit “getters” and “setters” on the property (or just one or the other if you want to restrict it). Let’s see a quick example using our existing Dog class:

DogExtensions.kt

val Dog.nameAndBreed : String
    get() = this.name + " " + this.breed
    set(value: String) { 
        var nameAndBreedArray = value.split(" ")
        name = nameAndBreedArray[0]
        breed = nameAndBreedArray[1]
        // note the absence of the "this" keyword since it is optional
    }

Notice, that we cannot have to explicitly define get() and set() within our nameAndBreed extension property. Then within these, we access the fields on the class.

If we try to instantiate an extension property with an initializer, we will get a compile-time error. For example, this is not allowed:

val Dog.nameAndBreed : String = "Ryder Labrador" // <- not allowed!

Extensions with Nullables and “Any” Types

With Kotlin extensions, you can also add nullable types:

fun Dog?.printNameAndBreed() {
    if (this == null) return; // just return out if it is null
    println(name + " " +breed)
}

This means you can also use it with the Any type in Kotlin:

fun Any?.print() {
    if(this == null) return;

    // now print out the string version of the object
    println(toString()) 
}

We’ll get a little more into the Any type in another post of this series, but the short version is that it is a valid Kotlin type that is not restrained to an actual pre-existing or new type. This works the same way as the TypeScript any and is most useful in functional programming when using type inference more.

That’s about it for Kotlin extensions! Extensions are great – they allow for separating some concerns and keep your actual model class definitions short and clean and put some other logic around it in a restrained location. Or to help extend the functionality of a third party library that you don’t control. All in all, it was a great design decision that the Kotlin team made to make building our applications even cleaner and easier!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Package Level Functions and Members

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Kotlin Package Level Functions and Members

So, Kotlin is an object-oriented language, however, it is not exclusively an object-oriented language. What does that mean? You can actually use Kotlin in a completely functional way and not require any of your implementation to be encapsulated within interfaces and classes. In Kotlin, you can define code within functions and property/variable members from the package level! This may be a weird concept for those coming from an exclusively object-oriented background, and especially from Java, but luckily, Kotlin simplifies so much of this confusion and makes it really simple to use back and forth.

In the last Android Kotlin Basics, we looked at static classes and functions, but Kotlin actually suggests using package level functions rather than companion objects or regular objects when needing simple static methods.

How does this work? Well, the name sort of speaks for itself! These are functions and members within a Kotlin file, but not class. Then they belong to whatever package you declare the file belongs to, OR, to the entire root package if you don’t specify one at all.

Here’s what that looks like:

HelperFunctions.kt

package com.suavepirate.helpers
// this is a file with random functions that belong to the package above.

fun sayMyName() {
    println("Alex Dunn - Suave Pirate")
}

fun isThisTrue(trueOrFalse: String){
    return trueOrFalse == "true" ? true : false
}

val bestLanguageForAndroid: String = "Kotlin"

Now we can use these functions in three different ways:

  1. Import each function / member
  2. Import package with wildcard
  3. Reference each call with the package name

MainActivity.kt

import com.suavepirate.helpers.sayMyName
import com.suavepirate.helpers.isThisTrue
import com.suavepirate.helpers.bestLanguageForAndroid
//... other packages

// showing how to use these functions and members with the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        sayMyName()
        val isTrue = isThisTrue("true")
        toolbar.title = bestLangaugeForAndroid
    }
}

With the wildcard import:

MainActivity.kt

import com.suavepirate.helpers.*
//... other packages

// showing how to use these functions and members with the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        sayMyName()
        val isTrue = isThisTrue("true")
        toolbar.title = bestLangaugeForAndroid
    }
}

Or without using the package import:

MainActivity.kt

//... other packages, but not the one where the members live

// showing how to use these functions and members without the import
class MainActivity : Activity() {
    override fun onCreate(savedInstance: Bundle) {
        com.suavepirate.helpers.sayMyName()
        val isTrue = com.suavepirate.helpers.isThisTrue("true")
        toolbar.title = com.suavepirate.helpers.bestLangaugeForAndroid
    }
}

This allows us to use these members and functions in either a static way, or in a functional way if your entire application wanted to focus more on that pattern over object-oriented! Kotlin gives us so many options!

But what about using this pattern when mixing Kotlin and Java? Underneath the hood, the Kotlin compiler will actually create a class for the entire package that wraps all of the members and functions within it. This means that in Java, we can use it in the exact same way! It then uses the naming convention of {PackageFinalName}Package

MainActivity.java

import com.suavepirate.helpers;
//... other packages

// showing how to use these functions and members with the import
public class MainActivity : Activity() {
    @Override
    void onCreate(Bundle savedInstance) {
        HelpersPackage.sayMyName();
        Boolean isTrue = HelpersPackage.isThisTrue("true");
        toolbar.setTitle(HelpersPackage.bestLangaugeForAndroid);
    }
}

Jetbrains themselves have a great post on some greater detail about how this works: https://blog.jetbrains.com/kotlin/2015/06/improving-java-interop-top-level-functions-and-properties/

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.