battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

kotlin AS PL grimoire

power_settings_newLogin to reply
2 posters

descriptionkotlin AS PL grimoire Emptykotlin AS PL grimoire

more_horiz
kotlin is a new programming language for android studio
its main benefit is you no longer have to use findviewbyid, instead you
have to have a new name for each view in the app

click convert to java at the kotlin online play ground to convert :
https://play.kotlinlang.org/

also : kotlin projects can use java classes

to install an emulator :
avd manager, create virtual device
select webcam for the camera (on verify config screen on advanced settings
after installing an emulator)

or just use an actual device.

:tokushushoukan

Last edited by Moti Barski on Sun Feb 14, 2021 5:19 pm; edited 1 time in total

descriptionkotlin AS PL grimoire Emptykotlin hello world

more_horiz
open a new project as in android studio

in the java folder, 1st package, right click add a new kotlin class and call it main :

Code:

package com.example.hellokotlin

fun main(args: Array<String>){println("hello kotlin grimoire")}


to run click the arrow to the left of the code or the green arrow at the toolbar
or control + r to run on a Mac
:rlx:

descriptionkotlin AS PL grimoire Emptykotlin comment code

more_horiz
// comment
/* multi line comment
*/

descriptionkotlin AS PL grimoire Emptykotlin variables

more_horiz
var str ="hadouken";print(str) // string
var n = 4;print(n) // int
var numba:Int = 32; // explicit
var name:String = "chii"
println("$name is $numba") // string megazord

//optional (null or var):
var myDouble: Double? = null;myDouble = 45.1
print(myDouble)

var myBool: Boolean? = null;myBool = true

descriptionkotlin AS PL grimoire EmptyRe: kotlin AS PL grimoire

more_horiz
kotlin float var

Code:


fun main(args: Array<String>){println("hello kotlin")
    var myfloat: Float? = null;
    myfloat = 23.4F
    println(myfloat)

}


Chars :

Code:


var myChar = 'm'
    var newChar: Char? = null
    newChar = 'b'
    println("$myChar $newChar") // insert var into string


Constants :
Val pi =3.14;val url = "yotamarker.com"

Getting debatable input :

In a new kotlin file in the main activity dir :

Code:


fun main(args: Array<String>){println("hello kotlin")
    println("what is your name ?mo")
    var name = readLine()
    println("hi $name")

}

:nemui:

descriptionkotlin AS PL grimoire EmptyRe: kotlin AS PL grimoire

more_horiz
‪String megazording‬

Code:


‪var x:Float = 1f // explicit varing‬
‪var y:Float = 5f;println("div result is ${x/y}") // expresion in string‬
‪var z = 8;var z2:Float = z.toFloat() // convert var type‬
‪var x = 8;var y = 3;println("div result is ${x%y}") // remainder‬
‪var x = 8;println(--x)//decreament by one‬


Conditionals :
Same as java, for one line you can omit the {} :
if(1<2) println("hadouken")

Switch case :

Code:


var N1: Int
    println("type an integer")
    N1 = readLine()!!.toInt() // convert input to int
    when(N1){
        4 -> println("four")
        5 -> println("five")
        39 -> println("numba 39 kibou hope")
        else -> {println("unknown")}
    }


Loops :

for (item in 1..5){ println("hadouken") } // 1 to 5 loop
for (item in 1..5){ println("hadouken $item") } // hadouken 1 hadouken 2...

While loop :

Code:


var counter = 5
while(--counter>0){println(counter.toString())}


Do while loop :

Code:


var counter = 5
    do{println("shoryuken $counter")}
    while(--counter>0) //ctrt + r to run


New line : \n : use : print("hi \n hello")
:building:

descriptionkotlin AS PL grimoire Emptyinheritance

more_horiz

Code:

// Parent class
open class Computer(val name: String,
                    val brand: String) {
}

// Child class (initializes the parent class)
class Laptop(name: String,
            brand: String,
            val batteryLife: Double) : Computer(name, brand) {
 
}


open enables subclasses
here in the class signatures is the primary c'tor.

Code:

class Laptop : Computer {
    val batteryLife: Double

   // Calls super() to initialize the Parent class
    constructor(name: String, brand: String, batteryLife: Double): super(name, brand) {
        this.batteryLife = batteryLife
    }

   // Calls another constructor (which calls super())
    constructor(name: String, brand: String): this(name, brand, 0.0) {
       
    }
}


If the child class doesn’t have a primary constructor, then all of its secondary constructors have to initialize : the{} of the constructors.

****************************************************************

Inheritance Example with Properties and Member Functions

Code:

/**
 * BankAccount (Base Class)
 * @property accountNumber - Account Number (read-only)
 * @property accountName -  Account Name (read-only)
 * @property balance - Current Balance (Mutable)
 */

open class BankAccount(val accountNumber: String, val accountName: String) {
    var balance : Double = 0.0

    fun depositeMoney(amount: Double): Boolean {
        if(amount > 0) {
            balance += amount
            return true
        } else {
            return false
        }
    }

    fun withdrawMoney(amount: Double): Boolean {
        if(amount > balance) {
            return false
        } else {
            balance -= amount
            return true
        }
    }

}


its subclass :

Code:

/**
 * SavingsAccount (Derived Class)
 * @property interestRate - Interest Rate for SavingsAccount (read-only)
 * @constructor - Primary constructor for creating a Savings Account
 * @param accountNumber - Account Number (used to initialize BankAccount)
 * @param accountName - Account Name (used to initialize BankAccount)
 */

class SavingsAccount (accountNumber: String, accountName: String, val interestRate: Double) :
        BankAccount(accountNumber, accountName) {

    fun depositInterest() {
        val interest = balance * interestRate / 100
        this.depositeMoney(interest);
    }
}


Properties - accountNumber, accountName, balance
Methods - depositMoney, withdrawMoney

using it in a main function

Code:

fun main(args: Array<String>) {
    // Create a Savings Account with 6% interest rate
    val savingsAccount = SavingsAccount("64524627", "Rajeev Kumar Singh", 6.0)
   
    savingsAccount.depositeMoney(1000.0)
   
    savingsAccount.depositInterest()
   
    println("Current Balance = ${savingsAccount.balance}")
}


*********************************************************************

Overriding Member Functions :

Code:

open class Teacher {
    // Must use "open" modifier to allow child classes to override it
    open fun teach() {
        println("Teaching...")
    }
}

class MathsTeacher : Teacher() {
    // Must use "override" modifier to override a base class function
    override fun teach() {
        println("Teaching Maths...")
    }
}


main :

Code:

fun main(args: Array<String>) {
    val teacher = Teacher()
    val mathsTeacher = MathsTeacher()

    teacher.teach()  // Teaching...
    mathsTeacher.teach() // Teaching Maths..
}


********************************************

Overriding Properties

Just like functions, you can override the properties of a super class as well. To allow child classes to override a property of a parent class, you must annotate it with the open modifier.

Moreover, The child class must use override keyword for overriding a property of a parent class

Code:

open class Employee {
    // Use "open" modifier to allow child classes to override this property
    open val baseSalary: Double = 30000.0
}

class Programmer : Employee() {
    // Use "override" modifier to override the property of base class
    override val baseSalary: Double = 50000.0
}

fun main(args: Array<String>) {
    val employee = Employee()
    println(employee.baseSalary) // 30000.0

    val programmer = Programmer()
    println(programmer.baseSalary) // 50000.0
}


*********************************

override using setter :

Code:

open class Person {
    open var age: Int = 1
}

class CheckedPerson: Person() {
    override var age: Int = 1
        set(value) {
            field = if(value > 0) value else throw IllegalArgumentException("Age can not be negative")
        }
}

fun main(args: Array<String>) {
    val person = Person()
    person.age = -5 // Works

    val checkedPerson = CheckedPerson()
    checkedPerson.age = -5  // Throws IllegalArgumentException : Age can not be negative
}


Calling properties and functions of Super class

Code:

open class Employee {
    open val baseSalary: Double = 10000.0

    open fun displayDetails() {
        println("I am an Employee")
    }
}

class Developer: Employee() {
    override var baseSalary: Double = super.baseSalary + 10000.0

    override fun displayDetails() {
        super.displayDetails()
        println("I am a Developer")
    }
}
:FP:

descriptionkotlin AS PL grimoire Emptybonus post : installing intelliJ

more_horiz
Install JDK and save the install from the oracle.com file destination in a txt file
Install IntelliJ IDE a Kotlin programming environment from : jetbrains.com

Open a new project : create new project, (java, check kotlin(java)) or the (Kotlin,
Kotlin JVM).
Click create, check use library.

If you don't have project SDK selected in the new project window:
new JDK and navigate to the JDK install directory Choose the jdk newest folder, ok.

To set appearance : file, settings, appearance.
Or to change the font : editor, colors and fonts, fonts, save as: my scheme, now
You can change the font and font size.

***********************************************************************************

At the solution explorer window under src right click, new, kotlin file/ class,

Code:


fun main(args: Array<String>){
    println(l"hello world")
}

🤷

descriptionkotlin AS PL grimoire EmptyWorking with a nullable Vars :

more_horiz
Working with a ? Var :

It could be a null or something. This is kotlins degenerate way of preventing
Null pointer exceptions.

Var str: String? = null
Str = "hadouken";println(srt?.length)

Var I:Int? = 3
println(I!!) // tell kotlin you are sure the nullable var isn't null. 👮 :cop2: :cop3:

descriptionkotlin AS PL grimoire Emptykotlin when with ranges

more_horiz
shortend cases

Code:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}


arbitrary expressions

Code:

when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}


check a value for being in or !in a range or a collection:

Code:

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}


check that a value is or !is of a particular type

Code:

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}



when can also be used as a replacement for an if-else if chain

Code:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}
:swt:

descriptionkotlin AS PL grimoire Emptykotlin more basics

more_horiz
‪‪There can only be one fun main per package within the src directory‬‬

‪‪Conditional as expressions :‬‬
‪‪

Code:

‬‬
‪‪// conditional as expressions‬‬
‪‪    var mode = 2‬‬
‪‪    var result = when(mode){‬‬
‪‪        1 -> "one";2->"two";‬‬
‪‪        else -> "?"}‬‬
‪‪    println(result)‬‬
‪‪    // with if :‬‬
‪‪    var n1 = if(mode>2){println("mode>2")‬‬
‪‪        3}else{println("mode<=2");1}‬‬
‪‪    println(n1)‬‬
‪‪
‬‬

‪Random :‬

‪Random.nextInt(50)+1‬

Array and lists :

Code:


// arrays
    val FruitArray = arrayOf("apple","banana","grape")
    val vegi = arrayOf("tomato", "lichi")
    val fusionArr = FruitArray + vegi
    println(fusionArr[4])
    val mixedArr = arrayOf("hi",3,4f,true)
    val intArray = intArrayOf(1,2,3,5)
    println(intArray[0])
    val str = "hadouken"
    println(str[4])
    //lists
    val list = listOf("dollar", "euro", "shekel") //unmutable
    val arrayList = arrayListOf(1,2,3)
    arrayList.add(4)
    val nameList = arrayListOf<String>("ryu","ken","chun li")
    println(nameList[0])
    val nameList2 = arrayListOf("peter","braiyen")
    println(nameList)
    val fusionList = nameList+nameList2
    println(fusionList)
    val subList = fusionList.subList(2,fusionList.size - 1)
    println(subList)
:getsome:

descriptionkotlin AS PL grimoire Emptynaming loops

more_horiz
Naming loops :

Code:


//named loops used with break or continue:
    outer@ for (i in 1..10){
        for (j in 1..10){if(j==5){break@outer}else println("i is $i and j is $j")}
    }


Loop list with index

Code:


var list = listOf("java","kotlin","visual basic")
    for((index,value) in list.withIndex()){println("at index $index the value is $value") }


8))

descriptionkotlin AS PL grimoire EmptyKotlin functions classes and inharitance

more_horiz
Protip : cmd + n to autogenerate getters and setters

Functions :

Code:


package com.example.myapplication

import java.util.*

fun someString() = "working"

fun printWithSpaces(txt: String):String{
    for(char in txt){print(char + " ")}
    return ""
}

fun getCurrentDate() : Date {return Date()}

fun reverseList(list: List<Int>):List<Int>{
    val result = arrayListOf<Int>()
    for (i in list.size -1 downTo 0){
        result.add(list.get(i))
    }
    return result
}

fun main(args: Array<String>){
    println(someString())
    println(printWithSpaces("hadouken"))
    println(getCurrentDate())
    val list1 = listOf(9,7,5,4,3,2,1)
    println(reverseList(list1))
}


**********************************************************************

elab on classes :

Code:


class Person(name:String,age:Int){
    val name:String
    var age:Int
    init{
        //this runs when the obj is created
        this.name = name
        this.age = age
        println("object was created")
    }
}

fun main(args: Array<String>){
    var person = Person("ryu", 28)
    println("person ${person.name} is ${person.age} ")
}


In the above you can write the Person class much shorter ! :

Code:


class Person(val name:String,var age:Int){
    init{
        //this runs when the obj is created
        println("object was created")
    }
}


Or shooter :
class Person(val name:String,var age:Int){}

Inheritance :

Code:


package com.example.myapplication

open class Person(open val name:String,open var age:Int){
}
class Student(override val name:String,override var age:Int, var grade:Int):Person(name,age){
    override fun toString() = "name : ${this.name} age : ${this.age} grade : ${this.grade}"
}


fun main(args: Array<String>){
    var student = Student("ryu",30,12)
    println(student.toString())
}

:BP:

descriptionkotlin AS PL grimoire Emptyabstract classes

more_horiz
Abstract classes :


Code:


abstract class Person(open val name:String,open var age:Int){
    abstract fun greet() : String
    fun sayHello() = "hello"
    open fun overideMe() = "not working"
}
class Student(override val name:String,override var age:Int, var grade:Int):Person(name,age){
    override fun greet(): String {
        return "hi"
    }

    override fun overideMe(): String {
        return "works"
    }

    override fun toString() = "name : ${this.name} age : ${this.age} grade : ${this.grade}"
}


fun main(args: Array<String>){
    var student = Student("ryu",30,12)
    println(student.toString())
    println(student.sayHello())
    println(student.greet())
    println("the fun overideMe was overiden thanks to the open modifier " + student.overideMe())
}


Interfaces :

Code:


interface Driveable{
    val gasLevel:Int
    fun drive()}

class Car(val color:String): Driveable{
    override val gasLevel: Int = 100

    override fun drive() {
        println("driving...")
    }

}

fun main(args: Array<String>){
    val car:Driveable = Car("blue")
    car.drive()
    println("gas level : ${car.gasLevel}")
}


Using both interface and inheritance :

Code:


abstract class Course(val topic:String,val price: Double){
    open fun learn(){println("learning... $topic")}
}

interface Learnable{
    fun learn(){println("loafing about...")}
}

open class KotlinCourse():Course("kotlin",25.0),Learnable{
    override fun learn() {
        super<Course>.learn() // or choose Learnable to overide it instead of courses learn func
        println("kotlin is fast")
    }
}

fun main(args: Array<String>){
    val course = KotlinCourse()
    course.learn()
}


:join:

descriptionkotlin AS PL grimoire Emptydata classes

more_horiz
Data classes :

Data classes have some extra Justus beyond simple classes :

Code:


data class DataBook(val title:String,val year: Int,var price: Double){}


fun main(args: Array<String>){
    val dataBook2 = DataBook("battle programming",2019,25.0)
    val dataBook1 = DataBook("battle programming",2019,25.0)
    val dataBook3 = dataBook1.copy(price = 10.9) // built in clone with property modification
    println(dataBook1) // built in toString
    println(dataBook1.equals(dataBook2)) // built in equals ?
    println(dataBook3)
    val(title,year,price) = dataBook1 // data class decomposition no jutsu
    println(title)
    val set = hashSetOf(dataBook1,dataBook2,dataBook3) // data class to set without duplicates unlike a regular class
    println(set) // only prints 2 unique classes
}


Singleton :

Code:


object gun{
    fun shoot(){println("pow")}
}


fun main(args: Array<String>){
    gun.shoot()
}


Enums :

Code:


enum class enumWaifu{
    oshina, hatsune, hinata
}

class Dancer(var waifu:enumWaifu){

}

fun main(args: Array<String>){
    val dancer = Dancer(enumWaifu.hatsune)
    println(dancer.waifu)
}


Packages :

Naming : most be lower case for all chars + unique name.
Like : com.yotamarker.hadouken

You can import a package or nested package :
Import package.subpackage.subsubpackage
Or all package files : import java.util.*
Or functions form a package with object class (see singleton example above)

Import package.objectclassname.function name

Or use the designated name without the import :
Var n1 = java.util.Date()

Protip : ctrl + space : auto completion
Ctrl + alt + o : optimise imports to take out redundant imports :s37:

descriptionkotlin AS PL grimoire Emptykotlin hexa binari

more_horiz
Hexadecimal representation of color enum :

Code:


enum class Color(val rgb:Int){
    RED(0xFF0000), GREEN(0x00FF00), BLUE(0X0000FF),YELLOW(0xFFFF00);
    fun containsRed():Boolean = this.rgb and 0xFF0000 != 0
}



fun main(args: Array<String>){

    println(0X10)
    println(0x000000) // black
    println(0xffffff) //white
    println(0xFF0000) // red
    println(0x00FF00)//green
    println(0x0000ff)// blue
    println(0x000088) // dark blue
    println(0b11111111) /// binary
    println(0b11111111_00000001_10101010) // binary
    println(Color.RED.containsRed()) //prints true
    println(Color.BLUE.containsRed()) //prints true
    println(Color.YELLOW.containsRed()) //prints true
}
}


Getter and setter

Code:


class Animal{
    var age :Int = 0
    get() = field // tho redundant at this form
    set(value) {if(value > 0 ) field = value}
}



fun main(args: Array<String>){
    var animal = Animal()
    animal.age = 4;animal.age = -5
    println(animal.age) // access getter, output 4
}
hadouken :)

descriptionkotlin AS PL grimoire EmptyKotlin access modifiers

more_horiz
kotlin Access modifiers :

Code:


package com.example.myapplication


open class Animal{
    private var age :Int = 0
    fun setAge(value:Int){age = value}
    protected var name:String = "shuki"
    internal var eatsMeat: Boolean = false // available only within module (dir above src dir)
    public fun isOld():Boolean = age > 3
}


class Mammal:Animal(){
    fun introSelf(){println("I am $name")}
}
fun main(args: Array<String>){
    var animal = Mammal()
    animal.introSelf()
}


Using varargs :

Code:


fun <E>concateMessage(vararg input: E):String{
    // E means basic type of var, T means any var
    var sum = ""
    for(item in input){sum += item.toString() }
    return sum
}


fun main(args: Array<String>){
    println(concateMessage("hello", " ","world"))
}
you can use it without<E>

Kotlin dictionary :

Code:


fun main(args: Array<String>){
    var namesToAges = mapOf(Pair("ryu",30),Pair("ken",29))
    var namesToAges2 = mapOf("ryu" to 30,"ken" to 29)
    println(namesToAges == namesToAges2)
    println(namesToAges.values)
    println(namesToAges.entries)
    println(namesToAges.keys)
    var countryToInhabitants = mutableMapOf("germany" to 900_000)
    countryToInhabitants.put("pripyat", 5)
    countryToInhabitants.putIfAbsent("kiev", 5000000) // requires build gradle SDK 24 or above
    println(countryToInhabitants)
    namesToAges.forEach(){println("key ${it.key} val : ${it.value} years old")}
}


shouryuken smell you later

descriptionkotlin AS PL grimoire Emptykotlin harnessing views

more_horiz
Using a view, examplified with an image view.
Assuming you read the android studio grimoire you can infer two images were added
To the drawable folder.

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        imageView.setImageResource(R.drawable.im2)
    }
}


Protip : when the code doesn't recognise and underlines something like imageView
Press option + enter

Protip : pasting java code into a Kotlin file converts the code to kotlin

Protein : in a view onClick property you can add a function name.
Add said function with view param in your code :
Fun doStuff(view:View){} :chii:

descriptionkotlin AS PL grimoire EmptyKotlin shared preferences

more_horiz
Save or load using stored preferences

Code:


package com.example.myapplication

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        http://imageView.setImageResource(R.drawable.im2)
        val sharedPreference = this.getSharedPreferences(
            "com.example.myapplication", Context.MODE_PRIVATE)
        // mode private : only this app can access, name : this apps package name
        var age = 30
        sharedPreference.edit().putInt("userAge", age).apply() //save
        // load :
        val storedAge = sharedPreference.getInt("userAge",0) // 0 = default value in none found
        editText.setText(storedAge.toString())
    }
}


Deleting a var from shared preferences :

Code:


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        http://imageView.setImageResource(R.drawable.im2)
        val sharedPreference = this.getSharedPreferences(
            "com.example.myapplication", Context.MODE_PRIVATE)
        // mode private : only this app can access, name : this apps package name
        var age = 30
        sharedPreference.edit().putInt("userAge", age).apply() //save
        // load :
        val storedAge = sharedPreference.getInt("userAge",0) // 0 = default value in none found

        // deleting :
        sharedPreference.edit().remove("userAge").apply()
        val removedValue: Int = sharedPreference.getInt("userAge",0)
        editText.setText("saved val: ${storedAge.toString()} del var : $removedValue")
    }
}
:rain:

descriptionkotlin AS PL grimoire EmptyKotlin intents

more_horiz
Teleporting to another activity :

Add 2nd activity, on the 1st activity a button with the onClick :

changeActivity :

Code:


import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
    fun changeActivity(view: View){
        val intent = Intent(applicationContext,Main2Activity::class.java)
        startActivity(intent)
    }
}


Passing info between 2 activities :
Protein also notice the Toast message in the 2nd activity that displays the info sent from
The 1st activity.

Activity1 :

Code:


import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
    fun changeActivity(view: View){
        val intent = Intent(applicationContext,Main2Activity::class.java)
        intent.putExtra("DInfo", "works")
        startActivity(intent)
    }
}


Activity2 :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast

class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val intent = intent
        val received = intent.getStringExtra("DInfo")
        Toast.makeText(this@Main2Activity,"the msg is : $received",Toast.LENGTH_LONG).show()
    }
}


Kotlin count down timer :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        object: CountDownTimer(10000,1000){
            override fun onFinish() {

            }

            override fun onTick(millisUntilFinished: Long) {
                txtBox.text = "time left : ${millisUntilFinished / 1000} seconds"
            }
        }.start()

    }
}


kotlin Timer thread :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var count = 0
        val t = object:Thread() {
            public override fun run() {
                while ((!isInterrupted()))
                {
                    try
                    {
                        Thread.sleep(2000)
                        runOnUiThread(object:Runnable {
                            public override fun run() {
                                count++
                                txtBox.text = count.toString()
                                http://tv1.setText(String.valueOf(count))
                            }
                        })
                    }
                    catch (e:InterruptedException) {
                        e.printStackTrace()
                    }
                }
            }
        }
        t.start()

    }
}
👮

descriptionkotlin AS PL grimoire EmptyKotlin runable

more_horiz
Timer using runnable :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    var number = 0
    var handler = Handler()
    var runnable : Runnable = Runnable{}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
    fun start(view: View){
        number = 0
        runnable = object : Runnable{
            override fun run() {
              textView.text = "time: " + number
                number++
                handler.postDelayed(this,1000)
            }
        }
        handler.post(runnable)
    }
    fun reset(view:View){
        handler.removeCallbacks(runnable)
        number = 0
        textView.text = "timer: " + number
    }
}



Alert dialog :

Code:


    fun start(view: View){
        val alert = AlertDialog.Builder(this)
        alert.setTitle("take the red pill ?")
        alert.setMessage("red or blue pill ?")
        alert.setPositiveButton("red pill"){dialogInterface:DialogInterface,i  : Int -> Toast.makeText(this@MainActivity,"welcome to the matrix",Toast.LENGTH_LONG).show()}
        alert.setNegativeButton("blue pill"){dialogInterface:DialogInterface,i  : Int -> Toast.makeText(applicationContext,"bye neo",Toast.LENGTH_SHORT).show()}
        alert.show()
    }

:shouryuken:

descriptionkotlin AS PL grimoire EmptyKotlin gridLayout

more_horiz
Grid view game :

Add gridLayout, add imageView under grid layout in its component tree.

Basically : click ban, you got x seconds to click the position changing image as
Many time as possible.

Xml :

Code:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <android.support.v7.widget.GridLayout
            android:layout_width="327dp"
            android:layout_height="0dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginBottom="24dp"
            app:layout_constraintHorizontal_bias="0.488"
            android:id="@+id/gridLayout" app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="151dp"
            app:layout_constraintBottom_toTopOf="@+id/button2">

        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="0"
                app:layout_column="0" android:id="@+id/imageView" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="0"
                app:layout_column="1" android:id="@+id/imageView1" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="0"
                app:layout_column="2" android:id="@+id/imageView2" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="0"
                app:layout_column="3" android:id="@+id/imageView3" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="1"
                app:layout_column="0" android:id="@+id/imageView4" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="1"
                app:layout_column="1" android:id="@+id/imageView5" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="1"
                app:layout_column="2" android:id="@+id/imageView6" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="1"
                app:layout_column="3" android:id="@+id/imageView7" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="2"
                app:layout_column="0" android:id="@+id/imageView8" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="2"
                app:layout_column="1" android:id="@+id/imageView9" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="2"
                app:layout_column="2" android:id="@+id/imageView10" android:onClick="increaseScore"/>
        <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp" app:srcCompat="@drawable/pica" app:layout_row="2"
                app:layout_column="3" android:id="@+id/imageView11" android:onClick="increaseScore"/>
    </android.support.v7.widget.GridLayout>
    <TextView
            android:text="TextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView2" android:layout_marginTop="57dp"
            android:layout_marginBottom="75dp" app:layout_constraintEnd_toEndOf="@+id/gridLayout"
            app:layout_constraintBottom_toTopOf="@+id/gridLayout" app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="154dp" android:layout_marginEnd="156dp"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            app:layout_constraintTop_toBottomOf="@+id/gridLayout" android:layout_marginBottom="40dp"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" android:onClick="gameOn"/>
</android.support.constraint.ConstraintLayout>


MainActivity :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    var score:Int = 0
    var x = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val animeArr= arrayOf(imageView,imageView1,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9,imageView10,imageView11)

        for (item in 0..11){animeArr[item].visibility = View.INVISIBLE}
        animeArr[x].visibility = View.VISIBLE
    button2.text = score.toString()

    }
    fun getArr():Array<View> = arrayOf(imageView,imageView1,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,imageView8,imageView9,imageView10,imageView11)

    fun gameOn(view: View){
        score = 0
        object: CountDownTimer(10000,1000){
            override fun onFinish() {
                textView2.text = "last score: " + button2.text
            }

            override fun onTick(millisUntilFinished: Long) {
                val animeArr = getArr()
                textView2.text = "time left : ${millisUntilFinished / 1000} seconds"
                val xTemp = x
                animeArr[x].visibility = View.INVISIBLE
                x = Random.nextInt(11) +1
                animeArr[x].visibility = View.VISIBLE
            }
        }.start()
    }
    fun increaseScore(view:View){
        score++
        button2.text = score.toString()
    }
}
:coolpepe:

descriptionkotlin AS PL grimoire EmptyKotlin global variables

more_horiz
Static Global variables

Exemplified with listView.
Global vars can be used throughout the app to transfer data anywhere
From class to class.

This app has a list of landmark sites, upon clicking one of which
It opens a 2nd activity with a respective picture and name of the place

Add 4 images to drawable : im1 im2 im4 im5
Add an empty activity : SiteActivity

activity_main :

Code:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <ListView
            android:layout_width="395dp"
            android:layout_height="715dp" tools:layout_editor_absoluteY="8dp" tools:layout_editor_absoluteX="8dp"
            android:id="@+id/listView"/>
</android.support.constraint.ConstraintLayout>


activity_site.xml : (the 2nd activity)

Code:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".SiteActivity">

    <ImageView
            android:layout_width="400dp"
            android:layout_height="400dp" app:srcCompat="@drawable/ic_launcher_background"
            android:id="@+id/imageView"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginTop="131dp" android:layout_marginStart="148dp"
            android:layout_marginBottom="135dp" app:layout_constraintBottom_toTopOf="@+id/textView"
            app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="155dp"/>
    <TextView
            android:text="TextView"
            android:layout_width="148dp"
            android:layout_height="50dp"
            android:id="@+id/textView"
            app:layout_constraintTop_toBottomOf="@+id/imageView" android:layout_marginBottom="187dp"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.498"/>
</android.support.constraint.ConstraintLayout>


Globals.kt (Kotlin file you add)

Code:


import android.graphics.Bitmap

// a class used for global variables to be used throughout the app classes
class Globales{
    companion object Chosen{
        var chosenImage : Bitmap? = null
        fun returnImage():Bitmap = chosenImage!!
        // !! means I am sure at this point the image isnt null and contains a valid image
    }
}


MainActivity :

Code:


package com.example.listview

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var siteNames = ArrayList<String>()
        siteNames.add("shinjuku")
        siteNames.add("akihabara")
        siteNames.add("mtFuji")
        siteNames.add("hokaido")
        val arrayAdapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,siteNames)
        listView.adapter = arrayAdapter


        val pic1 = BitmapFactory.decodeResource(applicationContext.resources,R.drawable.im1)
        val pic2 = BitmapFactory.decodeResource(applicationContext.resources,R.drawable.im2)
        val pic3 = BitmapFactory.decodeResource(applicationContext.resources,R.drawable.im5)
        val pic4 = BitmapFactory.decodeResource(applicationContext.resources,R.drawable.im4)
        val siteImages = ArrayList<Bitmap>()
        siteImages.add(pic1)
        siteImages.add(pic2)
        siteImages.add(pic3)
        siteImages.add(pic4)

        listView.onItemClickListener = AdapterView.OnItemClickListener{parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
            val intent = Intent(applicationContext,SiteActivity::class.java)
            intent.putExtra("DInfo",siteNames[position])

            val picture = siteImages[position]
            val chosen = Globales.Chosen;chosen.chosenImage = picture

            startActivity(intent)

        }

    }
}


SiteActivity :

Code:


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_site.*

class SiteActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_site)

        val intent = intent
        val name = intent.getStringExtra("DInfo")
        textView.text = name
        val chosen = Globales.Chosen
        val selectedImage = chosen.returnImage()
        imageView.setImageBitmap(selectedImage)

    }
}


hadofsetofkein thanks

descriptionkotlin AS PL grimoire Emptykotlin sql

more_horiz
SQL Justus

Insert :

Code:


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            val myDataBase = this.openOrCreateDatabase("Musicians", Context.MODE_PRIVATE, null)
            myDataBase.execSQL("CREATE TABLE IF NOT EXISTS musicians (name VARCHAR, age INT(2))")
            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('james',50)")
        }catch (e: Exception){e.printStackTrace()}

    }
}


Read data :

Code:


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            val myDataBase = this.openOrCreateDatabase("Musicians", Context.MODE_PRIVATE, null)
//            myDataBase.execSQL("CREATE TABLE IF NOT EXISTS musicians (name VARCHAR, age INT(2))")
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('james',50)")
            val cursor = myDataBase.rawQuery("SELECT * FROM musicians", null)
            val nameIndex = cursor.getColumnIndex("name")
            val ageIndex = cursor.getColumnIndex("age")
            cursor.moveToFirst()
            while (cursor != null){
                // txtBox if the textView id
                txtBox.text = "name : ${cursor.getString(nameIndex)} age: ${cursor.getInt(ageIndex)}"
                cursor.moveToNext()
            }
            if(cursor !=null){cursor!!.close()} // extra safety not a must
        }catch (e: Exception){e.printStackTrace()}

    }
}


UPDATE sql value :

Code:


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            val myDataBase = this.openOrCreateDatabase("Musicians", Context.MODE_PRIVATE, null)
            myDataBase.execSQL("CREATE TABLE IF NOT EXISTS musicians (name VARCHAR, age INT(2))")
// run this lines than comment them out
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('kirk',60)")
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('Lars',56)")
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('rob',70)")
            myDataBase.execSQL("UPDATE musicians SET age = 55 WHERE name = 'Lars'") // update jutsu

            val cursor = myDataBase.rawQuery("SELECT * FROM musicians", null)
            val nameIndex = cursor.getColumnIndex("name")
            val ageIndex = cursor.getColumnIndex("age")
            cursor.moveToFirst()
            while (cursor != null){
                // txtBox if the textView id
                println("name : ${cursor.getString(nameIndex)} age: ${cursor.getInt(ageIndex)}")
                // search System.out in the logcat to see
                cursor.moveToNext()
            }
            //if(cursor !=null){cursor!!.close()} // extra safety not a must
        }catch (e: Exception){e.printStackTrace()}

    }
}


DELETE :

Code:


import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            val myDataBase = this.openOrCreateDatabase("Musicians", Context.MODE_PRIVATE, null)
            myDataBase.execSQL("CREATE TABLE IF NOT EXISTS musicians (name VARCHAR, age INT(2))")
// run this lines than comment them out
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('kirk',60)")
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('Lars',56)")
//            myDataBase.execSQL("INSERT INTO musicians (name,age) VALUES ('rob',70)")
//            myDataBase.execSQL("UPDATE musicians SET age = 55 WHERE name = 'Lars'") // update jutsu
            myDataBase.execSQL("DELETE FROM musicians WHERE name = 'rob'") // sakujou( delete ) jutsu

            val cursor = myDataBase.rawQuery("SELECT * FROM musicians", null)
            val nameIndex = cursor.getColumnIndex("name")
            val ageIndex = cursor.getColumnIndex("age")
            cursor.moveToFirst()
            while (cursor != null){
                // txtBox if the textView id
                println("name : ${cursor.getString(nameIndex)} age: ${cursor.getInt(ageIndex)}")
                // search System.out in the logcat to see
                cursor.moveToNext()
            }
            //if(cursor !=null){cursor!!.close()} // extra safety not a must
        }catch (e: Exception){e.printStackTrace()}

    }
}


Filer results (sql query) : just add a WHERE to the cursor code line :
val cursor = myDataBase.rawQuery("SELECT * FROM musicians WHERE name = 'Lars'", null)
Or something like :
val cursor = myDataBase.rawQuery("SELECT * FROM musicians WHERE age > 55", null)
Or :
"SELECT * FROM musicians WHERE name LIKE 'k%'" // starts with k
"SELECT * FROM musicians WHERE name LIKE '%a%'" // has an 'a' in the name
%s // ends with 's' :hkn:

descriptionkotlin AS PL grimoire EmptyRe: kotlin AS PL grimoire

more_horiz
Working with images from device memory

Main activity : listView id: listView

Main2Activity.

Add a menu to activity 1 :

Right click res dir, new, directory and name it menu.
Right click said menu dir, new, menu resource file, name it (add_art in this exanple)
The menu xml with 1 menu <item >I added :

Code:


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add_art" android:title="Add Art"></item>
</menu>


Link the menu to the MainActivity from its code :

Code:


import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val menuInflater = menuInflater
        menuInflater.inflate(R.menu.add_art,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.add_art){
            val intent = Intent(applicationContext,Main2Activity::class.java)
            startActivity(intent)
        }
        return super.onOptionsItemSelected(item)
    }
}


activity_main2.xml :

Code:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Main2Activity">

    <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Name"
            android:ems="10"
            android:id="@+id/editText"
            android:layout_marginTop="83dp"
            android:layout_marginBottom="86dp" app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/imageView" app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" android:hint="name"/>
    <ImageView
            android:layout_width="215dp"
            android:layout_height="0dp" app:srcCompat="@mipmap/ic_launcher"
            android:id="@+id/imageView"
            app:layout_constraintTop_toBottomOf="@+id/editText" android:layout_marginBottom="126dp"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintStart_toStartOf="parent" android:onClick="select1"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            app:layout_constraintTop_toBottomOf="@+id/imageView" android:layout_marginBottom="43dp"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" android:onClick="save"/>
</android.support.constraint.ConstraintLayout>

Notice the onClick functions above.

Add permission read external storage to access pictures on phone :

Code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.picgallery">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <application
            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=".Main2Activity">
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>


Main2Activity code (at this stage it takes an external image into its image view) :

Code:


import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import kotlinx.android.synthetic.main.activity_main2.*
import java.lang.Exception
import java.util.jar.Manifest

class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
    }
    fun select1(view: View){
        if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),2)
        }else{val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent,1)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode==2){
            if (grantResults.size > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                startActivityForResult(intent,1)
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(requestCode ==1 && resultCode == Activity.RESULT_OK && data !=null){
            val image = data.data
            try {
                val selectedImage = MediaStore.Images.Media.getBitmap(this.contentResolver,image)
                imageView.setImageBitmap(selectedImage)
            }catch (e:Exception){e.printStackTrace()}


        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    fun save(view: View){}
}



Modify Main2Activity to save the image (as a blob in the sql DB )and a name for it :

Code:


import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import kotlinx.android.synthetic.main.activity_main2.*
import java.io.ByteArrayOutputStream
import java.lang.Exception
import java.util.jar.Manifest

class Main2Activity : AppCompatActivity() {

    var selectedImage: Bitmap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
    }
    fun select1(view: View){
        if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),2)
        }else{val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent,1)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode==2){
            if (grantResults.size > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                startActivityForResult(intent,1)
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(requestCode ==1 && resultCode == Activity.RESULT_OK && data !=null){
            val image = data.data
            try {
                selectedImage = MediaStore.Images.Media.getBitmap(this.contentResolver,image)
                imageView.setImageBitmap(selectedImage)
            }catch (e:Exception){e.printStackTrace()}


        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    fun save(view: View){
        // saving title + image file
        val artName = editText.text.toString()
        val outputStream = ByteArrayOutputStream()
        selectedImage?.compress(Bitmap.CompressFormat.PNG,50,outputStream)
        val byteArray = outputStream.toByteArray() // the image as a byteArray

        try {
            val dataBase = this.openOrCreateDatabase("Arts", Context.MODE_PRIVATE,null)
            dataBase.execSQL("CREATE TABLE IF NOT EXISTS arts (name VARCHAR, image BLOB)")
            val sqlString = "INSERT INTO arts (name, image) VALUES (?, ?)"
            val statement = dataBase.compileStatement(sqlString)
            statement.bindString(1,artName);statement.bindBlob(2,byteArray)
            statement.execute()

        }catch (e:Exception){e.printStackTrace()}

        // to the main activity
        val intent = Intent(applicationContext,MainActivity::class.java)
        startActivity(intent)

    }
}
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply