Posts

Showing posts from October, 2018

Kotlin Interface Examples

Interface define contract for classes. An interface is similar to a class just that,  it's a collection of abstract methods and variables.  Essentially Interfaces are one level more abstract than abstract classes. Let's say we have an interface called Driveable. interface Driveable { fun drive() // declaring 'abstract' is implicit and unnecessary } we can then have different vehicles (e.g Car, Truck, Lorry, Motorcycle, Ship, Plane etc) implement the interface and override the drive method. now let's see how we implement it interface Driveable { fun drive() fun refuel() } class Car(var color : String) : Driveable{ override fun drive() { println("Driving my $color car...") } override fun refuel() { println("Re-Fueling my car ...") } } class Truck (var color: String) : Driveable{ override fun drive() { println("Driving my $color Truck...") } override fun refuel() { ...

Kotlin Open & Abstract Classes and How Inheritance Works

In  object-oriented programming ,  inheritance  enables new objects to take on the properties of existing objects. We can have class that can inherit properties and methods from the parent class, when we inherit classes, we do not need to specify the method and properties again, in the new class (child class or sub class). In essence it allow us to avoid code duplication (important) and make our code more flexible and maintainable (also very important). By default, classes in kotlin are final i.e they cannot be inherited from. This makes sense because not all classes created will need to be inherited or opened Why do we Inherit classes? Let's say, we wanted to create a class for Student and Employee . What do student and employee have in common? they both need to eat they both sleep they both move they both need to bath they both have a name the both have hair (no matter how small) they both breath air they both have birthdays they both ... You g...

Kotlin Class Examples

Class without a Constructor but with default variable (or properties or data) [box type="info" align="" class="" width=""]In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.[/box] class Person { val name : String = "Peter" // Default Variable var age : Int = 30 // Default Variable } fun main (args: Array<String>){ val person = Person() // this line tell kotlin to instantiate a new object from 'Person' class person.age = 33 //accessing our 'Person' property person.name = "Peterr"// this won't compile and can't be re-assigned because 'val' keyword makes it immutable } Class without a Constructor but with properties (or variables or data) and Methods fun main (args: Array<S...

Kotlin Methods Example

Simple Function. neither accepts nor return any variable or value fun helloWorld(){ println("Hello World") }  Function that takes a parameter but returns no value fun stringFunction (text : String){ for (c in text){ println("$c ") //KOTLIN -> K O T L I N } } fun intFunction(int : Integer){ println(int) } Functions that returns a value but takes no parameter fun getAuthorsName() : String { return "Olorunleke Opeyemi" } fun getTodaysDate() : Date { return Date() } Functions that accept a value and returns a value class Example{ fun main(args: Array<String>) { println(evaluateInteger(21, 23)) } fun evaluateInteger (a : Int, b: Int) : String { return if (a>b) { "$a is greater than $b" } else if (a<b){ "$b is greater than $a" } else {"they are equal"} } }  

Kotlin ArrayList and Loops Example

Kotlin ArrayList Kotlin ArrayList is also very similar to Java Arraylist . ArrayList<T> is the resizable-array implementation of the  List  interface. The ArrayList class has only a few methods in addition to the methods available in the List interface . val myArrayList = arrayListOf("John", "Fred", "McKinsey", "Morgan", "Sarah") //an arraylist of my friends val newFriendList = arrayListOf("Musa", "Victor", "Timothy") myArrayList.add(0, newFriendList[0]) for (e in myArrayList){ print("$e -") } // Musa -John -Fred -McKinsey -Morgan -Sarah myArrayList.removeAt(0) // removes 'Musa' which is at postion 1 val allOfMyFriends = myArrayList + newFriendList for(element in allOfMyFriends){ print("$element -") } // John -Fred -McKinsey -Morgan -Sarah -Musa -Victor -Timothy println(allOfMyFriends.size) // 8 println(allOfMyFriends.isEmpty) // false val isRemoveFredSucces...

OOP: What is an Interface?

An interface is a collection of abstract methods. It is a reference type in Java/Kotlin. It is similar to class. A class implements an interface, thereby inheriting the abstract methods of the interface. public class HelloWorld { class Example implements InterfaceExample{ @Override public void doSomething() { // doSomething } @Override public int doAnotherThing(String s) { return 0; } @Override public boolean doEntirelyAnottherThing(Long l) { return false; } } interface InterfaceExample { // Collection of Abstract Methods void doSomething(); // a simple abstract method int doAnotherThing(String s); //accepts a String returns an Int boolean doEntirelyAnottherThing(Long l) // accepts a long value and returns a boolean } } Along with abstract methods, an interface may also contain constants, default methods, static methods, a...

Kotlin Basics - Variables, Basic Types, and Array

1. Variables In Kotlin, we use " val"  to declare a constant or " var " keywords to declare a variable. You can specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword. val firstName: String = "Opeyemi" // this is similar to -> final String firstName = "Opeyemi" <- Java But you'll soon realize that in Kotlin , it's often possible to omit the type from the declaration and the compiler won't complain. val lastName = "Olorunleke" // will still compile In the code above, you'll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We'll come back to this! The difference between the val and var keywords is that the former is immutable ((its value cannot be changed or read-only), while the latter is mu...

Kotlin: Array vs List - Similarities and Differences

Image
// Initializing array and list val array = arrayOf(1, 2, 3) //pure array val list = listOf("apple", "ball", "cow") //pure list val mixedArray = arrayOf(true, 2.5, 1, 1.3f, 12000L, 'a') // mixed Array val mixedList = listOf(false, 3.5, 2, 1.4f, 13000L, 'b') // mixed List Arrays An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Arrays can be concatenated to give a new Array val array1 = arrayOf(1, 2, 3, 4, 5, 6) val array2 = arrayOf(7, 8, 9, 10, 11, 12) val newArray = array1 + array2 for(element in newArray) { println("$element - ") } // 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 Lists A list is an interface. It is a generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the  MutableL...

Kotlin Conditional Statements

If StatementsSometimes we may want to run our code only when a condition holds true. For example, let's hypothetically assume that we run a bar and we only want to admit users who are 18 years old and above. in the code below we're trying to access our code with a preset age of 16,  since 16 is less than 18. if we run the code "Sorry you cannot Register" will be printed to the console Please Pay Attention to the comment within the block of code and Practice them too! class KotlinConditionals { fun main(args: Array<String>) { val age: Int = 16 // << Preset Age if (age < 18){ println("Sorry you cannot Register") } else if (age < 21){ println("Well you can Register") // this will run only if age is between 18 to 20 } else{ println("Welcome! You can Register") // will run if age is 21 to infinity integer } println("S...

Content Providers Tutorial

Content Provider allow us to write or grab data to a user's contact, document or calendar with a few lines of code. How do two totally different apps read and write from the same data source? This is where content providers come in. A content provider is a class that sits between an application and it's data source and it's job is to provide easily managed access to the underlying data source. Why you may need Content Providers As an extra level of abstraction - they allow developers to change the underlying data source without needing to change any code that access the content provider. For example with content providers you can swap out SQLite database for any other database and your app would still remain functional. Leverage functionality of android classes ex. Loaders  and Cursor Adapter. Allow many apps to access, use and modify a single data source securely. So that they can use, access and modify your data source. If you didn't use content provide...

Firebase Crashlytics Android Example

Firebase Crashlytics is a lightweight, realtime crash reporter that helps you track, prioritize and fix stability issues that erode your app quality. Crashlytics saves you troubleshooting time by intelligently grouping crashes and highlighting the circumstances that lead up to them. Prior to Firebase Crashlytics, Google offered Firebase Crash Reporting (FCR), for app crash monitoring and reporting. Although FCR did it's job (monitoring crashes) it was a hack and it has since been deprecated in favor of Crashlytics. Reasons to use FIrebase Crashlytics over Firebase Crash Reporting Real time crash reporting : FCR could take up to 30 mins or more before an error could be reported (via email). Intuitive Dashboard Report interface : the dashboard of has been improved un-obfuscated stack trace: If you used Pro Guard or DexGuard to obfuscate your code, firebase crash reporting mandates the uploading of a "mappings.txt" file to the FCR console in order to decode stack tra...

How to select Multiple Item in RecyclerView in Android

Image
Implementing multi-select on a Recycler View can be tricky and complicated. However, by the end of this tutorial, you'll understand how to implement multi selection of items in a recycler view and do whatever you want (delete, share, copy etc) with the selected items . [box type="info" align="" class="" width=""] Disclaimer I would like to mentally prepare you, this tutorial a bit lengthy. To absorb all the concept please pay close attention make sure you are well rested make sure you have eaten. LOL This tutorial will be very useful if you aim to understand how to implement multi selection on a recycler view and modify the code to your taste (recommended approach to learn), but if you're in 'BEAST mode' you might want to  get the gitHub repository  instead. If you have ANY question, just ask! I'll be happy to help.[/box] Aim: To demystify multiple item selection in a RecyclerView Goals: Demonstrate ho...