Monday, 20 July 2020

Android Development By KOTLIN

Using by Kotlin:

Here we use Kotlin Language for Development of Android Apps.

Intellij Ide is used to compile and run Kotlin codes. Kotlin is mainly based on JAVA Language. 

some examples from beginner to advanced are shown here

**We use ctrl+shift+F10 for compile and run code in Intellije IDE

            Code:

fun main()
{
var wholenumber=18
var fractionalNumber=3.5
var sentence="A new sentence"
var condition=false
var a:Int=5
var str:String="Trainings"

var number=2345
var decimal=5.6
var name="Intershala"
var conditions=true

wholenumber=wholenumber+40
fractionalNumber=38.56
sentence="Another Sentence "

println(wholenumber)
println(fractionalNumber)
println(sentence)
println(condition)

println(number)
println(decimal)
println(name)
println(conditions)
println(a)
println(str)

wholenumber=wholenumber+40
}

**We can't change Values in Val variable but we can change values in Var variables.


fun main()
{
val number1 = 12.5
val number2 = 3.5
val a =20.5
val b=40.7

var result: Double
var result2:Boolean

val s="Make my miki app"
val stringLength=s.length
val stringIndex = s.get(8)


result2 = a == b
println(result2)

result = number1+number2
println(result)

result = number1-number2
println(result)

result = number1 * number2
println(result)

result = number1 % number2
println(result)


print("The Length of the character is:")
println(stringLength)
print("The character at index 12 is:")
println(stringIndex)

println("The Character index 12 is:${s.get(8)}")


val i = 10
println("The Value of i is $i")
println("The Value of a is $a")

println(s.subSequence(0,8))
println(s.length)

}

fun main(){
iAmANewFunction()
iAmANewFunction2()
timesTwo(23 )
println(timesTwo(23))
}

fun iAmANewFunction(): Unit {
println("I am your new function")
}
fun iAmANewFunction2() = println("Hello the world of App")

fun timesTwo(x: Int) : Int {

return x*2
}

import com.sun.xml.internal.fastinfoset.util.StringArray
import java.util.*

fun main()
{
var characterArray = arrayOf('h','a','c','k','e','r')
val characArray = arrayOf('h','a','c','k')

var otherArray = arrayOf('h','a','c','k','i','n')

characterArray = otherArray

val StringArray = arrayOf("Hello","You","are","hacked")

val newArray = arrayOf("Hello",12,34.5,true,'x')

println(characArray.get(0))
println(StringArray.get(1))



println(StringArray.size)



println(StringArray.contentToString())

}
fun main()
{
val a=10
val b=5

if(b == 0)
{
println("Division cannot be performed")

}
else
{
println(a/b)
}
}




fun main(){

val num =2
when(num)
{
0 -> println("Zero")
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("None of the Above")

}
}

fun main()
{
val a:Int=2
when
{
a > 0 -> println("Positive")
a == 0 -> println("Zero")
else->
{
println("Negative")
}
}
}
fun main()
{
for(i in 1..10)
{
println(i)
}

val a= arrayOf("a","b","c","d","e","f")
for (i in 0 until a.size){
println("${a[i]}")
}
for(i in 1..10 step 2)
{
println(i)
}

}
//Using of List instead of Array
fun main()
{
val listOfStrings = listOf<String>("Box","Table","Chair") //Immutable List

println(listOfStrings)

val listOfString = mutableListOf("Box","Pen","Table") //Muatable List

listOfString[1]="River"

listOfString.add("TV")

listOfString.add(index = 2, element = "Air Conditioner")

listOfString.removeAt( index = 3)

val arr=arrayOf("Fan","Lights","Mattress")

listOfString.addAll(arr)


print(listOfString)

}
That's are some basic codes. as it is based on Java language so we can handle the exception here as we can handle in Java.

fun main()
{
var arr=arrayOf( 2, 3 , 5, 8)

try{
arr[4]=7
}
catch (e: ArrayIndexOutOfBoundsException)
{

}
finally {
println(arr[2])
}
}
**It is not necessary to execute finally statement in everytime when we are writing the code.


fun main()
{
var arr=arrayOf( 2, 3 , 5, 8)

try{
arr[4]=7
println("I am learning Kotlin")
}
catch (e: ArrayIndexOutOfBoundsException)
{
println("I ran and caught catch body")
}

println(arr[2])
}
Output: 
I ran and caught catch body
5

** So the try-catch body try stoped the execution-only catch executes.

Exceptions are two types: Arithmetic & array bound exception.

    A mostly Billion Dollar Exception is Null-Pointer-Exception(NPE) : This occurs Compiler expects a value for a variable but instead gets NULL(no value).


fun main()
{
var nullValue:String? = null //Null Value & String? is nullsafety operator

println(nullValue)
}

** Null-safety operator: A operator which tells the compiler that value of the particular variable may be Null.


Here we can't use string.indexOf() or string.length() but here we have to use string?.indexOf() or string?.length(). As our IDE suggest us to use non-null string!!.length but when we use it IDE throws an exception error because it returns a non-null value and program crashes.

  • If We want to print some other massage without the null value then we use Elvis (?:) operator

fun main()
{
var nullValue:String? = null

println(nullValue?.length ?: "This is null") //here we use elvis operator
}
here the operator tells the compiler if the length of the string has some length then print that otherwise print that message.

Print Values of an array without getting null values: 

fun main()
{
val arr= listOf(3,5,null,6,8,9)
val arr2= arrayListOf("You","are",null,"Hacked!!")

println("Mutable List wihout null value is ${arr.filterNotNull()}")
println("String array wihout null value is ${arr2.filterNotNull()}")
}

** we use filterNotNull() function to filter out null values.

CONCEPT OF OOPS: organising and structuring code using objects.



 
    
Using Class & Object codes :
class Dog {                         //Creation of class
var breed:String="Labrador"
var color:String="Brown"
var age:Int=3

fun bark()
{
println("${breed} is barking")
}
fun eat()
{
println("${color} colored dog eat everything")
}

}
fun main(){

var dog1=Dog() //creation of object
dog1.bark()
dog1.eat()
}
** We can also change the properties in the main function

class Dog {
var breed:String="Labrador" //properties
var color:String="Brown"
var age:Int=3

fun bark()
{
println("${breed} is barking")
}
fun eat()
{
println("${color} colored dog eat everything")
}

}
fun main(){

var dog1=Dog()

dog1.breed="Alchecian"
dog1.color="Light Brown"
dog1.age=5

println("The breed of dog is ${dog1.breed} whose color is ${dog1.color} and is ${dog1.age}
 years old")

dog1.bark()
dog1.eat()
}

Constructor: Special kind of member function that is used to initialize the state or properties of the newly created objects of a class. 

    The constructor is written inside the class, but it gets invoked when you create an instance of the class(objects).

    Constructors are required to create an object of a class.

** If your class does not have a constructor then the contractor create a default constructor for that class...


Primary Constructor Code :

class Dog (breed:String,color:String,age:Int){ // constructor variable
var breed:String //member variable
var color:String
var age:Int

init{
this.breed=breed // initialization of constructor variables and member variables
this.color=color
this.age=age
}

fun bark()
{
println("${breed} is barking")
}
fun eat()
{
println("${color} colored dog eat everything")
}

}
fun main(){

var dog1=Dog()

dog1.breed="Alchecian"
dog1.color="Light Brown"
dog1.age=5

println("The breed of dog is ${dog1.breed} whose color is ${dog1.color} and is ${dog1.age} years old")

dog1.bark()
dog1.eat()
}

We can also shorten the code again just keep your cursor on grey line of IDE and press ALT+Enter.

class Dog (var breed: String, var color: String, var age: Int){

fun bark()
{
println("${breed} is barking")
}
fun eat()
{
println("${color} colored dog eat everything")
}

}
fun main(){

var dog1=Dog()

dog1.breed="Alchecian"
dog1.color="Light Brown"
dog1.age=5

println("The breed of dog is ${dog1.breed} whose color is ${dog1.color} and is ${dog1.age} years old")

dog1.bark()
dog1.eat()
}

Secondary Constructor:

Has two types 1. Only Secondary Constructor

2.Both Primary & Secondary Constructor

1.example of First topic

class secondaryconstructor {
var breed:String
var color:String
var age:Int

constructor(breed:String,color:String,age:Int){
this.breed=breed
this.color=color
this.age=age

}
}
fun main()
{

}

2.example of the Second topic


 class secondaryconstructor (breed: String,color:String,age: Int){

    var name: String? =null

constructor(breed:String,color:String,age:Int,name:String):this(breed, color, age){
this.name=name

}
}
fun main()
{
val dog=secondaryconstructor("Labrador","Brown",3)
val dog4=secondaryconstructor("Germen Sepherd","grey",2,"Jerry")
}


Problem Statement: 
Create a class called 'Restaurants' This class will have three properties -'name','rating', and 'costForOne'.

create 3 objects of this class. print out all the values of these objects.

Code:
     ** Make a class file and type this class code
class restaurant(var name:String,var ratings:Double,var costForOne:Int)
   **Make a main kotlin file and type this line
fun main()
{
val rest1=restaurant("The Taj Hotel",4.2,1200)
val rest2=restaurant("Hotel Grand caninan",4.5,800)
val rest3=restaurant("Hacker's Paradise",4.0,650)

println(rest1)
println(rest2)
println(rest3)
}

Output:  

restaurant@610455d6

restaurant@511d50c0

restaurant@60e53b93

      //so I know some errors occur here below codes how to solve that thing

data class restaurant(var name:String,var ratings:Double,var costForOne:Int)

** For printing the values of objects you have to make the class into data class.  

Data-class:  Data class is just like a regular class that holds some data. when we develop android apps then we need lots of classes that not really perform any functions just hold some data.


Now if we want to short and use loops for this problem statement:

fun main()
{
val rest1=restaurant("The Taj Hotel",4.2,1200)
val rest2=restaurant("Hotel Grand caninan",4.5,800)
val rest3=restaurant("Hacker's Paradise",4.0,650)

var restaurantlist= mutableListOf(rest1)
restaurantlist.add(rest2)
restaurantlist.add(rest3)

for(rest in restaurantlist)
{
println(rest)
}
}

  • Data Classes are used to store data
  • They help us to perform operations directly on the data stored in the objects of a class.
  • They help us in omitting redundant code
  • A primary constructor of a data class must always have at least one parameter.


Now we want to use classes of class so here the concept of Inheritance came.


Two classes Dogs and cats but these two classes have the same functions eat and sleep but the bark & purr function is not the same so we use concept of Inheritance here to reduce the code.


  • Inheritance is one of the key concepts of Objects oriented programming(OOP).
  • It enables re-usability, that is, it allows a class to inherit features from another class.
  • The class that inherits the features is called the Child class.
  • The class whose features are inherited is called Parent class

The syntax for creating parent class :

   ** keyword open allows this class for reusuable.

The syntax for creating Child Class:

Now below the code is an example of this procedure.

We create parent animal class

open class animals (var legs:Int,var color:String){
fun eat()
{
println("I eat food")
}
fun sleep(){
println("I sleep")
}

}

Then create the child classes:

class Dog(legs:Int,color:String):animals(legs,color) {
fun bark(){
println("Dog is Barking")
}
}


class cat(legs:Int,color:String):animals(legs,color) {
fun purr(){
println("I purr")
}
}

After that, We create the main class

fun main(){
val dog1=Dog(4,"Brown")
dog1.eat()
dog1.sleep()
dog1.bark()

val cat1=cat(4,"white")
cat1.eat()
cat1.sleep()
cat1.purr()

}

**Visibility Modifiers :

                    Visibility modifiers are keywords that help us set the visibility or accessibility of variables, functions, classes, objects, constructors etc.

4 types of Visibility modifiers in Kotlin:
  1. Public
  2. Private
  3. Protected
  4. Internal

Public: Accessible from anywhere
private: accessed only within the file where it is declared.
protected: visible or accessible only within the class and its subclasses 
                      **Top-level function cannot be declared protected.
Internal: accessible only within the module.
                       **Module is a set of dies compiled together.



 


In Kotlin, we can only inherit the child class for the parent class but if we need to inherit child classes from multiple parent classes we use Interface.

after that override concept come that same as Java.

Some example codes of Interface:

we create an Interface
interface MyInterface {
fun hello() //function without any implementation
fun greeting()=println("Hello hackers!!") //function with default information
}
Then write the class of an Interface

class CallMe:MyInterface,NewInterface {
override fun hello(){ //here we are overriding the function hello
println("Function hello is called here")

}

override fun greeting() {
println("You are caught Hackers!!")
}

override fun newMethod() { //addded after creating the NewInterface
println("Function of New Interface")
}
}

now create another Interface:
interface NewInterface {
fun newMethod()
}

then create the main files with the objects of the classes:

fun main(){
val a=CallMe()

a.hello()
a.greeting()
a.newMethod()

}


Now come to the most interesting part that is called Android Studio.


1st one is the name of the app
2nd is the domain of the company -- make sure you give a unique package name 




see here package names are highlighted and that is unique.


It's in the apps then manifest...there XML file 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.learning.activitylifecycle"> //Parent tag

<application //Child Tag
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">
<activity android:name=".MainActivity"> //child tag of the application tag
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>
<manifest> is a tag
xmlns: android is an attribute
http://schemas.android.com/apk/res/android
this line is the values of the attribute.


now xmlns is broken down to XML and ns where ns stands for Namespace.

The value given to this xmlns attribute is URI(Uniform Resource Identifier): that tells the compiler about the place. This place is called Namespace.

    

now come to the next folder. Java where all the Kotlin codes are present.
here all the codes and packages are kept in MainActivity .


Here in this res folder, all the resources are placed that we will use to build this app.



Here the full folder structure of resources folder. 

Now all the images and design files are present in the drawable directory.
all the layout files will be placed and inside the layout folder.
then mipmap directory contains the app launcher icon.
then the values directory contains the values used in XML files.



here in Gradle Scripts here kotlin version to android studio version all info are present.
now check the code would you find anything exciting in repositories??
Yeah google() and centre() I'm talking about.


here see compileSdkVersion is the current sdk version to compile our app.
now applicationId is the package Id that we give.
minSdkVersion is the minimum version of sdk which our app will run.
versionCode that we will change after uploading it on play-store.It is the version of the app.
versionName that is the version of the app that we see when we download it from play-store.

at least dependencies that are the external-libraries we use in the project.


Now after getting familiar with the android studio now we start our Coding part :
             **From here we use code tab to see and edit in codes, split and design to see the designs and codes in different manner.


Now our Project is Activity-Lifecycle. 
    
            so what is Activity: 
                                    Activity is a screen on our device which consists of a user interface. An activity provides the window in which the app draws its UI. 

                Now a app has many activity like If we consider Instagram. The first page of Instagram is the main activity 


   Main Activity
   **Now we open any persons profile that is a different activity and if we see any persons post that is another different activity.

Activity 1
This also Activity 1

This can be called Activity 2
Some points about Activity:
        An activity has different state like create, pause,stop, destroy etc.
        States are attained by an activity because of some events.
        An activity has different events like creation, pausing, destroying etc.
        These events are triggered by user interaction.










22 comments:

  1. Nice Post...


    We are having very interesting information regarding Hire A Hacker, Hire Hackers and Hire A Hacker for iPhone

    ReplyDelete
  2. Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 網上商店

    ReplyDelete
  3. I would state, you do the genuinely amazing.This substance is made to a wonderful degree well. Hacker for Hire

    ReplyDelete
  4. Excellent Blog, I like your blog and It is very informative. Thank you
    kotlin online course
    Learn kotlin online

    ReplyDelete
  5. Internet search engine optimization experts apply the modern analytics service, which has a positive affect a website. SEO companies are facing great competition in the SEO field. However, they introduce guaranteed SEO services to manage with the competition.
    app

    ReplyDelete
  6. I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. ecommerce solutions SLC

    ReplyDelete
  7. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work! diseñador de páginas web

    ReplyDelete
  8. I probably shouldn't be saying this here in public honestly, but let me introduce everyone to this experience genuine hacker. He is a professional and the best of hacking any iOS device & iCloud ID, Androids device & Google ID, Mac Book PC, and all Window system. He is called "Hacker Kaspersky" I have used his service and confirm how ethical standard he can handles social network Applications, He help hack my spouse phone, As my phone was linked with access to interact with target device as a remote operator. I can monitor my spouse iPhone11pro, Location, Facebook, Messenger, Instagram, WhatsApp, Hangout chats, Call logs and Notifications. Reach out to him for help via Email (hackerkasperskytech @ gmail com) Tell him I refer you.

    ReplyDelete
  9. Excellent Blog, I like your blog and It is very informative. Thank you
    Java
    Programming Language



    ReplyDelete
  10. It turns out that even the hottest port has a few places where you can get off the beaten path. Here are some recommendations that will make you feel like you're in the know
    luckia app android

    ReplyDelete
  11. I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up. android programming wallpapers

    ReplyDelete
  12. cool stuff you have got and you keep update all of us. ranking

    ReplyDelete
  13. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. https://601e860216774.site123.me/blog/wealth-contribution-to-society

    ReplyDelete
  14. I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing.
    SaaS Application Development Services

    ReplyDelete
  15. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. neak oknha chen zhi

    ReplyDelete
  16. Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information. https://sites.google.com/view/world-through-lens/best-cambodian-business-ideas-for-2021

    ReplyDelete
  17. Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks. https://sites.google.com/view/making-a-difference-21/best-9-reasons-to-do-business-in-cambodia

    ReplyDelete
  18. I have been reading many articles on the same issue but found this one uniquely written. You covered almost every point over the topic. I don’t feel need to read any other article on this topic now.
    mobile app development company

    ReplyDelete
  19. I love the way you write and share your niche! Very interesting and different! Keep it coming!
    best time to visit new zealand

    ReplyDelete
  20. Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing...
    net software development

    ReplyDelete

Web development with Html and PHP