Saturday, July 15, 2017

Kotlin OOP: method overriding

July 15, 2017

Welcome to kotlin Series



Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding
This is the fourth post in this Kotlin OOP series. In this series, we are going to cover a very important topic that is method overriding. This uses in the android app development is huge. First, we create two classes and we use one class method for other class. But we already know it how we can do that. we can do this? In the third part of this series. But in this tutorial, we are going to do some advance. We modify first class method in the second class.

Let's start.
Create a class name Math3 and also create 2 two class. Like previous Math class.

See the code-
class Math3 {

    fun add(a:Int, b:Int):Int{
        return a+b
    }

    fun sub(a:Int, b:Int):Int{
        return a-b
    }
}
Now create a second class name Math4 and it also has two methods.(like previous second math class). But take an extra variable and we use this variable in the override methods.
See the code-
class Math4(val extra:Int) {

    fun mul(a:Int, b:Int):Int{
        return a*b
    }

    fun div(a:Int, b:Int):Int{return a/b}
}
two class creation complete. Now we do our main job. Before inheriting one class to another make class as open and methods also.

See the code-
open class Math3 {

    open fun add(a:Int, b:Int):Int{
        return a+b
    }

    open fun sub(a:Int, b:Int):Int{
        return a-b
    }
}
Now inherit the first class, to second class.
class Math4(val extra:Int) : Math3(){
     //some code
}
we override two methods from first math class (Math3.kt). in add and sub-method we just add our extra value.

See the code-
add method
override fun add(a:Int, b:Int):Int{
    return a+b+extra
}
submethod-
override fun sub(a:Int, b:Int):Int{
        return a-b+extra
}
That it we finish. Now we run this code in the Main method.

see full code of Math4.kt
class Math4(val extra:Int) : Math3(){

    override fun add(a:Int, b:Int):Int{
        return a+b+extra
    }

    override fun sub(a:Int, b:Int):Int{
        return a-b+extra
    }

    fun mul(a:Int, b:Int):Int{
        return a*b
    }

    fun div(a:Int, b:Int):Int{return a/b}
}
on the Main method, we first create an instance of the Math3 class and use Math3 methods.
fun main(args: Array<String>){

    val math = Math3()
    println("add: ${math.add(20,21)}")
    println("add: ${math.sub(22,21)}")
}
Output-
add: 41
Sub: 1
Now time for Math4. use 4 methods and pass value 10.
val math2 = Math4(10)
println("add: ${math2.add(20,21)}")
println("sub: ${math2.sub(22,21)}")

println("mul: ${math2.mul(20,21)}")
println("div: ${math2.div(22,21)}")
Output-
add: 51
sub: 11
mul: 420
div: 1
Now compare two those output. you see 10 different in the result of add and sub.
Main Method-
fun main(args: Array<String>){

    val math = Math3()
    println("add: ${math.add(20,21)}")
    println("Sub: ${math.sub(22,21)}")

    val math2 = Math4(10)
    println("add: ${math2.add(20,21)}")
    println("sub: ${math2.sub(22,21)}")

    println("mul: ${math2.mul(20,21)}")
    println("div: ${math2.div(22,21)}")

}
Output-
add: 41
Sub: 1
add: 51
sub: 11
mul: 420
div: 1
That's it.
Now we learn how we can modify one class methods in other class.

Thank you for reading this post

Happy coding.

Read More

Friday, July 14, 2017

Kotlin OOP: Inheritance

July 14, 2017

Welcome to kotlin Series

Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding

This is the third post about Kotlin OOP. In this post, we are going to cover Kotlin Inheritance.
Let's start-
First, create a class named Math. This class contains two function name add and sub.

add method -> take two integers and return the addition result of that two integers.
sub method -> also take two integers and return the subtracted result of two integers.

Full math class code-
class Math {

  fun add(a:Int, b:Int):Int{
  return a+b
  }

  fun sub(a:Int, b:Int):Int{
  return a-b
  }
}
Now we create a new class and the class name is Math2. see the code-
class Math2 {

  fun mul(a:Int, b:Int):Int{
  return a*b
  }

  fun div(a:Int, b:Int):Int{return a/b}
}
Now we inherited Math class to Math2. But you get some error. Because by default all the class is final. So you can not modify the class. So that we need to modify the Math class and open keyword before class Math
open class Math {
//some code
}
Now the error will be solved. See the code-
class Math2 : Math(){

  fun mul(a:Int, b:Int):Int{
  return a*b
  }

  fun div(a:Int, b:Int):Int{return a/b}
}
Now in the main method- create a math instance and print use those the two method-
val math = Math()
println("add: ${math.add(20,21)}")
println("add: ${math.sub(22,21)}")
output-
add: 41
add: 1
so we see that we can an easily use add and sub-methods. Now we create the Math2 instance. Through this instance, we can use 4 methods. two class method and Math class method.
Let see-
val math2 = Math2()
println("add: ${math2.add(20,21)}")
println("sub: ${math2.sub(22,21)}")

println("mul: ${math2.mul(20,21)}")
println("div: ${math2.div(22,21)}")
see we use both Math and Math2 class methods.
Output-
add: 41
sub: 1
mul: 420
div: 1
Full main method-
fun main(args: Array<String>){

  val math = Math()
  println("add: ${math.add(20,21)}")
  println("add: ${math.sub(22,21)}")

  val math2 = Math2()
  println("add: ${math2.add(20,21)}")
  println("sub: ${math2.sub(22,21)}")

  println("mul: ${math2.mul(20,21)}")
  println("div: ${math2.div(22,21)}")

}
Output:
add: 41
add: 1
add: 41
sub: 1
mul: 420
div: 1

That's all. In this post, we learn about Kotlin inheritance. In Android app development we use this concept a lot.

Thanks for reading this post.

Happy coding.

Read More

Kotlin OOP : Constructor

July 14, 2017

Welcome to kotlin Series


Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding

This is the second post about Kotlin OOP Concept. In the previous post,  Kotlin OOP: Basic
we talk about a basic opp concept.
In this post, we are going to litter deeper.
Let's start-
From the previous post, we create an Apple class like previous.
let do this-
private class Apple(color:String,shape:String){

  var color:String? = null
  var shape:String? = null

  init {
  //println("Color: $color")
  //println("Shape: $shape")

  this.color = color
  this.shape = shape
  }

  fun GetColor():String?{
  return this.color
  }

  fun GetShape():String?{
  return this.shape
  }

}
In this class, we are working with the primary constructor. But If we have another option to working with the second constructor. Just like Java. How can I do this? Let's start- Let's make the primary constructor empty
private class Apple3(){
}
and declarer secondary constructor like below-
constructor(color:String,shape:String): this() {
}
Now declare class two class variable and assign it in the constructor.
var color:String? = null
var shape:String? = null
assign it-
//second constrictor
constructor(color:String,shape:String): this() {
  this.color = color
  this.shape = shape
}
Greater and setter method already there Check full class code-
private class Apple(){

  var color:String? = null
  var shape:String? = null

  //second constrictor
  constructor(color:String,shape:String): this() {
  this.color = color
  this.shape = shape
  }

  fun GetColor():String?{
  return this.color
  }

  fun GetShape():String?{
  return this.shape
  }

}
test this on the Main method-
fun main(args: Array<String>){
  val apple =Apple3("red","oval")

  println("Color: ${apple.GetColor()} Shape: ${apple.GetShape()}")
}
output-
Color: red Shape: oval
This is very similar to Java code. But if you are using this secondary constructor. you can not create a variable like the primary constructor.

This is a very smaller post. In this post we cover constructor. Some you need the secondary constructor and some time you need the primary constructor. If you come from Java then you should go through the secondary constructor. Then it looks link java. So you feel easy to learn Kotlin. Keep learning.

Thank you for reading this post.
Happy coding.

Read More

Kotlin OOP: Basic

July 14, 2017

Welcome to kotlin Series

Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding

In this post, we are going to cover object-oriented programming concept with kotlin. In kotlin, all the item is an object. So we are going to create an object name apple. and it has two properties color and shape. Let's create an Apple object class-
private class Apple(color:String,shape:String){
}
now we are going to create two class variable and this variable can nullable. Those are color and shape
var color:String? = null
var shape:String? = null
Now initialize this value in init{}
init {
   this.color = color
   this.shape = shape
}
Not: it just like Java constructor. In java you assign your class variable in the constructor it works just like that. Now we are going to create two methods that return shape and color. Those methods are like Java getter method
fun GetColor():String?{
    return this.color
}

fun GetShape():String?{
    return this.shape
}
oh! we finished the apple class. you check my full apple class code.
private class Apple(color:String,shape:String){

    var color:String? = null
    var shape:String? = null

    init {
        this.color = color
        this.shape = shape
    }

    fun GetColor():String?{
        return this.color
    }

    fun GetShape():String?{
        return this.shape
    }

}
Now time to test this apple class.
Create a main Method-
fun main(args: Array<String>){
}
create a variable name apple and assign to apple class.
val apple =Apple("red","oval")
print apple color and shape-
println("Color: ${apple.GetColor()} Shape: ${apple.GetShape()}")
complete Main method-
fun main(args: Array<String>){
    val apple =Apple("red","oval")

    println("Color: ${apple.GetColor()} Shape: ${apple.GetShape()}")
}
Output:
Color: red Shape: oval
This code like too similar to Java. I try to make it similar to java. But we are learning new language Kotlin. we can make this class is very small through Kotlin concept. we make a new class Apple2. It also has same properties like color and shape.
Let's do that.
code-
class Apple2(var color: String, var shape: String)
our Apple class is complete in just one line. We don't need any greater or setter methods. No extra constructor need.
Let's test this apple class and check the output is same.
fun main(args: Array<String>){
    val apple =Apple2("red","oval")
    println("Color: ${apple.color} Shape: ${apple.shape}")
}
Output
Color: red Shape: oval
So we see that output is same. We don't need to write more code. Another big advantage is that you can define default value when you create the class variable.
See this-
private class Apple2(var color: String = "red",
                     var shape: String = "oval")
on the main method
val deafult = Apple2()
println("Color: ${deafult.color} Shape: ${deafult.shape}")
See we don't pass any value. Those values come from the default value when you assign it.
Output-
Color: red Shape: oval
we can also assign value through variable wise.
see the code-
val appleGreen = Apple2(color = "red",shape = "round")
This is very helpful when you have many variables in your constructor. So you don't check again and again is the value is assigned the correct one.
Check the main method-
val appleGreen = Apple2(color = "red",shape = "round")
println("Color: ${appleGreen.color} Shape: ${appleGreen.shape}")
Output
Color: red Shape: round
Full main Method code-
fun main(args: Array<String>){
    val apple =Apple2("red","oval")
    println("Color: ${apple.color} Shape: ${apple.shape}")

    val deafult = Apple2()
    println("Color: ${deafult.color} Shape: ${deafult.shape}")

    val appleGreen = Apple2(color = "red",shape = "round")
    println("Color: ${appleGreen.color} Shape: ${appleGreen.shape}")

}
and output is
Color: red Shape: oval
Color: red Shape: oval
Color: red Shape: round
That's it today. Thank you for reading this post.

Happy coding

Read More

Friday, June 23, 2017

Android: Job Scheduler schedule you job

June 23, 2017

Welcome to the android tutorial.
android
Android

In this post, we talk about JobSchedular. A job scheduler is more effective than alarm manager. Want to see it benefits then check out this link.

For scheduling, you have many options to use.
1. Android Alarm manager
2. Job Scheduler
3. Gcm Network Manager

In the previous post, we talk about android alarm manager. Are you confused about those? which one is appropriate for your android app. Read this document Become a pro at scheduling tasks in Android

Now come to code- Before starting we have to add below line in the build.gradle file
compile 'com.firebase:firebase-jobdispatcher:0.5.0'
Now we need to a service class. Create a services class and extend it to JobService. In this case, my class name is EverydayJobTask.java
public class EverydayJobTask extends JobService {
}
we need to override two class-
1. onStartJob()
2. onStopJob()

onStartJob() will call when the job is started. So we need to implement the start logic in this methods.
onStopJob() will call after job will finish. In my case, I show a notification on start Job.

Full Java code of service class-
public class EverydayJobTask extends JobService {

  @Override
  public boolean onStartJob(JobParameters job) {

  //if job schedule then set a notification
  TaskNotification.notify(EverydayJobTask.this,
  "Start sync Task... ", 0);

  return true;
  }

  @Override
  public boolean onStopJob(JobParameters job) {
  return true;
  }
}
Now we need to build FirebaseJobDispatcher. we need to create a google play driver
Driver driver = new GooglePlayDriver(context);
now create a firebase job dispatcher variable and pass this driver
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
next step is to create a job this job will help to do the task with time-
Job syncJob = dispatcher.newJobBuilder()
set service to the job by calling setService and parameter will be a service class and its super class must be JobService.
.setService(EverydayJobTask.class)
set a tag and this tag must be unique. this tag is used to identify this job.
.setTag("Everyday_Task")
set it's lifetime by calling setLifeTime(). setLifetime sets how long this job should persist you two option
1. UNTIL_NEXT_BOOT
2.FOREVER
.setLifetime(Lifetime.FOREVER)
set a Network constraints on which this Job should run. You have some option
1. DEVICE_CHARGING -> the will be run only while the device is running.
2. ON_ANY_NETWORK -> for this case job will be running on any network
3. ON_UNMETERED_NETWORK-> on unmetered connection.

In my case, I set on any network
.setConstraints(Constraint.ON_ANY_NETWORK)
Note: It might be a good idea to include a preference for this, as some users may not want to download any data on their mobile plan.

set trigger for the job to start by calling setTrigger and the parameter will be another method Trigger.executionWindow(). This method has two parameters.The first argument for * which the data should be synced Note: this end time is not * guaranteed, but is more of a guideline for FirebaseJobDispatcher to go off we need two time interval time and flex time for that add those below line-
private static final int HOURS = 3;
private static final int INTERVAL_SECONDS = (int) TimeUnit.HOURS.toSeconds(HOURS);
private static final int FLEXTIME_SECONDS = INTERVAL_SECONDS / 3;
Note: I set interval time three hours. If you want to set more hour then change hours variable. After that add below code-
.setTrigger(Trigger.executionWindow(INTERVAL_SECONDS,INTERVAL_SECONDS+FLEXTIME_SECONDS))
If you want to set this job requiring the set true in the setRecurring or don't set false-
.setRecurring(true)
once the job is finished then call build method. this method has returned a job.
.build();
we finished making the job. But we have one more step to finish. we need to set schedule this job with the dispatcher.
dispatcher.schedule(syncJob);

oh! we done. Now I think you can use this job scheduler in your next android project.
That's it's today post
Happy coding.

Read More

Tuesday, June 20, 2017

Kotlin: Array and Loop

June 20, 2017

Welcome to kotlin Series

kotlin
Kotlin Series

In this post, we are going to learn about Array. The array is really helpful for saving the collection of data. Let's start- we declare a variable and name arrays and assign with Array.
val arrays = Array(5) { 0 }
Now currently our arrays variable has only one index and index position is 0 now add some other index and also print an index for checking.
val arrays = Array(5) { 0 }

arrays[1] = 1
arrays[2] = 2
println(arrays[2])
Note: here Array(5) it indicates that it's size is 5. See an another example-
val arrayStr = Array(5) { "Shudipto" }
arrays[1] = 2
println(arrayStr[0])
Code analysis-
if we don't define this array with a data type then we can insert any type of data type in it. Now add an another variable and initialize it by calling listOf()
val arraysNew = listOf(1, "shudipto", 2.5, 0.234, "Trafder", false)
Code analysis- you might notice that in this array we insert
1. integer
2. string
3. double
4. float
5. boolean
many data types. It's work fine. we don't put the same type of data in the array. That's are array declaring.

Now we use some practices with the loop that's print all the value in an array. first, we using while loop we create a variable that value is zero first and after working with loop this value will increase.
While Loop
var size = 0

//using while loop
while (size < arraysNew.size) {
    println("Position $size value ${arraysNew[size]}")
    size++

}
For Loop:
// using for loop
for (i in arraysNew) {
    println("value: $i")
}
Note: here i is predefined in kotlin it looks like Val i If we want to print value with position then we need two variable in for loop. In the previous we have one variable now we need two variables. How can we do that? see the code-
for ((position, i) in arraysNew.withIndex()) {
     println("position: $position value: $i")
}
Now we do some advance practice: 1. we create a variable and fill this variable this user input after that we show all the data that in the array we for loop(essay to use). we also know how to use for loop.(we just learn it)
for ((position) in arrayFill.withIndex()) {
    print("Insert a value:")
    val input = readLine()!!.toInt()
    arrayFill[position] = input
}
Code Analysis: we need the only position so we declare only one variable. (In the previous code we work with two variables and because we also learn the value along with the position). we also need an array with the index. if don't understand below the line, ignore this list for now. This is null safety. I will talk about null safety in another post.
val input = readLine()!!.toInt()
Now time to print what we are inserted in the array. Try yourself. You already learn how to print all the data of any array. Code-
for ((position, i) in arrayFill.withIndex()) {
    println("position: $position value: $i")
}
Today Full Code-
/**
 * Created by Shudipto Trafder on 6/20/2017.
 */

fun main(args: Array<String>) {

    val arrays = Array(5) { 0 }

    arrays[1] = 1
    arrays[2] = 2
    println(arrays[2])

    val arrayStr = Array(5) { "Shudipto" }
    arrays[1] = 2
    println(arrayStr[0])

    val arraysNew = listOf(1, "shudipto", 2.5, 0.234, "Trafder", false)

    var size = 0

    //using while loop
    while (size < arraysNew.size) {
        println("Position $size value ${arraysNew[size]}")
        size++

    }

    // using for loop
    for (i in arraysNew) {
        println("value: $i")
    }

    for ((position, i) in arraysNew.withIndex()) {
        println("position: $position value: $i")
    }

    println("Please help us to fill some data")
    val arrayFill = Array(5) { 0 }
    for ((position) in arrayFill.withIndex()) {
        print("Insert a value:")
        val input = readLine()!!.toInt()
        arrayFill[position] = input
    }

    println("Your inserted data")
    for ((position, i) in arrayFill.withIndex()) {
        println("position: $position value: $i")
    }
}

Thank you very much for reading this post.
Happy coding

Read More

Friday, June 16, 2017

Android: Alarm Manger with broadcast receiver

June 16, 2017

Welcome to this post. In this post, we are going to learn about Alarm manager and BroadCast Receiver. As usual before start please check official documentation.
1.Alarm Manager official documentation
2.BroadCast Receiver official documentation

Alarm manager is used for scheduling task. If you want to do a task after some time intervals or if want to do some task at 11 am. of the daytime, you have to use alarm manager. Because there is a possibility that user is not using this app at that particular time. So If you are using alarm manager and schedule some task then you don't have to tense about your task is executed or not. More accurately, when phone time is 11.am (example time) then system send a broadcast and from the broadcast receiver, you can receive this signal and execute the task.

Ok, enough talk.

First Alarm Manager-

* we have to create a calendar variable like-
Calendar calendar = Calendar.getInstance();
Now set a time when you do the task. In this case, I want to set 23.59.00 this time. you can also set a specific date. But I don't need a date I just need time so I set time only. But you can also add a date in similar ways.
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,0);

Now we have to do-
 * create an alarm manager and get system alarm services
* create an Intent and Intent class must be a broadcast receiver extend the class (we will create in later in this post).
* set an intent action (so we can filter on broadcast receiver, in this case, I use package name)
* now create a pending intent and get broadcast receiver
*now set alarm manager with set repeating
see the code-
//alarm manager
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, TaskManager.class);
intent.setAction("com.blogspot.shudiptotrafder.lifeschedular");

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,

PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.setRepeating(AlarmManager.RTC_W
  AKEUP, calendar.getTimeInMillis(),
  AlarmManager.INTERVAL_DAY, pendingIntent);
Note: here I set interval time AlarmManager.INTERVAL_DAY so it will be trigger at once in every day. you can set a custom time limit.
That's it on alarm manager.

BroadCast Reciever 

the broadcast receiver receives system and custom broadcast. we also explain in the first section of this post. Create a class extend with the broadcast receiver
public class TaskManager extends BroadcastReceiver {
}
you have to override onRecive method.
@Override
public void onReceive(Context context, Intent intent) {
}
we check that if intent has the same action that we have passed through pending intent on alarm manager. If the answer is true then we do our task. For simplicity, I show a toast message.
if (intent.getAction().equalsIgnoreCase("com.blogspot.shudiptotrafder.lifeschedular")) {

  Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();
}
Now we have to declare this receiver on manifest (AndroidMenifest.xml)
<!-- Broadcast Receiver -->
<receiver
  android:name=".manager.TaskManager"
  android:enabled="true"
  android:exported="false">
  <intent-filter>
  <action android:name="com.blogspot.shudiptotrafder.lifeschedular"/>

  <category android:name="android.intent.category.DEFAULT"/>
  </intent-filter>
</receiver>
we set the specific broadcast receiver on the intent filter. If you want to receive more action then set on action tag. Full receiver class-
public class TaskManager extends BroadcastReceiver {
  
  @Override
  public void onReceive(Context context, Intent intent) {

  if (intent.getAction().equalsIgnoreCase("com.blogspot.shudiptotrafder.lifeschedular")) {

  Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();
}
That's all.
Happy coding.

Read More