Android Kotlin Basics – Static Classes and 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

Kotlin Static Classes

 
Using statics in object oriented design is not really a necessity, but something we find ourselves doing from time to time. This is especially true with newer trends that bring more functional style programming mixed with object-oriented. The first thing to note, is that Kotlin does not define entire static class as “static classes”. Instead, we use what is called an object declaration. It is also true that Kotlin does not use the static keyword at all. Even if you wanted a single static function/method in a non-static class, you need to create what is called a companion object within your class.

Let’s look at example of using statics to implement the Factory Pattern – which allows for an object to create the instance of itself in a lazy fashion, using static methods. To do this in Java, we would create a class and a static function that returns an instance of itself. Here’s an example of doing this in Java and in Kotlin

Dog.java

class Dog {
    public static Dog create() {
        return new Dog();
    }
}

Dog.kt

class Dog() {
    companion object Factory {
        fun create(): Dog = Dog()
    }
}

There are a few differences that happen when using these companion objects from our Kotlin classes within our Java code.
When creating a companion object, it creates an inner class with a static method on it in Java, so to invoke the above factory create function, you would call

Dog.Factory.create();

but in Kotlin, you can simple say

Dog.create()

Also, the name of the companion object is optional, so you could simply say:
Dog.kt

class Dog() {
    companion object {
        fun create(): Dog = Dog()
    }
}

But to call this in Java, you would say:

Dog.Companion.create();

If you REALLY don’t want to have to call the .Companion from your Java code, you can use the @JvmStatic tag like so:

class Dog() {
    companion object {
        @JvmStatic
        fun create(): Dog = Dog()
    }
}

Then you can use it in Java the same way you do in Kotlin:

Dog.create();

On the same note as using the companion object, you can also create regular object declarations at the package level, and use functions within those in a static manner:

// remember, Dog factories in real life 
// are awful, awful things, but in the context of Data
// they are okay.
object DogFactory {
    fun create(): Dog = Dog() 
}

And this can be called directly if the package is imported:

DogFactory.create()

Next Steps

Although this is the best solution for creating static classes and methods the same way Java does it, the standards of Kotlin actually suggest using a completely new pattern – package level functions. We’ll talk about that in the next post of the series!

Statics are also extremely useful for another feature that helps Kotlin stand out – Extension Functions and Properties. These are very similar to C# extension methods, but with even more features. We will also cover this subject in a later post.

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.

Advertisement

Android Kotlin Basics – Visibility Modifiers

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 Visibility Modifiers

Visibility modifiers are what we use to facilitate the Encapsulation and Polymorphism aspects of object-oriented design and it seems that every language handles a few things differently. We use modifiers to restrict access to certain parts of our code from other code. We know Kotlin is interoperable with Java, but their visibility modifiers are actually different in a few ways!

Java has 4 primary modifiers:

  • public
  • private
  • protected
  • package-private: The default if you do not explicitly provide one

However, these modifiers are not available for top level structures such as classes or interfaces. All the modifiers are used for members of those classes and interfaces, but only public and package-private are used for the actual classes and interfaces.

Oracle has created a useful chart on what each modifier is and what it restricts:

Access Levels
Modifier Class Package Subclass World
public Yes Yes Yes Yes
protected Yes Yes Yes No
no modifier Yes Yes No No
private Yes No No No

source: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Those are pretty straightforward. public means everyone gets to see it, protected means subclasses and packages can see it, package-private means objects in the same package see it, but that’s it, and private means only the immediate class can see it.

Let’s look at Kotlin’s implementation, and what I personally believe to be more useful and logical. If you come from a C# background these will seem familiar.

Kotlin has 4:

  • public
  • private
  • protected
  • internal

One important thing to note is that Kotlin, unlike many other languages, defaults to public. This means everything is exposed, and it is up to the developer to determine what should be hidden. Java’s approach is to enforce the security more directly with their default which then forces the developer to determine what should be exposed. It’s an interesting approach, but the more you get into Kotlin development, the more you’ll see why it is appropriate for the style. Kotlin is statically-typed object oriented, but does not require your code to be written in forced structures, and has a lot of functional aspects to it, but we’ll get into that later in the series.

Let’s create our own chart for these:

Access Levels
Modifier Class Package Subclass World Module*
public or no modifier Yes Yes Yes Yes Yes
protected Yes No Yes No No
internal Yes Yes Yes if in Module No Yes
private Yes No No No No

*Modules are unique to Kotlin and include all files compiled in one source-set. More info here https://kotlinlang.org/docs/reference/visibility-modifiers.html#modules

Some important things to note:

  • protected is not visible to the entire package – it is basically private but also exposes to sublcasses. This is the same as C# protected.
  • internal is like public if the referencing code is within the same Module
  • private is not just for classes, since Kotlin does not actually require a class for functions. private restricts to the actual FILE that the code lives in.

 

Now that we know how to use encapsulation and visibility modifiers, we can start to understand more of how we can secure our code and architect our solutions in strong and logical ways.

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 – Property Encapsulation

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 Property Encapsulation

Okay, let’s get to it then. Kotlin is an object-oriented, statically typed, programming language. This means we use interfaces, classes, and abstract classes (among some other unique data structures) to define our data and objects. Encapsulation in our classes serves 2 primary purposes – Code security and architecture strength. It’s how we restrict access to these data structures as well as their contained properties and functions.

In this post we will focus on how we encapsulate properties within our classes, interfaces, and more. Kotlin is 100% interoperable with Java so its practices have to work back and forth with the limitations of Java as well. Let’s take a look at ways we encapsulate properties in Java first, then show how much better it is in Kotlin!

Let’s look at 2 classes – Animal and a child class Dog. We’ll first be showing the Java implementation, then look at how much nicer the Kotlin implementation is!

Animal.java

abstract class Animal {
    // name property
    private String name;

    // constructor with name parameter
    protected Animal(String name) {
        this.name = name; // sets the name
    }

    public String getName() {
        return this.Name
    }
    public void setName(String name) {
         this.name = name;
    }
}

Dog.java

public class Dog extends Animal {
    private String breed;
    // constructor with name parameter
    protected Dog(String name, String breed) {
        super(name); // sets the name through base constructor
        this.breed = breed;
    }

    public String getBreed() {
        return this.breed;
    }

}

To summarize the relationship – Animal has a property called name that we have access to both get and set via the getName and setName functions. Dog then inherits those functions from the Animal class and adds a new property called breed, but breed can only be set by the constructor, so we do not create a setBreed function.

This is just a simple example of encapsulating properties and using functions to manage the access of reading and writing the data separately.

Now let’s see how much better this looks in Kotlin:

Animal.kt

abstract class Animal(public var name: String) { }

Yup… that’s literally it. This creates an abstract class with a public property name that is instantiated in the constructor and has public access to both read and write.

Now let’s look at how that inheritance works and how to restrict write access

Dog.kt

class Dog(name: String, breed: String) : Animal(name) {
    val breed: String = breed
        private set
}

4 lines of code. A class that inherits everything from Animal and has a breed property that is set by the default constructor and can only be set privately.

You can use these get and set modifiers to restrict access to either as well as create custom “dynamic” getters and setters (that we will look at further later in the series).

There are many different ways to handle the code above in Kotlin, but I wanted to demonstrate the shortest and most direct. In future parts of the series, we will also look at constructor overloading, dynamic getters/setters, val vs. var, and so much more.

One last thing – because Kotlin is interoperable with Java, we need to know how this ends up outputting in Java. When we create custom getters and setters for public properties, it actually creates a dynamic function getPropertyName and setPropertyName that can be consumed by Java. And even does it the other way around. If you reference a Java library in your Kotlin code, you can access the underlying property since it will automatically map methods with the prefix of “get” or “set” to custom properties. Pretty cool!

For those coming from a C# background this is extremely similar to how C# handles property getters and setters. In C# it will create methods with the name get_PropertyName and set_PropertyName to handle the dynamic encapsulation and implementations! Kotlin pulls the best parts from the best langauges!

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.

 

Pluralsight Course Announcement – Building Android Apps with Kotlin: Getting Started

Today’s the day! My first Pluralsight course Building Android Apps with Kotlin: Getting Started has finally released!
Take a look at the course here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/

And read below for more information.

What’s in it for me?

In this course, we take an introductory look at Android application development with the newest language set out to replace Java – Kotlin. This is a beginner’s course to both Android and Kotlin, so no experience in either is required. If you have some Android knowledge, come take a look at how it looks in Kotlin, and if you have some Kotlin experience, take a look at how it is applied to Android development.

In the end you’ll leave the course with a fully built real-world application that you can always look back to and reference in your own Android apps going forward!

Touch on topics such as:

  • Android fundamentals
  • Activities and their lifecycle
  • Fragments and their lifecycle
  • Creating models in Kotlin to represent remote data
  • Accessing data over HTTP
  • Storing data locally on the device with Sqlite and Anko
  • Making asynchronous data calls to ensure the UI remains smooth
  • Material design
  • Other helpful tools and libraries
  • Comparing Java to Kotlin
  • So much more…

 

I’m planning a paired blog series to tag along with the course that will focus on some other basic Android+Kotlin concepts and draw comparisons to how they were done in Java and how they should be done in Kotlin, so keep an eye out for that as well!

Feedback

Again, this is my first course completed with Pluralsight, so I’m always looking for feedback or questions you might have about the course. You can either, comment in the “Discussion” section of the course, comment on this post, or reach me on Twitter @Suave_Pirate. What did you like? What could have been done better? What are you stuck on?

Thank You!

A special thank you to my Editor, Alex Walton, and my Author Success Manager, Beth Gerard-Hess for their help through the process as well as the rest of the Pluralsight team for being so great while I produced my first course.

 

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 – Comparing Models in Kotlin, Java, and C# for Xamarin

Models are an obvious important part of our applications we develop. It’s how we define our data and because of that, we can grow our models to be quite large in number. This post will look at comparing the definition of models between Java, C# (for Xamarin), and Kotlin.

Our example model will be a simple Person that has a Name and Description along with an ID. Let’s look at how we can define our Person model with these fields as well as the ability to access these fields publicly.

Using Java

Java is going to be our largest and most annoying to develop. We need to define our class, private fields, and then public functions/methods to get and set the value of each of the fields. We also need to be able to instantiate a Person with all these properties set in the constructor.

Person.java

public class Person{
    private int id;
    private String name;
    private String description;

    public Person(int id, string name, string description){
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public void setID(int id){
        this.id = id;
    }
    public int getID(){
        return this.id;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setDescription(String description){
        this.description = description;
    }
    public String getDescription(){
        return this.description;
    }
}

That’s exhausting…

Now we can instantiate it and update properties like this:

...
Person bob = new Person(1, "Bob", "He writes code and stuff");
bob.setDescription("He doesn't actually write code");
...

Using C# for Xamarin Applications

C# makes our lives a lot easier with the get and set mechanism built into properties.

Person.cs

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public Person(int id, string name, string description)
    {
        ID = id;
        Name = name;
        Description = description;
    }
}

Nice and neat!

Now we can instantiate it and update properties like this:

...
var bob = new Person(1, "Bob", "He writes code and stuff");
bob.Description = "He doesn't actually write code";
...

Using Kotlin

Kotlin has some cool tricks that allow us to define and set properties directly in our constructor without having to define and set them separately. This gives us the quickest way to create simple POCO definitions and speed up that development time.

Person.kt

class Person(var id: Int, var name: String, var description: String);

One line.

Now we can instantiate it and update properties like this:

...
val bob = Person(1, "Bob", "He writes code and stuff");
bob.description = "He doesn't actually write code";
...

Conclusion

Each language has their nuances, but I think we can all agree that defining models in Java is just a headache that other languages have solved with better solutions.

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.Basics – Adding a Bottom Navigation View

Changing my pace of steady Xamarin content to go to my roots of native mobile development. This time, we’ll look at implementing the latest control provided by Google and Material Design – The BottomNavigationView.

Resources

Aren’t These Just Tabs?

I mean… yeah, but… it’s new and cool! Google finally realized that stretching to the top of the app can be annoying.
Screen Shot 2017-06-27 at 5.56.48 PM.png

This new control is also a little different from the TabLayout we all know in love from Material Design and Android development in that it is limited to 5 maximum tab items and does not support scrolling. It’s meant to act as top level or sibling level navigation as long as all items are of equal importance in the context of the application/current view. It is also nice to give some variety to our applications navigation scheme; larger apps with many tabbed views can become overwhelming, so tossing something new is relieving to our users.

Code

There are 3 major components to setting up a view with a BottomNavigationView.

  1. First, we need to create a menu resource for our navigation items.
  2. Then we need to create, style, and set up our BottomNavigationView in our layout.
  3. Lastly, add listeners for when an item is selected in our BottomNavigationView and make sure it fits the experience expectation defined in Material Design.

Create a Menu

In our example, we will be building an application for viewing adoptable puppies. Each navigation item will be a different set of these puppies by categorizing them. Let’s create a menu for “all”, “big”, “small”, “trained”, and “active” as categories for our puppies:

res/menu/bottom_bar_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/all_puppies"         android:title="@string/action_all"         android:icon="@drawable/ic_home_white_24dp" />

    <item android:id="@+id/big_puppies"         android:title="@string/action_big"         android:icon="@drawable/ic_dog_white_24dp" />

    <item android:id="@+id/small_puppies"         android:title="@string/action_small"         android:icon="@drawable/ic_small_dog_white_24dp" />

    <item android:id="@+id/trained_puppies"         android:title="@string/action_trained"         android:icon="@drawable/ic_trained_white_24dp" />

    <item android:id="@+id/active_puppies"         android:title="@string/action_active"         android:icon="@drawable/ic_active_white_24dp" />
</menu>

With our menu, we can create our layout.

Updating the Layout

In our example, we are moving from a TabLayout with a ViewPager. However, the Material Design documentation for the BottomNavigationView states that it should NOT be used with side-swiping actions such as a ViewPager. Let’s replace that ViewPager with a FrameLayout that will be used to swap our active Fragment and also remove the TabLayout that is being replaced by the BottomNavigationView:

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/main_content"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fitsSystemWindows="true"     tools:context="com.suavepirate.bottomnavigationpuppies.activities.MainActivity">

    <android.support.design.widget.AppBarLayout         android:id="@+id/appbar"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:paddingTop="@dimen/appbar_padding_top"         android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar             android:id="@+id/toolbar"             android:layout_width="match_parent"             android:layout_height="?attr/actionBarSize"             android:background="?attr/colorPrimary"             app:layout_scrollFlags="scroll|enterAlways"             app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

<FrameLayout     android:id="@+id/container"     android:layout_width="match_parent"     android:layout_height="match_parent"     app:layout_behavior="@string/appbar_scrolling_view_behavior" ></FrameLayout>
<android.support.design.widget.BottomNavigationView     android:id="@+id/bottombar"     android:layout_width="match_parent"     android:layout_height="56dp"     android:layout_gravity="bottom|fill_horizontal|start"     app:menu="@menu/bottom_bar_menu"     android:background="@android:color/white"     app:elevation="8dp"/>
</android.support.design.widget.CoordinatorLayout>

It’s important to layout the BottomNavigationView at the bottom of the page as well as give it a solid background and elevation. Also, notice how we apply our menu we created to the view by setting app:menu="@menu/bottom_bar_men".

With our layout set, let’s wire up listeners to update the current Fragment based on the selected navigation item.

Setting Up Listeners

In our MainActivity.java we can implement the BottomNavigationView.OnNavigationItemSelectedListener interface and override the onNavigationItemSelected method:

MainActivity.java

// imports

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
    private PageAdapter mSectionsPagerAdapter;
    private FrameLayout mContainer;
    private BottomNavigationView mBottomBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of puppy types
        mSectionsPagerAdapter = new PageAdapter(getSupportFragmentManager(), this);

        // Set up the ViewPager with the sections adapter.
        mContainer = (FrameLayout) findViewById(R.id.container);

        // set up the first Fragment
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, mSectionsPagerAdapter.getItem(0), "CURRENT_PAGE");
        ft.commit();

        // set up the bottom bar and listener
        mBottomBar = (BottomNavigationView)findViewById(R.id.bottombar);
        mBottomBar.setOnNavigationItemSelectedListener(this);

    }

    // Handles when an item is selected to update the fragment container
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);

        switch(item.getItemId()){
            case R.id.all_puppies: ft.replace(R.id.container, mSectionsPagerAdapter.getItem(0));
                break;
            case R.id.big_puppies: ft.replace(R.id.container, mSectionsPagerAdapter.getItem(1));
                break;
            case R.id.small_puppies: ft.replace(R.id.container, mSectionsPagerAdapter.getItem(2));
                break;
            case R.id.trained_puppies: ft.replace(R.id.container, mSectionsPagerAdapter.getItem(3));
                break;
            case R.id.active_puppies: ft.replace(R.id.container, mSectionsPagerAdapter.getItem(4));
                break;
        }
        ft.commit();
        return true;
    }
}

Now with all of this, we are able to switch the current Fragment with a fade in and out animation when the selected navigation item is updated. That means our BottomNavigationView is implemented and ready to go!

Screenshot_1497932698

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.