Wednesday, August 16, 2017

Kotlin ArrayList

August 16, 2017

Welcome to kotlin Series

Kotlin

In this post, we are going to learn about ArrayList. In android the use of ArrayList is huge.
So let's move on today task list.
1. we create an ArrayList
2. insert some value
3. update some value
4. search in ArrayList
5. delete some value

Let's start:
Note: we discuss array and loop in this post Kotlin: Array and Loop. you can take a look at this post of array section it will help you to understand today's topics easily.
Create an instance of ArrayList class and make this variable as immutable by using val
val list = ArrayList<String>()
Now insert some value by calling add method
list.add("Shudipto")
list.add("Trafder")
list.add("Is")
list.add("a")
list.add("good")
list.add("student")
Now print the first element of this array list
println("First Name:${list[0]}")
Result:
First Name:Shudipto
Now print all the element by using a for loop. see the code-
println("All element")
println("\nOnly value")
for (a in list){
     println("value:$a")
}
Output:
All element

Only value
value:Shudipto
value:Trafder
value:Is
value:a
value:good
value:student
Now print all the element with the index number. see the code-
println("\nIndex with value")
for ((position,a) in list.withIndex()){
    println("Index:$position value:$a")
}
Output:
Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:a
Index:4 value:good
Index:5 value:student
Now update an element-
we update the value of index number 5.
The new value will be developer.
println("\n\nUpdate an element")
list[5] = "developer"
Now print all the value with index
println("\nIndex with value")
for ((position,a) in list.withIndex()){
     println("Index:$position value:$a")
}
Output:
Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:a
Index:4 value:good
Index:5 value:developer
Search in ArrayList: we make a search in our ArrayList.
If we found the data and we print name found and if not we print name not found.
see the code below
println("\n\nSearch in array list")
if (list.contains("Shudipto")){
    println("Name found")
} else println("Not found")
Output:
Search in array list
Name found
Now delete some data: we can remove by two ways.
1. by value
2. by index number
I am showing you those two ways by the value, we remove "a" by index number, we remove index number 5
see the code below
println("Delete some data")
//with value
list.remove("a")
//with position
list.removeAt(4)
Note: in code, we use index number 4 because we just remove one element so the last index number is now 4.
Now print all the value with index number
println("\nIndex with value")
for ((position,a) in list.withIndex()){
     println("Index:$position value:$a")
}
Output:
Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:good
Today's full code:
fun main(args: Array<String>) {

    val list = ArrayList<String>()

    list.add("Shudipto")
    list.add("Trafder")
    list.add("Is")
    list.add("a")
    list.add("good")
    list.add("student")

    println("First Name:${list[0]}") //list.get(0)

    println("All element")
    println("\nOnly value")
    for (a in list){
        println("value:$a")
    }

    println("\nIndex with value")
    for ((position,a) in list.withIndex()){
        println("Index:$position value:$a")
    }

    println("\n\nUpdate an element")
    //list.set(5,"developer")
    list[5] = "developer"

    println("All element")
    println("\nOnly value")
    for (a in list){
        println("value:$a")
    }

    println("\nIndex with value")
    for ((position,a) in list.withIndex()){
        println("Index:$position value:$a")
    }

    println("\n\nSearch in array list")
    if (list.contains("Shudipto")){
        println("Name found")
    } else println("Not found")

    println("Delete some data")
    //with value
    list.remove("a")
    //with position
    list.removeAt(4)

    println("\nIndex with value")
    for ((position,a) in list.withIndex()){
        println("Index:$position value:$a")
    }
}
Full output:
First Name:Shudipto
All element

Only value
value:Shudipto
value:Trafder
value:Is
value:a
value:good
value:student

Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:a
Index:4 value:good
Index:5 value:student


Update an element
All element

Only value
value:Shudipto
value:Trafder
value:Is
value:a
value:good
value:developer

Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:a
Index:4 value:good
Index:5 value:developer


Search in array list
Name found
Delete some data

Index with value
Index:0 value:Shudipto
Index:1 value:Trafder
Index:2 value:Is
Index:3 value:good

Process finished with exit code 0
Thank you for reading this post.
Happy coding

Read More

Tuesday, August 15, 2017

Kotlin: File reader and writer

August 15, 2017

Welcome to kotlin Series

Kotlin


In this post, we are going to learn about kotlin IO (input or output)

we basically learn about file reader and writer.
In this post, we are going to write a program that takes text from the console and save it on computer hard disk as a text file.
Let start-

First, we are going to create a method for saving file, method name writeToFile
Follow those step:
1. take a String parameter
 2. Create an instance of FileWriter
3. in try-catch block write this string by using write method.
See the code-
fun writeToFile(str: String) {

    val writer = FileWriter("text.txt", true)

    try {
        writer.write(str+"\n")

    } catch (ex: Exception) {
        println(ex.message)

    } finally {
        writer.close()
    }
}
Now time to create the Main method-
in the main method-
1. first we show a message to user to write some text
2. take those text and save in on a variable
3. after the call the writeToFile method and parameter is this variable.
see the code-
fun main(args: Array<String>) {
    println("Write a message")
    val str: String = readLine().toString()

    writeToFile(str)

}


Now time to read this text file and print the text in the console-
Follow those step-
1.create a method name readFile()
2. in try-catch block create an instance of FileReader class
3. print text to the console by using readText() method
see the code-
fun readFile(){

    try {
        val read = FileReader("text.txt")

        println(read.readText())


    } catch (e:Exception){
        println(e.message)
    }

}
In the main method, call this method-
fun main(args: Array<String>) {
    println("Write a message")
    val str: String = readLine().toString()

    writeToFile(str)

    readFile()

}

Now run this program-
after running the programming this will show you like below picture
input some text I input: Hello I am shudipto trafder

kotlin-io-code

Note: Green colored text is your input text and white color text is output text( that read from the file)
this is the text file that saved

kotlin-io-output

Thanks for reading this post.
Happy coding.

Read More

Saturday, August 12, 2017

Android studio: share code on Github and add SSH key to you Git

August 12, 2017

Welcome to this post. In this post, we are going to discuss how to share code on Git from Android Studio.

(I don't want to describe what is GitHub or why you need to use git. I just want to show you the process only)
Let's jump in.

Before share, you need to create a GitHub account click here for GitHub account.
After creating a GitHub account, you can now share your code into GitHub.

Open android studio. Now open an exciting project that you want to share.
Click on VCS on the main toolbar.
then import into version
after Share project on GitHub
Like below picture

Share Project into GitHub

You will get an error. To fix this error you need to add an SSH key.

Open git-bash
gitbash1


To add this you need to check first if you have any key open git-bash.
Now enter the command
ls -al ~/.ssh

if the key already exists you can jump on the copy to clip bord option.
If the key does not exist then you need to create a new key.
Follow this command-
ssh-keygen -t rsa -b 4096 -C "your@email.com"
in your@email.com you need to write your email that you used in GitHub account.

gitbash2

it will show-
Generating public/private rsa key pair.
When you're prompted to "Enter a file in which to save the key," press Enter if you want to save those file in the default location.
Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]
now enter your password.
Note for the beginner: If you enter your password it will not showing anything (even no start).
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
your password must be same. your SSH key is created.
Now you need to add your SSH key to the ssh-agent before adding, you need to ensure the ssh-agent is running: to run ssh-agent-
eval $(ssh-agent -s)
Now add your ssh private key to ssh-agent
ssh-add ~/.ssh/id_rsa
Now run this command this command will copy the key into you clip bord.
clip < ~/.ssh/id_rsa.pub

show the picture
gitbash3

Time to add this key into you Github account.
Login your GitHub and go to Settings.
Select SSH and GPG key Now click New SSH key.

GitHub account


write the title as you want and the key will be your copied key.
press ctrl+c button to paste the copied key.
and save this by pressing add SSH key.

That's it. It will be working fine

Now click on
VCS on the main toolbar.
then import into version
after Share project on GitHub

it will show like below picture

share1

if you are not logged in then it will prompt to login. Log in through your Github user name, and pass.

After login, it will show like this-
share2


Now write a short description about your project

share 4

it will promote like this 
share4

write commit message

And click ok.

Note: after you find a popup window of Git and login in with your GitHub account details.

It will share your project in Github.
Login to your Github account you will find your project.

Thanks for reading.
Hope you will post will help you and you are now able to share project on GitHub

Happy coding.

Read More

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