Snippets Collections
//Step1: Implement these 3 Dependencies in build.gradle.kts(Module:app)

implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.5")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5")
implementation("androidx.compose.material3:material3:1.3.0")

//Step2: Create CounterViewModel.kt

package com.example.incrementviewmodel

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class CounterViewModel: ViewModel(){
    //Mutable State Flow to hold the counter value
    //StateFlow is a read only data stream
    private val _counter = MutableStateFlow(0)
    val counter : StateFlow<Int> = _counter

    fun incrementcounter(){
        _counter.value +=1
    }
}

//MainActivity.kt

package com.example.incrementviewmodel

import android.os.Bundle
import androidx.compose.foundation.layout.*//Import compose layout
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel

import androidx.lifecycle.viewmodel.compose.viewModel//Import this

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            display()
        }
    }
}

@Composable
fun display(counterViewModel: CounterViewModel = viewModel()){
    val counterState = counterViewModel.counter.collectAsState()
    Column( modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(text = "Counter: ${counterState.value}")
        Spacer(modifier = Modifier.height(30.dp))
        Button(onClick = {counterViewModel.incrementcounter()}) {
            Text(text = "Increment")
        }
    }
}
package com.example.incrementcounter

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.incrementcounter.ui.theme.IncrementCounterTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            display()
        }
    }
}

@Composable
fun display(){
    var counter by remember { mutableIntStateOf(0) }
    Column( modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
            ) {
        Text(text = "Counter: $counter")
        Spacer(modifier = Modifier.height(30.dp))
        Button(onClick = {counter++}) {
            Text(text = "Increment")
        }
        Button(onClick = {if(counter > 0) counter--}) {
            Text(text = "Decrement")
        }
    }
}

package com.example.diceroller

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.diceroller.ui.theme.DiceRollerTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DiceRollerTheme {
                DiceRollerApp()
            }
        }
    }
}


@Composable
fun DiceRollerApp() {
    DiceWithButtonAndImage()
}

@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
    var result by remember { mutableStateOf(1) }

    val imageResource = when (result) {
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }

    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(imageResource),
            contentDescription = result.toString()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = { result = (1..6).random() }) {
            Text(text = "roll dice")
        }
    }
}
package com.example.sep11

import android.os.Bundle
import android.widget.Space
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.sep11.ui.theme.Sep11Theme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            //display()
            //RowExample()
            //HelloWorld()
            //ImageExample()
            simpleButton()
        }
    }
}
@Composable
fun display(){
    Column( modifier = Modifier.padding(top = 150.dp, start = 60.dp)) {
        Text(text = "Hello JetPackCompose",
            fontSize = 35.sp,
            color = Color.Red,
        )
        Text(text = "Python",
            color = Color.Blue,
            fontSize = 45.sp,
            )
    }

}

@Composable
fun RowExample(){
    Row(modifier = Modifier.padding(all = 40.dp)){
        Text(text = "Java", color = Color.Green, fontSize = 45.sp)
        Text(text = "Kotlin", color = Color.Magenta, fontSize = 45.sp)
    }
}

@Composable
fun HelloWorld(){
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "Hello World", color = Color.Red,
            fontWeight = FontWeight.Bold,
        )
    }
}

@Composable
fun ImageExample(){
    Column{
        Image(painter = painterResource(id = R.drawable.java),
            contentDescription = "Java Logo",
            modifier = Modifier.padding(top = 45.dp)
            )
        Spacer(modifier = Modifier.height(45.dp))
        Text(text = "This is a Java Logo")
    }
}

@Composable
fun simpleButton(){

    val context = LocalContext.current
    Button(onClick = {Toast.makeText(context,"Button Clicked", Toast.LENGTH_LONG).show() }) {
        Text(text = "Click Here")
    }
}
1. Create a 'Book' class with the following specifications:

 Properties:  title,Author,Published_year

Methods:
  displayInfo : to print Book details.

//Program
package com.example.objectoriented

class Book(val title:String, val author:String, val published_year:Int){
    fun display(){
        println("Title: $title\nAuthor: $author\nPublished Year: $published_year")
        println()
    }
}

fun main(){
    val b1 = Book("Computer Networking", "John", 2020)
    val b2 = Book("Algorithms Design And Analysis", "James", 2019)

    println("Book Details")
    println()
    b1.display()
    b2.display()
}



2. Simple class with a Primary Constructor

//Program

package com.example.objectoriented

class Emp(val ename:String, val id:Int, val age:Int){

    init {
        if(age<0){
            println("Age cannot be negative")
        }
        else{
            println("Object is created")
        }
    }
    fun showDetails(){
        println("Name: $ename \nID: $id")
    }
}

fun main(){
    val e1 = Emp("Rahul", 101, 20)
    e1.showDetails()
    println()
    val e2 = Emp("Aarav", 102, -3)
    e2.showDetails()
}


3. Implelemt a Employee Class with default constructor values

    Properties: name,position,department,experience(set it to 1 default)

  Methods: showdetails()

  a. Create a Instance with only Name specified
  b. Create a Instance with Name and Position Specified
  c. Create a Instance with All Properties Specified
  d. Instance with Name and Experience Specified
  
//Program

package com.example.objectoriented

class Employee(val name:String, val position:String = "Clerk", val department:String = "CS", val experience:Int = 1){
    fun display(){
        println("Name: $name")
        println("Poistion: $position")
        println("Department: $department")
        println("Experience: $experience")
        println()
    }
}

fun main(){
    val e1 = Employee("Rahul")
    val e2 = Employee("Aarav", "Data Analyst ", "CS")
    val e3 = Employee("James", "Manager", "IT", 20)
    val e4 = Employee("Adam", experience = 15)

    e1.display()
    e2.display()
    e3.display()
    e4.display()


}

1.HTML - blockquote tag and q tag

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Traditional Fair Poster</title>
</head>
<body>
    <h2>Wedding Event</h2>
    <p>A wedding is a ceremony where two people or a couple are united in marriage. Wedding traditions and customs vary greatly between cultures, ethnic groups, religions, countries, and social classes. Most wedding ceremonies involve an exchange of marriage vows by the couple, presentation of a gift, and a public proclamation of marriage by an authority figure or celebrant. Special wedding garments are often worn, and the ceremony is sometimes followed by a wedding reception. Music, poetry, prayers or readings from religious texts or literature are also commonly incorporated into the ceremony.</p>

    <blockquote cite="https://www.brainyquote.com/quotes/sheri_l_dew_679111">
        <q>Neither man nor woman is perfect or complete without the other. Thus, no marriage or family, no ward or stake is likely to reach its full potential until husbands and wives, mothers and fathers, men and women work together in unity of purpose, respecting and relying upon each other's strengths.</q>
    </blockquote>
</body>
</html>



2. HTML Basics - Formatted tags-Olympics


<html>
    <head>
        <title>My First Website</title>
    </head>
    <body>
      <h1>Olympic Games</h1>

The modern <b>Olympic Games</b> or <b>Olympics</b> are leading international sporting events featuring summer and winter sports competitions in which thousands of <i>athletes</i> from around the world participate in a variety of competitions. The Olympic Games are considered the world's foremost sports competition with more than <i>200 nations</i> participating. The Olympic Games are normally held every <u>four years</u>, alternating between the <u>Summer</u> and <u>Winter Olympics</u> every two years in the four-year period.
Their creation was inspired by the <ins>ancient Olympic Games</ins>, held in Olympia, Greece from the 8th century BC to the 4th century AD. <mark>Baron Pierre de Coubertin</mark> founded the <ins>International Olympic Committee</ins> (IOC) in 1894, leading to the first modern Games in Athens in 1896. The IOC is the governing body of the Olympic Movement, with the Olympic Charter defining its <small>structure and authority</small>.
The evolution of the Olympic Movement during the 20<sup>th</sup> and 21<sup>st</sup> centuries has resulted in several changes to the Olympic Games. Some of these adjustments include the creation of the Winter Olympic Games for snow and ice sports, the Paralympic Games for athletes with disabilities, the Youth Olympic Games for athletes aged <sub>14 to 18</sub>, the five Continental games <big>(Pan American, African, Asian, European, and Pacific)</big>, and the World Games for sports that are not contested in the Olympic Games. The IOC also endorses the <strike>Deaflympics and the Special Olympics</strike>. The IOC has needed to adapt to a variety of <del>economic, political, and technological</del> advancements.
<tt>The Olympic Movement consists of international sports federations (IFs), National Olympic Committees (NOCs), and organising committees for each specific Olympic Games.</tt>

    </body>
</html>
MainActivity.kt

package com.example.intent

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

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

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}

activity_main.xml

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

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/teal_200"
        />


</LinearLayout>

DetailsActivity.kt

package com.example.intent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

activity_deatils.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/purple_700"
        />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools = "http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity"
    >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/changeImageButton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintStart_toEndOf="parent"
        android:src="@drawable/java"
        tools:ignore="UnknownId"
        />

    <Button
        android:id="@+id/changeImageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginBottom="25dp"
        />

    <TextView
        android:id="@+id/imageDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am Java"
        app:layout_constraintTop_toBottomOf="@id/imageView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="8dp"
        android:textSize="18sp" />

</androidx.constraintlayout.widget.ConstraintLayout>






package com.example.imageshuffler

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.imageshuffler.ui.theme.ImageShufflerTheme

class MainActivity : ComponentActivity() {
    private lateinit var imv : ImageView
    private lateinit var chngbt: Button
    private lateinit var imgdes: TextView
    val imlist = listOf(
        R.drawable.java,
        R.drawable.kotlin,
        R.drawable.python
    )
    var currentimgindx = 0
    private val imgdescription = listOf(
        "Hi I am Java",
        "Hi I am Kotlin",
        "Hi I am Python"
    )
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imv = findViewById(R.id.imageView)
        chngbt = findViewById(R.id.changeImageButton)
        imgdes = findViewById(R.id.imageDescription)

        chngbt.setOnClickListener {

            changeImage()
        }
        imgdes.text=imgdescription[currentimgindx]
    }
    fun changeImage(){
        currentimgindx = (currentimgindx + 1 ) % imlist.size
        imv.setImageResource(imlist[currentimgindx])
        imgdes.text = imgdescription[currentimgindx]
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_200"
    >

    <TextView
        android:id="@+id/title"
        style="bold"
        android:layout_width="match_parent"
        android:layout_height="73dp"
        android:text="Addition of Two Numbers"
        android:textColor="#ED0E5A"
        android:textSize="30dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/num1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter the First Number" />

    <EditText
        android:id="@+id/num2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter the Second Number" />



    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/purple_200"
        >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0B89ED"
        android:layout_marginLeft="80dp"
        android:layout_marginRight="40dp"
        android:text="SUM" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0B89ED"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:text="Clear"/>
    </LinearLayout>

    <TextView
        android:id="@+id/result"
        style="bold"
        android:layout_width="wrap_content"
        android:layout_height="79dp"
        android:text="Result will be displayed here"
        android:textColor="#F3DE2F"
        android:textSize="29dp"
        android:textStyle="bold" />

</LinearLayout>





package com.example.sum

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.sum.ui.theme.SumTheme
import java.util.jar.Pack200

class MainActivity : ComponentActivity() {
    private lateinit var t1 : TextView
    private lateinit var et1: EditText
    private lateinit var et2: EditText
    private lateinit var bt1 : Button
    private lateinit var bt2: Button
    private lateinit var t2: TextView

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


        t1 = findViewById(R.id.title)
        et1 = findViewById(R.id.num1)
        et2 = findViewById(R.id.num2)
        bt1 = findViewById(R.id.btn)
        bt2 = findViewById(R.id.clear)
        t2 = findViewById(R.id.result)

        bt1.setOnClickListener{
            var n1 = et1.text.toString()
            var n2 = et2.text.toString()

            if (n1.isNotEmpty() && n2.isNotEmpty()){
                val total = n1.toInt() + n2.toInt()

                t2.text = "Sum is $total"
            }else{
                t2.text = "Please enter both the values"
            }
        }

        bt2.setOnClickListener {
            et1.text.clear()
            et2.text.clear()
            t2.text = "Result will be displayed here"
            et1.hint = "Enter the First Number"
            et2.hint = "Enter the Second Number"
        }


    }
}
import android.webkit.CookieManager
import android.webkit.WebView

class MainActivity : AppCompatActivity() {
  lateinit var webView: WebView

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    webView = findViewById(R.id.webview)

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
    // Let the web view use JavaScript.
    webView.settings.javaScriptEnabled = true
    // Let the web view access local storage.
    webView.settings.domStorageEnabled = true
    // Let HTML videos play automatically.
    webView.settings.mediaPlaybackRequiresUserGesture = false

    // Load the URL for optimized web view performance.
    webView.loadUrl("https://webview-api-for-ads-test.glitch.me")
  }
}
import android.webkit.CookieManager
import android.webkit.WebView

class MainActivity : AppCompatActivity() {
  lateinit var webView: WebView

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    webView = findViewById(R.id.webview)

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
    // Let the web view use JavaScript.
    webView.settings.javaScriptEnabled = true
    // Let the web view access local storage.
    webView.settings.domStorageEnabled = true
    // Let HTML videos play automatically.
    webView.settings.mediaPlaybackRequiresUserGesture = false
  }
}
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
import android.webkit.CookieManager
import android.webkit.WebView

class MainActivity : AppCompatActivity() {
  lateinit var webView: WebView

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    webView = findViewById(R.id.webview)

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
    // Let the web view use JavaScript.
    webView.settings.javaScriptEnabled = true
    // Let the web view access local storage.
    webView.settings.domStorageEnabled = true
    // Let HTML videos play automatically.
    webView.settings.mediaPlaybackRequiresUserGesture = false

    // Load the URL for optimized web view performance.
    webView.loadUrl("https://webview-api-for-ads-test.glitch.me")
  }
}
import android.webkit.CookieManager
import android.webkit.WebView

class MainActivity : AppCompatActivity() {
  lateinit var webView: WebView

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    webView = findViewById(R.id.webview)

    // Let the web view accept third-party cookies.
    CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
    // Let the web view use JavaScript.
    webView.settings.javaScriptEnabled = true
    // Let the web view access local storage.
    webView.settings.domStorageEnabled = true
    // Let HTML videos play automatically.
    webView.settings.mediaPlaybackRequiresUserGesture = false
  }
}
package com.example.calcapptoturial

import android.content.Intent
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.ImageButton
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity

class SettingsActivity : AppCompatActivity() {

    private lateinit var editTextFormativeWeight: EditText
    private lateinit var editTextSummativeWeight: EditText

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

        // Initialize EditText fields
        editTextFormativeWeight = findViewById(R.id.editTextFormativeWeight)
        editTextSummativeWeight = findViewById(R.id.editTextSummativeWeight)

        // Set current weights as hints for EditText fields
        val currentFormativeWeight = intent.getDoubleExtra(EXTRA_FORMATIVE_WEIGHT, 40.0)
        val currentSummativeWeight = intent.getDoubleExtra(EXTRA_SUMMATIVE_WEIGHT, 60.0)
        editTextFormativeWeight.hint = "Current Formative Weight: $currentFormativeWeight"
        editTextSummativeWeight.hint = "Current Summative Weight: $currentSummativeWeight"

        // Set click listener for the save button
        findViewById<Button>(R.id.btnSave).setOnClickListener {
            saveWeights()
            finish() // Close the settings activity
        }

        val themeOptions = arrayOf(
            "Keller HS Light",
            "Timber Creek HS Light",
            "Fossil Ridge HS Light",
            "Keller Central HS Light",
            "Keller HS Dark",
            "Timber Creek HS Dark",
            "Fossil Ridge HS Dark",
            "Keller Central HS Dark",
            "Default (Light + Orange)"
        )

        val themeSpinner = findViewById<Spinner>(R.id.themeSpinner)
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, themeOptions)
        themeSpinner.adapter = adapter

        // Find the close button
        val closeButton = findViewById<ImageButton>(R.id.btnClose)

        // Set click listener for the close button
        closeButton.setOnClickListener {
            // Close the settings activity
            finish()
        }
    }

    private fun saveWeights() {
        // Get the input values from EditText fields
        val formativeWeightInput = editTextFormativeWeight.text.toString()
        val summativeWeightInput = editTextSummativeWeight.text.toString()

        // Convert input values to doubles
        val formativeWeight = if (formativeWeightInput.isNotEmpty()) formativeWeightInput.toDouble() else 40.0
        val summativeWeight = if (summativeWeightInput.isNotEmpty()) summativeWeightInput.toDouble() else 60.0

        // Create an intent to pass the weights back to MainActivity
        val intent = Intent().apply {
            putExtra(EXTRA_FORMATIVE_WEIGHT, formativeWeight)
            putExtra(EXTRA_SUMMATIVE_WEIGHT, summativeWeight)
        }
        setResult(RESULT_OK, intent) // Set result OK to indicate successful operation
    }

    companion object {
        const val EXTRA_FORMATIVE_WEIGHT = "extra_formative_weight"
        const val EXTRA_SUMMATIVE_WEIGHT = "extra_summative_weight"
    }
}
package com.example.calcapptoturial

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var inputTextView: TextView
    private lateinit var calculatedGradeTextView: TextView
    private lateinit var historyTextView: TextView
    private lateinit var currentModeTextView: TextView
    private var totalFormativeGrades: Double = 0.0
    private var totalSummativeGrades: Double = 0.0
    private var formativeWeight: Double = 40.0 // Default formative weight
    private var summativeWeight: Double = 60.0 // Default summative weight
    private var formativeGradeCount: Int = 0
    private var summativeGradeCount: Int = 0

    companion object {
        const val REQUEST_CODE_SETTINGS = 1001 // Define the request code
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        inputTextView = findViewById(R.id.inputext)
        calculatedGradeTextView = findViewById(R.id.calculatedgradetext)
        historyTextView = findViewById(R.id.historytext)
        currentModeTextView = findViewById(R.id.currentmodetext)

        // Initialize settingsButton
        val settingsButton = findViewById<ImageButton>(R.id.settingsButton)

        // Set click listener for settingsButton
        settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            intent.putExtra(SettingsActivity.EXTRA_FORMATIVE_WEIGHT, formativeWeight)
            intent.putExtra(SettingsActivity.EXTRA_SUMMATIVE_WEIGHT, summativeWeight)
            startActivityForResult(intent, REQUEST_CODE_SETTINGS)
        }

        // Set max length for input text view
        inputTextView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (s?.length ?: 0 > 5) {
                    s?.delete(5, s.length)
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SETTINGS && resultCode == RESULT_OK) {
            // Update weights from settings
            formativeWeight = data?.getDoubleExtra(SettingsActivity.EXTRA_FORMATIVE_WEIGHT, formativeWeight) ?: formativeWeight
            summativeWeight = data?.getDoubleExtra(SettingsActivity.EXTRA_SUMMATIVE_WEIGHT, summativeWeight) ?: summativeWeight
            // Update mode text view with updated weights
            updateModeTextView()
            // Recalculate grade with updated weights
            updateCalculatedGrade()
        }
    }

    override fun onResume() {
        super.onResume()
        // Update mode text view with weights from settings
        updateModeTextView()
        // Recalculate grade when returning from settings
        updateCalculatedGrade()
    }

    fun onDigitClick(view: View) {
        if (inputTextView.text.length < 5) { // Allow up to 5 digits
            if (view is TextView) {
                val digit: String = view.text.toString()
                inputTextView.append(digit)
            }
        }
    }

    fun onequalClick(view: View) {
        val grade = inputTextView.text.toString().toDoubleOrNull()
        if (grade != null) {
            updateHistory(grade)
            updateCalculatedGrade()
            inputTextView.text = ""
        }
    }

    fun onbackClick(view: View) {
        val expression = inputTextView.text.toString()
        if (expression.isNotEmpty()) {
            inputTextView.text = expression.substring(0, expression.length - 1)
        }
    }

    fun onMClick(view: View) {
        // Toggle between Formative and Summative mode
        if (currentModeTextView.text.contains("Formative")) {
            currentModeTextView.text = "Summative Mode: (${String.format("%.1f", summativeWeight)}%)"
        } else {
            currentModeTextView.text = "Formative Mode: (${String.format("%.1f", formativeWeight)}%)"
        }
        // Recalculate grade when mode changes
        updateCalculatedGrade()
    }

    fun onclearAllClick(view: View) {
        inputTextView.text = ""
        calculatedGradeTextView.text = "Grade: 0.0%"
        historyTextView.text = ""
        historyTextView.visibility = View.GONE // Set visibility to gone
        totalFormativeGrades = 0.0
        totalSummativeGrades = 0.0
        formativeGradeCount = 0
        summativeGradeCount = 0
    }

    private fun updateCalculatedGrade() {
        val newAverage = if (formativeGradeCount == 0) {
            totalSummativeGrades / summativeGradeCount
        } else if (summativeGradeCount == 0) {
            totalFormativeGrades / formativeGradeCount
        } else {
            (totalSummativeGrades / summativeGradeCount) * (summativeWeight / 100.0) +
                    (totalFormativeGrades / formativeGradeCount) * (formativeWeight / 100.0)
        }
        val formattedGrade = if (newAverage.isNaN()) {
            "0.0%"
        } else {
            "${String.format("%.2f", newAverage)}%"
        }
        calculatedGradeTextView.text = "Grade: $formattedGrade"
    }

    private fun updateHistory(grade: Double) {
        if (historyTextView.text.isNotEmpty()) {
            historyTextView.append(" + ")
        }
        historyTextView.append(grade.toInt().toString())
        historyTextView.visibility = View.VISIBLE // Set visibility to visible

        // Update flag based on mode
        if (currentModeTextView.text.contains("Formative")) {
            totalFormativeGrades += grade
            formativeGradeCount++
        } else {
            totalSummativeGrades += grade
            summativeGradeCount++
        }
    }

    private fun updateModeTextView() {
        if (currentModeTextView.text.contains("Formative")) {
            currentModeTextView.text = "Formative Mode: (${String.format("%.1f", formativeWeight)}%)"
        } else {
            currentModeTextView.text = "Summative Mode: (${String.format("%.1f", summativeWeight)}%)"
        }
    }

    fun onQuitButtonClick(view: View?) {
        finish() // Finish the activity, effectively quitting the app
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">



    <!-- Title: Change Weights -->
    <TextView
        android:id="@+id/textChangeWeights"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update Grade Weights:"
        android:textSize="22sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"/>

    <!-- Formative weight input field -->
    <EditText
        android:id="@+id/editTextFormativeWeight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:hint="Formative Weight (%)"
        android:imeOptions="actionNext"
        android:inputType="numberDecimal"
        android:minWidth="200dp"
        android:minHeight="48dp"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textChangeWeights" />

    <!-- Summative weight input field -->
    <EditText
        android:id="@+id/editTextSummativeWeight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:hint="Summative Weight (%)"
        android:imeOptions="actionDone"
        android:inputType="numberDecimal"
        android:minWidth="200dp"
        android:minHeight="48dp"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextFormativeWeight" />

    <!-- Title: Theme -->
    <TextView
        android:id="@+id/textTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themes:"
        android:textSize="22sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextSummativeWeight"
        android:layout_marginTop="16dp"
        android:layout_marginStart="8dp"/>

    <!-- Theme dropdown menu -->
    <Spinner
        android:id="@+id/themeSpinner"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textTheme"
        tools:listitem="@android:layout/simple_spinner_dropdown_item" />


    <!-- Button (Close) -->
    <ImageButton
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/close_window"
        android:background="@android:color/transparent"
        android:padding="16dp"
        android:contentDescription="Close"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <!-- Button (Save) -->
    <Button
        android:id="@+id/btnSave"
        style="@style/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:layout_marginEnd="12dp"
        android:text="Save"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/themeSpinner" />

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


    <ImageButton
        android:id="@+id/quitButton"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/quit_app_icon_bigger"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:onClick="onQuitButtonClick"
        android:contentDescription="@+string/quit_button_description"/>


    <ImageButton
        android:id="@+id/settingsButton"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/settings_gear_bigger"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:onClick="onSettingsButtonClick"
        android:contentDescription="@+string/settings_button_description"/>


    <TextView
        android:id="@+id/currentmodetext"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"

        android:text="Formative Mode (40%)"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.555"

        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginLeft="30dp"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/inputext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"

        android:text=""
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="115dp"
        app:layout_constraintBottom_toTopOf="@+id/calculatedgradetext"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/currentmodetext"
        app:layout_constraintVertical_bias="0.703" />

    <TextView
        android:id="@+id/calculatedgradetext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="18dp"

        android:layout_marginBottom="16dp"
        android:text="Grade: 0.0%"
        android:textAlignment="center"

        android:textColor="@color/black"
        android:textSize="31dp"
        app:layout_constraintBottom_toTopOf="@+id/historytext"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.482"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/historytext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:layout_margin="5dp"
        android:textSize="18sp"
        android:visibility="gone"
        android:text=""
        android:textColor="@color/historyColor"
        app:layout_constraintBottom_toTopOf="@id/line"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/linecolor"
        app:layout_constraintBottom_toTopOf="@id/linearLayout"
        android:layout_marginBottom="8dp"/>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_7"
                android:onClick="onDigitClick"
                android:text="7" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_8"
                android:onClick="onDigitClick"
                android:text="8" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_9"
                android:onClick="onDigitClick"
                android:text="9" />

            <com.google.android.material.button.MaterialButton
                style="@style/importantButtons"
                android:id="@+id/btn_delete"
                android:onClick="onbackClick"
                app:icon="@drawable/whitebackspace"
                app:iconTint="@color/white"

                android:text="4"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_4"
                android:onClick="onDigitClick"
                android:text="4" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_5"
                android:onClick="onDigitClick"
                android:text="5" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_6"
                android:onClick="onDigitClick"
                android:text="6" />

            <com.google.android.material.button.MaterialButton
                style="@style/importantButtons"
                android:id="@+id/btn_mode"
                android:onClick="onMClick"
                android:text="M" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_1"
                android:onClick="onDigitClick"
                android:text="1" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_2"
                android:onClick="onDigitClick"
                android:text="2" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_3"
                android:onClick="onDigitClick"
                android:text="3" />

            <com.google.android.material.button.MaterialButton
                style="@style/PlusMinusButton"
                android:id="@+id/btn_plusMinus"
                android:onClick="onclearAllClick"
                android:text="AC" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_0"
                android:onClick="onDigitClick"
                android:text="0" />

            <com.google.android.material.button.MaterialButton
                style="@style/digitButton"
                android:id="@+id/btn_period"
                android:onClick="onDigitClick"
                android:text="." />

            <com.google.android.material.button.MaterialButton
                style="@style/operatorButton"
                android:id="@+id/btn_equal"
                android:onClick="onequalClick"

                android:text="=" />

        </LinearLayout>

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
    @Preview(showBackground = true)
    @Composable
    fun scaffold() {
        Scaffold(
            topBar = {
                TopAppBar {
                    Text(text = stringResource(id = R.string.app_name))
                }
            },
            bottomBar = {
                BottomAppBar(
                    cutoutShape = MaterialTheme.shapes.small.copy(CornerSize(percent = 50))
                ) {

                }
            },
            floatingActionButton = {
                FloatingActionButton(onClick = { /*TODO*/ }) {
                    Icon(Icons.Filled.Add, contentDescription = "")
                }
            },
            isFloatingActionButtonDocked = true
        ) {
            main()
        }
    }
val client: BillingClient = ...
val acknowledgePurchaseResponseListener: AcknowledgePurchaseResponseListener = ...

suspend fun handlePurchase() {
    if (purchase.purchaseState === PurchaseState.PURCHASED) {
        if (!purchase.isAcknowledged) {
            val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                    .setPurchaseToken(purchase.purchaseToken)
            val ackPurchaseResult = withContext(Dispatchers.IO) {
               client.acknowledgePurchase(acknowledgePurchaseParams.build())
            }
        }
     }
}
dependencies {
	implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	implementation("com.graphql-java-kickstart:graphql-spring-boot-starter:15.0.0")
	implementation("com.graphql-java-kickstart:graphiql-spring-boot-starter:11.1.0")
	implementation("com.graphql-java-kickstart:graphql-java-tools:13.0.3")
	testImplementation("org.springframework.boot:spring-boot-starter-test")
}
dependencies {
	implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	testImplementation("org.springframework.boot:spring-boot-starter-test")
}
dependencies {
	implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	testImplementation("org.springframework.boot:spring-boot-starter-test")
}
import graphql.kickstart.tools.GraphQLQueryResolver
import me.stegall.personalwebsiteapi3.models.Project
import me.stegall.personalwebsiteapi3.repositories.ProjectRepository
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.stereotype.Component

@Component
class ProjectQueryResolver(
  val projectRepository: ProjectRepository,
  private val mongoOperations: MongoOperations
) : GraphQLQueryResolver {
  fun projects(): List<Project> {
    return projectRepository.findAll()
  }
}
import me.stegall.personalwebsiteapi3.models.Project
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository

@Repository
interface ProjectRepository : MongoRepository<Project, String>
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document

@Document(collection = "projects")
data class Project(
  @Id
  val id: String,
  val description: String,
  val title: String,
  val url: String
)
  private fun downloadfile(
        filUrl: String,
        filePath: String,
        completion: (response: String) -> Unit
    ) {

        binding.progressBar.max = 100
        binding.progressBar.setProgress(0)
        binding.progressTextView.setText("0")

        val storage = FirebaseStorage.getInstance()
        val storageRef =
            storage.getReferenceFromUrl(filUrl)

        val localFile = File(filePath)

        storageRef.getFile(localFile)
            .addOnProgressListener {
                Log.e(TAG, "downloadfile: " + it.bytesTransferred + "/" + it.totalByteCount)
                if (it.totalByteCount.toInt() != -1) {
                    val progress: Double = 100.0 * it.bytesTransferred / it.totalByteCount
                    binding.progressBar.setProgress(progress.toInt())
                    binding.progressTextView.setText(progress.toInt().toString())
                }

            }
            .addOnSuccessListener(object : OnSuccessListener<FileDownloadTask.TaskSnapshot?> {
                override fun onSuccess(taskSnapshot: FileDownloadTask.TaskSnapshot?) {
                    Log.e(
                        TAG,
                        "downloadfile:onSuccess: ;local tem file created  created $localFile"
                    )
                    completion("1")
                }
            }).addOnFailureListener(object : OnFailureListener {
                override fun onFailure(@NonNull exception: java.lang.Exception) {
                    Log.e(
                        TAG,
                        "downloadfile:onFailure: ;local tem file not created  created $exception"
                    )
                    completion("downloadfile:onFailure: ;local tem file not created  created $exception")
                }
            })
    }
    private fun downloadPDF(
        filUrl: String,
        filePath: String,
        completion: (response: String) -> Unit
    ) {

        binding.progressBar.max = 100
        binding.progressBar.setProgress(0)
        binding.progressTextView.setText("0")

        val executor2: ExecutorService = Executors.newSingleThreadExecutor()
        val handler2 = Handler(Looper.getMainLooper())
        executor2.execute {
            //Background work here
            var inputStream: InputStream? = null
            handler2.post {
                val url = URL(filUrl)
                val urlConnection: HttpURLConnection =
                    url.openConnection() as HttpsURLConnection
                if (urlConnection.responseCode == 200) {
                    inputStream = BufferedInputStream(urlConnection.inputStream)
                    try {
                        inputStream = url.openStream()
                        val outputStream = FileOutputStream(filePath)
                        val buffer = ByteArray(1024)

                        //var bytesRead = inputStream.read(buffer)
                        val fileLength: Int = urlConnection.getContentLength()
                        var total: Long = 0
                        var count: Int

                        while (inputStream!!.read(buffer).also { count = it } != -1) {
                            total += count
                            // publishing the progress....
                            if (fileLength > 0) {
                                Log.e(
                                    TAG,
                                    "download_progress: " + (total * 100 / fileLength).toInt()
                                )
                                runOnUiThread {
                                    if (!(total * 100 / fileLength).toInt().toString()
                                            .equals(binding.progressTextView.text)
                                    ) {
                                        binding.progressTextView.setText(
                                            (total * 100 / fileLength).toInt().toString()
                                        )
                                        binding.progressBar.setProgress((total * 100 / fileLength).toInt())
                                    }
                                }
                            } // only if total length is known
                            else {
                                Log.e(
                                    TAG,
                                    "download_progress: " + fileLength
                                )
                            }


                            outputStream.write(buffer, 0, count)
                        }

                        outputStream.close()
                        inputStream!!.close()
                        urlConnection.disconnect();

                        //dialogProgress.dismiss()
                        completion("1")

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

                }

            }
        }

    }
fun String.toEditable(): Editable =  Editable.Factory.getInstance().newEditable(this)
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        jcenter()
    }
}
val shortcutManager = getSystemService(ShortcutManager::class.java)

if (shortcutManager!!.isRequestPinShortcutSupported) {
    // Assumes there's already a shortcut with the ID "my-shortcut".
    // The shortcut must be enabled.
    val pinShortcutInfo = ShortcutInfo.Builder(context, "my-shortcut").build()

    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the shortcut to be pinned. Note that, if the
    // pinning operation fails, your app isn't notified. We assume here that the
    // app has implemented a method called createShortcutResultIntent() that
    // returns a broadcast intent.
    val pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo)

    // Configure the intent so that your app's broadcast receiver gets
    // the callback successfully.For details, see PendingIntent.getBroadcast().
    val successCallback = PendingIntent.getBroadcast(context, /* request code */ 0,
            pinnedShortcutCallbackIntent, /* flags */ 0)

    shortcutManager.requestPinShortcut(pinShortcutInfo,
            successCallback.intentSender)
}

* Reto #50
 * LA ENCRIPTACIÓN DE KARACA
 * Fecha publicación enunciado: 12/11/22
 * Fecha publicación resolución: 19/12/22
 * Dificultad: FÁCIL
 *
 * Enunciado: Crea una función que sea capaz de encriptar y desencriptar texto utilizando el
 * algoritmo de encriptación de Karaca (debes buscar información sobre él).

val numbersMap = mapOf("a" to 0, "e" to 1, "i" to 2, "o" to 3, "u" to 4)
fun main() {
    println(encrypt("apple"))
    println(decrypt(encrypt("apple")))
}


fun encrypt(word:String):String{
    val reversedWord = word.reversed()
    var encryptedWord:String = ""
    reversedWord.forEachIndexed{ i, it ->
           encryptedWord += if(numbersMap.contains(it.toString())) numbersMap[it.toString()] else reversedWord[i]   
    }
     return encryptedWord + "aca"
}

fun decrypt(word:String):String{
    val encriptedWord = word.removeRange(word.length-3, word.length)
    val reversedWord = encriptedWord.reversed()
    var decryptedWord:String = ""
    reversedWord.forEachIndexed{ i, letter ->
           decryptedWord += if(numbersMap.containsValue(Character.getNumericValue(letter))) numbersMap.entries.find { it.value == Character.getNumericValue(letter)}?.key else reversedWord[i]   
    }
    return decryptedWord
}


1. inside Adapter add
interface OnClickListener {
        fun onClick(position: Int, model: HappyPlaceModel) {

        }
    }

2. on top of Adapter make variable
 private var onClickListener : OnClickListener? = null

3. dolje tu dodaj
 
 fun setOnClickListener(onClickListener: OnClickListener) {
        this.onClickListener = onClickListener
    }

4. idi nazad u Activity class
  tamo gdje postavljas RecyclerView
 
  placesAdapter.setOnClickListener(object : HappyPlaceAdapter.OnClickListener)

5. placesAdapter.setOnClickListener(object : HappyPlaceAdapter.OnClickListener{
            override fun onClick(position: Int, model: HappyPlaceModel) {
                super.onClick(position, model)

                val intent = Intent(this@MainActivity, nekiClass::class.java)
                startActivity(intent)
            }
        })
        
6. back to Adapter -> onBindViewHolder

holder.itemView.setOnClickListener {
  if (onClickListener != null)
    onClickListener!!.onClick(position, model)
}

model je zapravo list[position]
    /*
* Crea una función que analice una matriz 3x3 compuesta por "X" y "O"
* y retorne lo siguiente:
* - "X" si han ganado las "X"
* - "O" si han ganado los "O"
* - "Empate" si ha habido un empate
* - "Nulo" si la proporción de "X", de "O", o de la matriz no es correcta.
*   O si han ganado los 2.
* Nota: La matriz puede no estar totalmente cubierta.
* Se podría representar con un vacío "", por ejemplo.
*/

    fun exercize() {
        var result = ""
        val myList = arrayListOf(
            listOf("O", "X", "O"),
            listOf("X", "O", "X"),
            listOf("X", "O", "X")
        )

        val flattedList = myList.flatten()
        val xQuantity = flattedList.filter { it == "X" }.size
        val oQuantity = flattedList.filter { it == "O" }.size

        if(flattedList.size != 9 || oQuantity.compareTo(xQuantity)  !in -1..1){
            result = "Nulo"
        }

        if(result != "Nulo")
        {
            result = checkCols(flattedList)
        }
        
        if(result == "Empate")
        {
            result = checkRows(flattedList)
        }

        if(result == "Empate")
        {
            result = checkDiagonals(flattedList)
        }

        println("Result: $result")
    }

    private fun checkCols(flattedList:List<String>):String =
        when{
            ((flattedList[0] == "X" && flattedList[3] == "X" && flattedList[6] == "X") ||
                    (flattedList[1] == "X" && flattedList[4] == "X" && flattedList[7] == "X") ||
                    (flattedList[2] == "X" && flattedList[5] == "X" && flattedList[8] == "X")) -> "X"

            ((flattedList[0] == "O" && flattedList[3] == "O" && flattedList[6] == "O") ||
                    (flattedList[1] == "O" && flattedList[4] == "O" && flattedList[7] == "O") ||
                    (flattedList[2] == "O" && flattedList[5] == "O" && flattedList[8] == "O")) -> "O"

            else -> "Empate"
        }

    private fun checkRows(flattedList:List<String>):String =
        when{
            ((flattedList[0] == "X" && flattedList[1] == "X" && flattedList[2] == "X") ||
                    (flattedList[3] == "X" && flattedList[4] == "X" && flattedList[5] == "X") ||
                    (flattedList[6] == "X" && flattedList[7] == "X" && flattedList[8] == "X")) -> "X"

            ((flattedList[0] == "O" && flattedList[1] == "O" && flattedList[2] == "O") ||
                    (flattedList[3] == "O" && flattedList[4] == "O" && flattedList[5] == "O") ||
                    (flattedList[6] == "O" && flattedList[7] == "O" && flattedList[8] == "O")) -> "O"

            else -> "Empate"
        }

    private fun checkDiagonals(flattedList:List<String>):String =
        when{
            ((flattedList[0] == "X" && flattedList[4] == "X" && flattedList[8] == "X") ||
                    (flattedList[2] == "X" && flattedList[4] == "X" && flattedList[6] == "X")) -> "X"

            ((flattedList[0] == "O" && flattedList[4] == "O" && flattedList[8] == "O") ||
                    (flattedList[2] == "O" && flattedList[4] == "O" && flattedList[6] == "O")) -> "O"

            else -> "Empate"
        }
binding?.fabAddHappyPlace?.setOnClickListener {
            val intent = Intent(this, AddHappyPlaceActivity::class.java)
            startActivity(intent)
        }
fun isOnline(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (connectivityManager != null) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                return true
            }
        }
    }
    return false
}
/*BATALLA POKÉMON
 * Fecha publicación enunciado: 29/08/22
 * Fecha publicación resolución: 06/09/22
 * Dificultad: MEDIA
 *
 * Enunciado: Crea un programa que calcule el daño de un ataque durante una batalla Pokémon.
 * - La fórmula será la siguiente: daño = 50 * (ataque / defensa) * efectividad
 * - Efectividad: x2 (súper efectivo), x1 (neutral), x0.5 (no es muy efectivo)
 * - Sólo hay 4 tipos de Pokémon: Agua, Fuego, Planta y Eléctrico (buscar su efectividad)
 * - El programa recibe los siguientes parámetros:
 *  - Tipo del Pokémon atacante.
 *  - Tipo del Pokémon defensor.
 *  - Ataque: Entre 1 y 100.
 *  - Defensa: Entre 1 y 100.
 */

private fun main() {
        println(battle(PokemonType.WATER, PokemonType.FIRE, 50, 30))
        println(battle(PokemonType.WATER, PokemonType.FIRE, 101, -10))
        println(battle(PokemonType.FIRE, PokemonType.WATER, 50, 30))
        println(battle(PokemonType.FIRE, PokemonType.FIRE, 50, 30))
        println(battle(PokemonType.GRASS, PokemonType.ELECTRIC, 30, 50))
    }

    private fun battle(attacker: PokemonType, defender: PokemonType, attack: Int, defense: Int): Double? {

        if (attack <= 0 || attack > 100 || defense <= 0 || defense > 100) {
            println("Ataque o defensa incorrecto")
            return null
        }

        val typeEffects = mapOf(
            PokemonType.WATER to PokemonChart(PokemonType.FIRE, PokemonType.GRASS),
            PokemonType.FIRE to PokemonChart(PokemonType.GRASS, PokemonType.WATER),
            PokemonType.GRASS to PokemonChart(PokemonType.WATER, PokemonType.FIRE),
            PokemonType.ELECTRIC to PokemonChart(PokemonType.WATER, PokemonType.GRASS)
        )

        val effectivity = when {
            (attacker == defender || typeEffects[attacker]?.notEffective == defender) -> {
                println("No es muy efectivo")
                0.5
            }
            (typeEffects[attacker]?.effective == defender) -> {
                println("Es súper efectivo")
                2.0
            }
            else -> {
                println("Es neutro")
                1.0
            }
        }

        return 50 * attack.toDouble() / defense.toDouble() * effectivity
    }
    
        enum class PokemonType {
        WATER,
        FIRE,
        GRASS,
        ELECTRIC
    }

    private data class PokemonChart(val effective: PokemonType, val notEffective: PokemonType)
fun main() {
    val array = arrayOf(3, 5, 1, 8, 9, 0)
        val sortedArray = quicksort(array, 0, array.size - 1)
        sortedArray.forEach {
            println(it)
        }
}

private fun quicksort(array: Array<Int>, first: Int, last: Int): Array<Int> {
        var i = first
        var j = last
        var sortedArray = array
        val pivot = (sortedArray[i] + sortedArray[j]) / 2

        while (i < j) {
            while (sortedArray[i] < pivot) {
                i += 1
            }

            while (sortedArray[j] > pivot) {
                j -= 1
            }

            if (i <= j) {
                val x = sortedArray[j]
                sortedArray[j] = sortedArray[i]
                sortedArray[i] = x
                i += 1
                j -= 1
            }
        }

        if (first < j) {
            sortedArray = quicksort(sortedArray, first, j)
        }

        if (last > i) {
            sortedArray = quicksort(sortedArray, i, last)
        }
        return sortedArray
    }
set - samo unique elements

array - ne mozes dodavati nove

lists - mora biti mutableList da mozes dodavati

map - Key/Value; dictionary u Swiftu
val mapOfDays = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday")

arrayList - read & write
		- ArrayList<E>() -> empty arrayList
		- 
/*
 * Enunciado: Dado un array de enteros ordenado y sin repetidos, 
 * crea una función que calcule y retorne todos los que faltan entre
 * el mayor y el menor.
 */

val originalList = listOf(1,2,7,8)
fun main() {
   val newList = findLostNumbers(originalList)
    print(newList)
}

fun findLostNumbers(originalList:List<Int>):ArrayList<Int>{
    val newList = ArrayList<Int>()
    for (i in originalList.first()..originalList.last()) {
        if(!originalList.contains(i))
        {
           newList.add(i) 
        }
    }
    return newList
}
fun addStrNums( num1: String,  num2: String):String {

    var isNum1 = true
    var isNum2 = true

    isNum1 = num1.matches("-?\\d+(\\.\\d+)?".toRegex())
	isNum2 = num2.matches("-?\\d+(\\.\\d+)?".toRegex())
    
    if (isNum1 && isNum2){
        var n1 = num1.toInt()
        var n2 = num2.toInt()
        
        return "${n1+n2}"
    }
    else return "not Number"
}
fun main() {
    print(countWords("Return number of words in String"))
}

fun countWords( txt: String):Int {
    
    var totalWords = txt.trim().split("\\s+".toRegex()).size
    
    return totalWords              
}
package com.scopedstoragepractice

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.storage.StorageManager
import android.provider.DocumentsContract
import android.util.Log
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import com.scopedstoragepractice.Constants.TAG
import com.scopedstoragepractice.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    lateinit var targetPath: String
    lateinit var binding: ActivityMainBinding
    var isLocationGranted: Boolean = false
    var isReadGranted: Boolean = false
    var isAudioGranted: Boolean = false
    lateinit var mPermissionLauncher: ActivityResultLauncher<Array<String>>
    lateinit var mWhatsLauncher: ActivityResultLauncher<Intent>
    lateinit var mWhatsLauncherStatus: ActivityResultLauncher<Intent>
    lateinit var whatsappStatus: String;


    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater);
        setContentView(binding.root)


//        mPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){ permissions->
//            isLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: isLocationGranted
//            isReadGranted = permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: isReadGranted
//            isAudioGranted = permissions[Manifest.permission.RECORD_AUDIO] ?: isAudioGranted
//        }
//
//        requestPermission()


        mWhatsLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if (it?.data != null) {
                    val treeUri = it.data!!.data
                    if (treeUri != null){
                        grantUriPermission(this.packageName,treeUri,Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    //    contentResolver.takePersistableUriPermission(treeUri,Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        getSharedPreferences("MY_PREFS", MODE_PRIVATE).edit().putString("DATA_PATH",
                            treeUri.toString()
                        ).apply()
                    }
                }
            })
        mWhatsLauncherStatus = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if (it?.data != null) {
                    Log.e(TAG, "onCreate: " + it.data!!.data)
                    binding.whatsAppImage.setImageURI(it.data!!.data)
                }
            })

        binding.btnWhatsApp.setOnClickListener {
            val result = readfromprefs()
            if (result){
                val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    type = "image/* video/*"

                    // Optionally, specify a URI for the file that should appear in the
                    // system file picker when it loads.
                    putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse(getSharedPreferences("MY_PREFS",
                        MODE_PRIVATE).getString("DATA_PATH","")))
                }
                mWhatsLauncherStatus.launch(intent)
            }else{
                getFolderPermission()
            }
        }


    }

    private fun readfromprefs(): Boolean {
        if (getSharedPreferences("MY_PREFS", MODE_PRIVATE).getString("DATA_PATH","").toString().isEmpty())
            return false
        else
            return true
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun getFolderPermission() {
        if (Build.VERSION.SDK_INT < 30) {
            // Less then 11
            targetPath =
                Environment.getExternalStorageDirectory().absolutePath + "/WhatsApp/Media/.Statuses"

        } else {
            // Android 11
            targetPath =
                Environment.getExternalStorageDirectory().absolutePath + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses"
        }
        val storageManager = application.getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val intent = storageManager.primaryStorageVolume.createOpenDocumentTreeIntent()
        var uri = intent.getParcelableExtra<Uri>("android.provider.extra.INITIAL_URI") as Uri
        var scheme = uri.toString()
        scheme = scheme.replace("/root/", "/document/")
        scheme += "%3A$targetPath"
        uri = Uri.parse(scheme)
        intent.putExtra("android.provider.extra.INITIAL_URI", uri)
        intent.putExtra("andriod.content.extra.SHOW_ADVANCED", true)
        mWhatsLauncher.launch(intent)
    }


    private fun requestPermission() {

        isLocationGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        isReadGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        isAudioGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED

        val permissionResuest: MutableList<String> = ArrayList()

        if (!isLocationGranted) {
            permissionResuest.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }

        if (!isReadGranted) {
            permissionResuest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        if (!isAudioGranted) {
            permissionResuest.add(Manifest.permission.RECORD_AUDIO)
        }

        if (permissionResuest.isNotEmpty()) {
            mPermissionLauncher.launch(permissionResuest.toTypedArray())
        }


    }

}
//Kotlin Kapt plugin used for annotations
id 'kotlin-kapt'

// RoomDatabase Libraries

 def roomVersion = "2.4.0"
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    implementation "androidx.room:room-ktx:$roomVersion"

// Coroutines
   implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3"
   implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.3"

// LiveCycle and ViewModel
 def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"


// Retrofit

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'



// for enabling view and databinding in android tag

buildFeatures{
        dataBinding true
    }

    viewBinding {
        enabled = true
    }
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import org.koin.android.ext.android.inject
import se.tv4.analytics.page.ScreenTracker

typealias FragmentInflater<T> = (LayoutInflater, ViewGroup?, Boolean) -> T

/**
 * base fragment to share the common functionality between the fragments in the app
 */
abstract class BaseFragment<T : ViewBinding>(private val inflate: FragmentInflater<T>) : Fragment() {

    private var _binding: T? = null

    /**
     * The view binding for this fragment.
     *
     * [https://developer.android.com/topic/libraries/view-binding]
     *
     * This property is only valid between [onCreateView] and [onDestroyView].
     */
    val binding: T
        get() = _binding ?: throw IllegalStateException("Cannot access view outside onCreateView and onDestroyView")

    @CallSuper
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflate(inflater, container, false)
        return binding.root
    }

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}
   fun main() {
        si(true){
            println("True")
        } sino {
            println("False")
        }
        
        val result = si(true){
            println("True")
        } sino {
            println("False")
        }
        println(result)

    }
    private fun si(booleano: Boolean, function: () -> Unit):Boolean{
        if(booleano){ function()}
        return booleano
    }
    private infix fun Boolean.sino(function: () -> Unit):String {
		if(!this){
            function()
        }
        return this.toString().capitalize()
    }
go to the project's res folder and delete the duplicated folder 
in my case anydpi folder 
class viewModel() : ViewModel() {

   private val _sharedFlow = MutableSharedFlow<Int>() // Mutable Share Flow

   val sharedFlow = _sharedFlow.asSharedFlow()  // Immutable Share Flow

   fun squareNumber(number:Int){
       viewModelScope.launch {
           _sharedFlow.emit(number * number)
       }
   }


   init {
       viewModelScope.launch {
           sharedFlow.collect {
               delay(2000L)
               println("First Flow : The received Number is $it")
           }
       }
       viewModelScope.launch {
           sharedFlow.collect {
               delay(3000L)
               println("Secound Flow : The received Number is $it")
           }
       }

       squareNumber(3)
   }
}
class MainActivity : AppCompatActivity() {

   lateinit var button: Button
   lateinit var counter: TextView
   val view_model:ViewModel = viewModel()

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

       button = findViewById(R.id.button)

       counter = findViewById(R.id.counter)

       lifecycleScope.launch {
           repeatOnLifecycle(Lifecycle.State.STARTED) {
               (view_model as viewModel).stateFlow.collectLatest { number ->
                  counter.text = number.toString()
               }
           }
       }

       button.setOnClickListener{
           (view_model as viewModel).incrementCounter()
       }

   }

}

class viewModel() : ViewModel() {

   private val _stateFlow = MutableStateFlow(0);  // Mutable State Flow

   val stateFlow = _stateFlow.asStateFlow();  // Immutable State Flow

   fun incrementCounter(){  // changes the state
       _stateFlow.value +=1;
   }
  
}
/**
 * Used as a wrapper for data that is exposed via a LiveData that represents an event.
 */
open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled. */ fun peekContent(): T = content }Copy the code
@Preview(device = Devices.PIXEL_3A)
@Composable
fun ExamplePreview() {...}
@Preview(uiMode = UI_MODE_NIGHT_NO)
@Preview(uiMode = UI_MODE_NIGHT_YES)
@Composable
fun ExamplePreview() {...}
@Preview(showBackground = true, backgroundColor = 0xff0000)
@Composable
fun ExamplePreview() {...}
@Preview
@Preview(locale = "fr")
@Composable
fun ButtonPreview() {
  Button(
    ...
    content = { Text(text = stringResource(id = R.string.day_monday)) })
}
@Preview(widthDp = 100, heightDp = 100)
@Composable
fun ExamplePreview() {...}
@Preview(group = "Buttons")
@Composable
fun ButtonEnabledPreview() {...}

@Preview(group = "Buttons")
@Composable
fun ButtonDisabledPreview() {...}

@Preview(group = "Texts")
@Composable
fun TextBigPreview() {...}

@Preview(group = "Texts")
@Composable
fun TextSmallPreview() {...}
@Preview(name = "Some preview name")
@Composable
fun ExamplePreview() {
  ...
}
val name: String = "",
val group: String = "",
@IntRange(from = 1) val apiLevel: Int = -1,
val widthDp: Int = -1,
val heightDp: Int = -1,
val locale: String = "",
@FloatRange(from = 0.01) val fontScale: Float = 1f,
val showSystemUi: Boolean = false,
val showBackground: Boolean = false,
val backgroundColor: Long = 0,
@UiMode val uiMode: Int = 0,
@Device val device: String = Devices.DEFAULT
@Preview
@Composable
fun ExamplePreview() {
  Button(
    modifier = Modifier.fillMaxWidth(),
    onClick = {},
    content = { Text(text = "Button") })
}
import kotlin.math.abs

const val riesenieSila = 92
const val riesenieSmer = 15

data class Riesenie(val sila: Int, val smer: Int) {
    fun cost() : Int =
        abs(riesenieSila - sila) +
        abs(riesenieSmer - smer)
}

fun main() {
    // vytvorenie nahodneho riesenia
    var riesenie = Riesenie(50, 60)
    while(true) {
        // ziskanie susednych rieseni
        val noveRiesenia = arrayOf(
            Riesenie(riesenie.sila - 1, riesenie.smer),
            Riesenie(riesenie.sila + 1, riesenie.smer),
            Riesenie(riesenie.sila, riesenie.smer - 1),
            Riesenie(riesenie.sila, riesenie.smer + 1)
        )
        val najlepsieNoveRiesenie = noveRiesenia.minByOrNull{ it.cost() }!!

        // vyhodnotenie
        if (najlepsieNoveRiesenie.cost() > riesenie.cost()) { break }
        else { riesenie = najlepsieNoveRiesenie }
    }

    println("najlepsie riesenie - ${riesenie.sila} / ${riesenie.smer}")
}
package com.example.addressbook

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity

class SplashScreen : AppCompatActivity() {
    private lateinit var runnable:Runnable
    private val handler = Handler()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        runnable = Runnable {
            val intent = Intent(this,MainActivity::class.java)
            startActivity(intent)
            finish()
        }

        handler.postDelayed(runnable,10000)
    }

    override fun onDestroy() {
        handler.removeCallbacks(runnable)
        super.onDestroy()

        //Toast.makeText(this,"onDestroy called",Toast.LENGTH_SHORT).show()
    }
    fun startNextActivity() {
        startActivity(Intent(applicationContext, MainActivity::class.java))
    }

    fun skipSplashScreen() {
        if (handler != null) handler.removeCallbacksAndMessages(null)
        startNextActivity()
    }

    override fun onStop() {
        super.onStop()
        // clear handler on stop
        if (handler != null) handler.removeCallbacksAndMessages(null)
    }
}

<resources>
    <string name="app_name">Implicit Intent Example</string>
    <string name="phone_number">Phone Number</string>
    <string name="call">Call</string>
    <string name="call_logs">Call Logs</string>
    <string name="contact">Contact</string>
    <string name="web_browser">Web Browser</string>
    <string name="gallery">Gallery</string>
    <string name="camera">Camera</string>
    <string name="alarm">Alarm</string>
</resources>

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

    <EditText
        android:id="@+id/et_number"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/phone_number"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_call"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/call"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_number" />

    <Button
        android:id="@+id/btn_call_log"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/call_logs"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_call" />

    <Button
        android:id="@+id/btn_contact"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/contact"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_call_log" />

    <Button
        android:id="@+id/btn_browser"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/web_browser"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_contact" />

    <Button
        android:id="@+id/btn_gallery"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/gallery"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_browser" />

    <Button
        android:id="@+id/btn_camera"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/camera"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_gallery" />

    <Button
        android:id="@+id/btn_alarm"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/alarm"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_camera" />
</android.support.constraint.ConstraintLayout>

---
          import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.AlarmClock
import android.provider.CallLog
import android.provider.CallLog.*
import android.provider.ContactsContract
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val CALL_REQUEST_CODE = 101

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

        setupPermissions()

        // Calling using intent
        btn_call.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:" + et_number.getText())
            startActivity(intent)
        })

        // Call log
        btn_call_log.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.type = Calls.CONTENT_TYPE
            startActivity(intent)
        })

        //Contact
        btn_contact.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = ContactsContract.Contacts.CONTENT_TYPE
            startActivity(intent)
        })

        // browser
        btn_browser.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse("https://tutorial.eyehunts.com/")
            startActivity(intent)
        })

        // Gallery
        btn_gallery.setOnClickListener(View.OnClickListener {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse("content://media/external/images/media/")
            startActivity(intent)
        })

        // camera
        btn_camera.setOnClickListener(View.OnClickListener {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivity(intent)
        })

        // alarm
        btn_alarm.setOnClickListener(View.OnClickListener {
            val intent = Intent(AlarmClock.ACTION_SHOW_ALARMS)
            startActivity(intent)
        })
    }

    private fun setupPermissions() {
        val permission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.CALL_PHONE)

        if (permission != PackageManager.PERMISSION_GRANTED) {
            Log.i("noone", "Permission to Call has denied")
            makeRequest()
        }
    }

    private fun makeRequest() {
        ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.CALL_PHONE),
                CALL_REQUEST_CODE)
    }

}

----manfiest addition---
      <uses-permission android:name="android.permission.CALL_PHONE" />
        
        ----
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.eyehunt.implicitintentexample">

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application <=Example

-------
      val emailIntent = Intent(Intent.ACTION_SENDTO).apply { 
    data = Uri.parse("mailto:abc@xyz.com")
}
startActivity(Intent.createChooser(emailIntent, "Send feedback"))

Email Intent
//dependencies
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    ... ... ...
    
    // Add for using latest experimental build of Android Extensions
    androidExtensions {
        experimental = true
    }
}
//parceable class
@Parcelize
data class Category(
    var categoryId: Int,
    var categoryName: String
) : Parcelable
--next class--
@Parcelize
data class Item(
    var imageId: Int,
    var title: String,
    var price: Double,
    var category: Category
) : Parcelable
--passing--
val intent = Intent(this, AnotherActivity::class.java)
item.title = "Anas Rathore"
item.price = 50303
intent.putExtra("extra_item", item.title)
intent.putExtra("item_price", item.price)<- key and object
--retreving--
val item = intent.getParcelableExtra("extra_item")
val item = intent.getParceableExtra("item_price")
// Do something with the item (example: set Item title and price)

--if object is pre-defined, data is pre-defined or hard coded--
val student <- object = Student() <- class
//serliaze class
import java.io.Serializable

class MyCustomObject: Serializable {

	var name = ""
	var id = 0
	var place = ""

	constructor(mName: String, mId: Int, mPlace: String){
		name = mName
		id = mId
		place = mPlace
	}

	constructor()
}

//XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	tools:context=".MainActivity">

	<Button
		android:id="@+id/btnSend"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerInParent="true"
		android:text="Send" />

</RelativeLayout>


//Main Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import java.io.Serializable

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

		val btn = findViewById<Button>(R.id.btnSend)

		btn.setOnClickListener {
			val intent = Intent(this, SecondActivity::class.java)
			val passingObject = MyCustomObject()
			passingObject.name = "Geek"
			passingObject.id = 1
			passingObject.place = "India"
			intent.putExtra("object", passingObject)
			startActivity(intent)
		}
	}
}
//Second Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class SecondActivity : AppCompatActivity() {
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_second)

		val myIntent = intent
		val derivedObject = myIntent.getSerializableExtra("object") as MyCustomObject

		val myTextView = findViewById<TextView>(R.id.tv1)
		myTextView.append(derivedObject.name + "\n")
		myTextView.append(derivedObject.id.toString() + "\n")
		myTextView.append(derivedObject.place + "\n")
	}
}
//XmL
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<TextView
		android:id="@+id/tv1"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:layout_centerInParent="true"/>

</RelativeLayout>
//EXAMPLE

class MainActivity : AppCompatActivity() {  
  
    private val sharedPrefFile = "kotlinsharedpreference"  
  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
  
        val inputId = findViewById<EditText>(R.id.editId)  
        val inputName = findViewById<EditText>(R.id.editName)  
        val outputId = findViewById<TextView>(R.id.textViewShowId)  
        val outputName = findViewById<TextView>(R.id.textViewShowName)  
  
        val btnSave = findViewById<Button>(R.id.save)  
        val btnView = findViewById<Button>(R.id.view)  
        val btnClear = findViewById<Button>(R.id.clear)  
        val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile,Context.MODE_PRIVATE)  
        btnSave.setOnClickListener(View.OnClickListener {  
            val id:Int = Integer.parseInt(inputId.text.toString())  
            val name:String = inputName.text.toString()  
            val editor:SharedPreferences.Editor =  sharedPreferences.edit()  
            editor.putInt("id_key",id)  
            editor.putString("name_key",name)  
            editor.apply()  
            editor.commit()  
        })  
        btnView.setOnClickListener {  
            val sharedIdValue = sharedPreferences.getInt("id_key",0)  
            val sharedNameValue = sharedPreferences.getString("name_key","defaultname")  
            if(sharedIdValue.equals(0) && sharedNameValue.equals("defaultname")){  
                outputName.setText("default name: ${sharedNameValue}").toString()  
                outputId.setText("default id: ${sharedIdValue.toString()}")  
            }else{  
                outputName.setText(sharedNameValue).toString()  
                outputId.setText(sharedIdValue.toString())  
            }  
  
        }  
        btnClear.setOnClickListener(View.OnClickListener {  
            val editor = sharedPreferences.edit()  
            editor.clear()  
            editor.apply()  
            outputName.setText("").toString()  
            outputId.setText("".toString())  
        })  
    }  
}  
#add dependencies
dependencies{
  // for adding recyclerview
  implementation 'androidx.recyclerview:recyclerview:1.2.0'
  
  // for adding cardview
  implementation 'androidx.cardview:cardview:1.0.0'
}

#activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	tools:context=".MainActivity">

	<androidx.recyclerview.widget.RecyclerView
		android:id="@+id/recyclerview"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		tools:itemCount="5"
		tools:listitem="@layout/card_view_design" />
	
</LinearLayout>

#new resource layout (card_view_design.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="50dp"
	android:layout_margin="10dp"
	app:cardElevation="6dp">

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:orientation="horizontal"
		android:padding="5dp">

		<ImageView
			android:id="@+id/imageview"
			android:layout_width="40dp"
			android:layout_height="40dp" />

		<TextView
			android:id="@+id/textView"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_marginStart="10dp"
			android:layout_marginLeft="15dp"
			android:text="Item"
			android:textSize="20sp"
			android:textStyle="bold" />

	</LinearLayout>

</androidx.cardview.widget.CardView>

#new class
Go to app > java > package name > right-click > New > Kotlin class/file
data class ItemsViewModel(val image: Int, val text: String) {
}
#custom Adapter class
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class CustomAdapter(private val mList: List<ItemsViewModel>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

	// create new views
	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
		// inflates the card_view_design view
		// that is used to hold list item
		val view = LayoutInflater.from(parent.context)
			.inflate(R.layout.card_view_design, parent, false)

		return ViewHolder(view)
	}

	// binds the list items to a view
	override fun onBindViewHolder(holder: ViewHolder, position: Int) {

		val ItemsViewModel = mList[position]

		// sets the image to the imageview from our itemHolder class
		holder.imageView.setImageResource(ItemsViewModel.image)

		// sets the text to the textview from our itemHolder class
		holder.textView.text = ItemsViewModel.text

	}

	// return the number of the items in the list
	override fun getItemCount(): Int {
		return mList.size
	}

	// Holds the views for adding it to image and text
	class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
		val imageView: ImageView = itemView.findViewById(R.id.imageview)
		val textView: TextView = itemView.findViewById(R.id.textView)
	}
}

----main activity.kt------
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

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

		// getting the recyclerview by its id
		val recyclerview = findViewById<RecyclerView>(R.id.recyclerview)

		// this creates a vertical layout Manager
		recyclerview.layoutManager = LinearLayoutManager(this)

		// ArrayList of class ItemsViewModel
		val data = ArrayList<ItemsViewModel>()

		// This loop will create 20 Views containing
		// the image with the count of view
		for (i in 1..20) {
			data.add(ItemsViewModel(R.drawable.ic_baseline_folder_24, "Item " + i))
		}

		// This will pass the ArrayList to our Adapter
		val adapter = CustomAdapter(data)

		// Setting the Adapter with the recyclerview
		recyclerview.adapter = adapter

	}
}

----for grid view only change line 130,
  recyclerview.layoutManager = GridLayoutManager(this,2)
----If any issue while running check manifest----
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dynamicphotoframe">

    <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/Theme.DynamicPhotoFrame">
        <activity
            android:name=".MainActivity"
            android:exported="true" >
            <intent-filter android:exported="true">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
#Main Activity   
		var fname = findViewById(R.id.firstName) as EditText
        var email = findViewById(R.id.email) as EditText
        var submit = findViewById(R.id.go) as Button


        submit.setOnClickListener{
            var name = fname.text.toString()
            var email_des = email.text.toString()
            var intent = Intent(this, HomeActivity::class.java)
            intent.putExtra("name", name)
            intent.putExtra("email", email_des)
            startActivity(intent)
        }
#2nd activity to get data
        val name_display = findViewById(R.id.name_display) as TextView
        val email_display = findViewById(R.id.email_display) as TextView
        val btn = findViewById(R.id.next_id) as Button

        var name = intent.getStringExtra("name")
        var email = intent.getStringExtra("email")

         name_display.text = name
        email_display.text = email

        btn.setOnClickListener{
            val intent = Intent(this,ThirdActivity::class.java)
            startActivity(intent)
        }
#third

        val btn = findViewById(R.id.back_button) as Button

        btn.setOnClickListener{
            val intent = Intent(this,MainActivity::class.java)
            startActivity(intent)
        }
class MainActivity : AppCompatActivity(), View.OnClickListener {
    //private var txMessage:TextView?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


		edEmailAddress.setText("ali@gmail.com")
        edPassword.setText("Ali@1234")

        btnSignIn.setOnClickListener(this)
private fun onSignIn(){
        /*val email = edEmailAddress.text.toString().trim()
        val password = edPassword.text.toString().trim()*/
        val emailRegex = Regex("^[\\w!#\$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#\$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}\$")
        val passwordRegex = Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$")
        val email = edEmailAddress.getInputText()
        val password = edPassword.getInputText()


        if(email.isNullOrEmpty()){
            showToast("please enter your email address")
            return
        }

        if(!emailRegex.matches(email)){
            showToast("please enter valid email address")
            return
        }

        if(password.isNullOrEmpty()){
            showToast("please enter your password")
            return
        }

        if(!passwordRegex.matches(password)){
            showToast("please enter your password")
            return
        }
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RadioButton
                android:id="@+id/rb10Above"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="10-17"/>

            <RadioButton
                android:id="@+id/rb18Above"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="18-30"/>

            <RadioButton
                android:id="@+id/rb31Above"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="31-Above"/>
        </RadioGroup>

        <CheckBox
            android:id="@+id/cbTermsConditions"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/terms_conditions"/>

              
    override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        showToast(p0?.getItemAtPosition(p2).toString())
    }

    override fun onNothingSelected(p0: AdapterView<*>?) {

    }

    fun onSignUpClicked(view: View) {
        executeSignUp()
    }
    private fun executeSignUp(){
        AlertDialog.Builder(this).apply {
            setTitle("Title")
            setMessage("RB 10 Above = ${rb10Above.isChecked}" +
                    "\nRB 18 Above = ${rb18Above.isChecked}" +
                    "\nRB 31 Above = ${rb31Above.isChecked}" +
                    "\n\nTerms & Conditions = ${cbTermsConditions.isChecked}")
            setPositiveButton("Ok") { dialogInterface, i ->
                dialogInterface.dismiss()
            }
            setNegativeButton("Cancel") { dialogInterface, i ->
                dialogInterface.dismiss()
            }
        }.create().show()
    }
        <TextView
            style="@style/AppLabelStyle"
            android:text="@string/date_of_birth" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:background="@drawable/bg_editbox">

            <TextView
                android:id="@+id/txDOB"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:text="DD-MM-YYYY"
                android:paddingLeft="5dp"
                android:gravity="center_vertical"/>

            <ImageView
                android:id="@+id/imDOB"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:src="@drawable/ic_calendar"/>
        </LinearLayout>

class SignUpActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {
    private val cal = Calendar.getInstance()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_up)
        updateDOBOnUI()


        val dateChangeListener = DatePickerDialog.OnDateSetListener{datePicker, year, month, dayOfMonth ->
            cal.set(Calendar.YEAR, year)
            cal.set(Calendar.MONTH, month)
            cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            updateDOBOnUI()
        }

        imDOB.setOnClickListener {
            DatePickerDialog(
                this,
                dateChangeListener,
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)
            ).show()
        }
    }
          
private val genderArr = arrayOf("Select Gender","Male","Female","Other")
setGenderDropDown()

 private fun setGenderDropDown(){
        //val adapter = ArrayAdapter.createFromResource(this, R.array.gender_array, android.R.layout.simple_dropdown_item_1line)
        val adapter = ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, genderArr)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spGender.adapter = adapter

        spGender.onItemSelectedListener = this
    }

//XML

        <Spinner
            android:id="@+id/spGender"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@drawable/bg_editbox"/>
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Toast

class SplashActivity : AppCompatActivity() {
    private lateinit var runnable:Runnable
    private val handler = Handler()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        runnable = Runnable {
            val intent = Intent(this,SignUpActivity::class.java)
            startActivity(intent)
            finish()
        }

        handler.postDelayed(runnable,3000)
    }

    override fun onDestroy() {
        handler.removeCallbacks(runnable)
        super.onDestroy()

        //Toast.makeText(this,"onDestroy called",Toast.LENGTH_SHORT).show()
    }
}

//XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SplashActivity"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tx_splash"
        android:textSize="30dp"
        android:textColor="@color/red"/>
</LinearLayout>
class KtApp : Application() {

    init {
        instance = this
    }

    companion object{
        private var instance: Application? = null
        fun getInstance(): Application? {
            return instance
        }
    }

    override fun onCreate() {
        super.onCreate()

    }
}
import androidx.preference.PreferenceManager
import com.delfi.area51.ktstart.KtApp

open class PrefUtils {

    companion object {
        private fun getSharePreferences() =
            PreferenceManager.getDefaultSharedPreferences(KtApp.getInstance())

        private fun getEditor() = getSharePreferences().edit()

        fun getString(key: String) = getSharePreferences().getString(key, "")
        fun setString(key: String, value: String) = getEditor().putString(key, value).apply()

        fun getLong(key: String) = getSharePreferences().getLong(key, 0)
        fun setLong(key: String, value: Long) = getEditor().putLong(key, value).apply()

        fun getInt(key: String): Int = getSharePreferences().getInt(key, 0)
        fun setInt(key: String, value: Int) = getEditor().putInt(key, value).apply()
        
        fun getBoolean(key: String): Boolean = getSharePreferences().getBoolean(key, false)
        fun setBoolean(key: String, value: Boolean) = getEditor().putBoolean(key, value).apply()
    }
}
You need to override onSaveInstanceState(Bundle outState).

The method you're overriding only gets called if with the attribute persistableMode is set to persistAcrossReboots in your Manifest.
/**
 * Captures the output of a Gradle exec command.
 * ####Example:
 * ```
 * tasks {
 *    register<Task>("restartAppServer") {
 *        group = "MyTasks"
 *        description = "Restarts your local PS app server."
 *        val output = execWithOutput {
 *            workingDir(projectDir)
 *            commandLine("cmd", "/c", "restartAppServer.bat")
 *        }
 *        doLast { println(output) }
 *    }
 * }
 * ```
 */
fun Project.execWithOutput(spec: ExecSpec.() -> Unit): String = ByteArrayOutputStream().use { outputStream ->
    exec {
        standardOutput = outputStream
        spec()
    }
    outputStream.toString()
}
register<Exec>("restartAppServer") {
    group = "MyTasks"
    description = "Stops your local PS app server."
    workingDir(projectDir)
    commandLine("cmd", "/c", "restartAppServer.bat")
    standardOutput = ByteArrayOutputStream()
    val getOutput: () -> String = {
        standardOutput.toString()
    }
    doFirst { println(commandLine) }
    doLast {
        println(getOutput())
    }
}
Box(
    modifier = Modifier.padding(LocalPaddings.current)
){
		// some composable padded by 24.dp
}
// Definition with default value
val LocalPaddings = compositionLocalOf { PaddingValues(0.dp) }

.
.
.

// Using CompositionLocal App-wide
CompositionLocalProvider(LocalPaddings provides PaddingValues(24.dp)) {
		/*
			your app composables...
		*/
}
val textColor = color.takeOrElse {
    style.color.takeOrElse {
        LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
    }
}
CompositionLocalProvider(LocalContentColor provides Color.Blue) {
		// content color for all components in this scope is blue
    Text(text = "Lorem")
    CompositionLocalProvider(LocalContentColor provides Color.Red) {
				// content color for all components in this scope is blue
        Text(text = "ipsum")
        Text(text = "dolor")
        CompositionLocalProvider(LocalContentAlpha provides 0.2f) {
						// alpha of all components in this scope is 0.2f
            Text(text = "sit...")
        }
    }
}
val sheetState = rememberModalBottomSheetState(
    initialValue = ModalBottomSheetValue.Hidden,
    confirmStateChange = { it != ModalBottomSheetValue.HalfExpanded }
)
val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

Button(
    onClick = {
        scope.launch { 
						// Important part
            sheetState.show()  
        }
    },
    content = { ... }
)
val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
fun ModalBottomSheetLayout(
    sheetContent: @Composable ColumnScope.() -> Unit,
    modifier: Modifier = Modifier,
    sheetState: ModalBottomSheetState = rememberModalBottomSheetState(Hidden),
    sheetShape: Shape = MaterialTheme.shapes.large,
    sheetElevation: Dp = ModalBottomSheetDefaults.Elevation,
    sheetBackgroundColor: Color = MaterialTheme.colors.surface,
    sheetContentColor: Color = contentColorFor(sheetBackgroundColor),
    scrimColor: Color = ModalBottomSheetDefaults.scrimColor,
    content: @Composable () -> Unit
)
@Composable
fun BackdropScaffold(
    appBar: @Composable () -> Unit,
    backLayerContent: @Composable () -> Unit,
    frontLayerContent: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    scaffoldState: BackdropScaffoldState = rememberBackdropScaffoldState(Concealed),
    gesturesEnabled: Boolean = true,
    peekHeight: Dp = BackdropScaffoldDefaults.PeekHeight,
    headerHeight: Dp = BackdropScaffoldDefaults.HeaderHeight,
    persistentAppBar: Boolean = true,
    stickyFrontLayer: Boolean = true,
    backLayerBackgroundColor: Color = MaterialTheme.colors.primary,
    backLayerContentColor: Color = contentColorFor(backLayerBackgroundColor),
    frontLayerShape: Shape = BackdropScaffoldDefaults.frontLayerShape,
    frontLayerElevation: Dp = BackdropScaffoldDefaults.FrontLayerElevation,
    frontLayerBackgroundColor: Color = MaterialTheme.colors.surface,
    frontLayerContentColor: Color = contentColorFor(frontLayerBackgroundColor),
    frontLayerScrimColor: Color = BackdropScaffoldDefaults.frontLayerScrimColor,
    snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) }
)
val view: View = LayoutInflater.from(LocalContext.current).inflate(R.layout.info_fragment, null)

AndroidView
(
factory = { view },
modifier = Modifier.fillMaxWidth()
)
@Composable
fun CustomDialog(
    onNegativeClick: () -> Unit,
    onPositiveClick: () -> Unit,
) {
    Dialog(
        onDismissRequest = {
            //Executes when dialog is dismissed
        },
    ) {
        Column(
            modifier = Modifier
                .background(Color(0xff2c3e50))
                .fillMaxWidth()
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()

            ) {
                val view: View =
                    LayoutInflater.from(LocalContext.current).inflate(R.layout.info_fragment, null)
                AndroidView(
                    factory = { view },
                    modifier = Modifier.fillMaxWidth()
                )
               val imageView = view.findViewById<ImageView>(R.id.pic)
                imageView.setOnClickListener {
                    //Perform action for Imageview click event
                }
            }
            Row(
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .background(
                        Color(0xff2c3e50)
                    )
            ) {

                TextButton(onClick = onNegativeClick) {
                    Text(
                        text = "Cancel",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = Color.White)
                    )
                }
                Spacer(modifier = Modifier.width(4.dp))
                TextButton(onClick = {
                    onPositiveClick()
                }) {
                    Text(text = "Ok",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = Color.White
                        )
                    )
                }
            }
        }


    }
}
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'

implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"

androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
ext {
        compose_version = '1.0.4'
    }
colors = TextFieldDefaults.outlinedTextFieldColors(
    focusedBorderColor = Color.Yellow,
    leadingIconColor = Color.Yellow
)
keyboardActions = KeyboardActions(
    onAny = {} // do when ANY of ime actions is emitted
)

//OR

keyboardActions = KeyboardActions(
    onDone = {}, // do when SPECIFIED action is emitted
    onSearch = {},
    .
    .
}
keyboardOptions = KeyboardOptions.Default.copy(
    capitalization = KeyboardCapitalization.Words,
    autoCorrect = false,
    keyboardType = KeyboardType.Text,
    imeAction = ImeAction.Search
)
visualTransformation = PasswordVisualTransformation()
leadingIcon = { Icon(imageVector = Icons.Default.Info, contentDescription = "") }

//OR

leadingIcon = { Text(text = "$") }
placeholder = { Text(text = "Placeholder for text") }
label = { Text(text = "Label for text") }
textStyle = MaterialTheme.typography.h3
@Composable
fun OutlinedTextField(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    readOnly: Boolean = false,
    textStyle: TextStyle = LocalTextStyle.current,
    label: @Composable (() -> Unit)? = null,
    placeholder: @Composable (() -> Unit)? = null,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    isError: Boolean = false,
    visualTransformation: VisualTransformation = VisualTransformation.None,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    keyboardActions: KeyboardActions = KeyboardActions.Default,
    singleLine: Boolean = false,
    maxLines: Int = Int.MAX_VALUE,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    shape: Shape = MaterialTheme.shapes.small,
    colors: TextFieldColors = TextFieldDefaults.outlinedTextFieldColors()
)
val painter = rememberImagePainter(
    data = url,
    builder = {
        crossfade(true) //Crossfade animation between images
        placeholder(R.drawable.ic_image_loading) //Used while loading
        fallback(R.drawable.ic_empty) //Used if data is null
        error(R.drawable.ic_empty) //Used when loading returns with error
    }
)
Row(
    modifier = Modifier.padding(16.dp),
    horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
    //Important image loading part
    //Remembering of painter
    val painter = rememberImagePainter(data = cat.photoUrl)
	
    Image(
       modifier = Modifier
           .size(100.dp)
           .clip(RoundedCornerShape(16.dp)),
       //Use painter in Image composable
       painter = painter,
       contentDescription = "Cat"
    )
    //Rest of compose code
}
Image(
    painter = ColorPainter(Color.Yellow), 
    contentDescription = "Yellow rectangle"
)
Image(
    imageVector = Icons.Default.Info,
    contentDescription = "Cat informations"
)
val bitmap = getBitmapFromYourSource()
Image(
    bitmap = bitmap, 
    contentDescription = "Cat"
)
@Composable
fun Image(
    //bitmap or vector or painter
    contentDescription: String?,
    modifier: Modifier = Modifier,
    alignment: Alignment = Alignment.Center,
    contentScale: ContentScale = ContentScale.Fit,
    alpha: Float = DefaultAlpha,
    colorFilter: ColorFilter? = null
)
SnackbarHost(
    modifier = Modifier.align(Alignment.BottomCenter),
    hostState = snackbarHostState,
    snackbar = { snackbarData: SnackbarData ->
        Card(
            shape = RoundedCornerShape(8.dp),
            border = BorderStroke(2.dp, Color.White),
            modifier = Modifier
                .padding(16.dp)
                .wrapContentSize()
        ) {
            Column(
                modifier = Modifier.padding(8.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(imageVector = Icons.Default.Notifications, contentDescription = "")
                Text(text = snackbarData.message)
            }
        }
    }
)
@Composable
fun SnackbarScreen() {
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    .
    .
    .
    FloatingActionButton(
        onClick = {
	    //Important part here
            scope.launch {
                snackbarHostState.showSnackbar("Hello there")
            }
	    //
        },
        content = { Icon(imageVector = Icons.Default.Add, contentDescription = "") }
    )
	
    SnackbarHost(hostState = snackbarHostState)
}
val snackbarHostState = remember { SnackbarHostState() }
.
.
.
SnackbarHost(hostState = snackbarHostState)
@Composable
fun SnackbarHost(
    hostState: SnackbarHostState,
    modifier: Modifier = Modifier,
    snackbar: @Composable (SnackbarData) -> Unit = { Snackbar(it) }
)
content: @Composable (PaddingValues) -> Unit
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
.
.
.
scaffoldState = scaffoldState,
floatingActionButton = {
    FloatingActionButton(
        onClick = {
            scope.launch {
                scaffoldState.snackbarHostState.showSnackbar("Hello there!")
            }
        },
        content = {
            Icon(imageVector = Icons.Default.Favorite, contentDescription = "")
        }
    )
}
snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) }
drawerContent = {
    Icon(
        modifier = Modifier.padding(16.dp),
        imageVector = Icons.Default.Person,
        contentDescription = ""
    )
    Text(modifier = Modifier.padding(16.dp), text = "First line")
    Text(modifier = Modifier.padding(16.dp), text = "Second line")
    Text(modifier = Modifier.padding(16.dp), text = "Third line")
}
drawerContent: @Composable (ColumnScope.() -> Unit)? = null
floatingActionButton = {
    FloatingActionButton(
        onClick = {},
        content = {
            Icon(imageVector = Icons.Default.Favorite,contentDescription = "")
        }
    )
}
floatingActionButton: @Composable () -> Unit = {}
bottomBar = {
    BottomAppBar(
        content = {
            Icon(modifier = padding, imageVector = Icons.Default.Menu, contentDescription = "Menu")
            Icon(modifier = padding, imageVector = Icons.Default.Search, contentDescription = "Search")
            Text(text = "Anything can be here")
        }
    )
}
bottomBar: @Composable () -> Unit = {}
topBar = {
    TopAppBar(
        title = { Text(text = "Title text") },
        navigationIcon = {
            Icon(modifier = padding, imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
        },
        actions = {
            Icon(modifier = padding, imageVector = Icons.Default.Favorite, contentDescription = "Favorite")
            Icon(modifier = padding, imageVector = Icons.Default.Search, contentDescription = "Search")
        }
    )
}
topBar: @Composable () -> Unit = {}
@Composable
fun Scaffold(
    modifier: Modifier = Modifier,
    scaffoldState: ScaffoldState = rememberScaffoldState(),
    topBar: @Composable () -> Unit = {},
    bottomBar: @Composable () -> Unit = {},
    snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) },
    floatingActionButton: @Composable () -> Unit = {},
    floatingActionButtonPosition: FabPosition = FabPosition.End,
    isFloatingActionButtonDocked: Boolean = false,
    drawerContent: @Composable (ColumnScope.() -> Unit)? = null,
    drawerGesturesEnabled: Boolean = true,
    drawerShape: Shape = MaterialTheme.shapes.large,
    drawerElevation: Dp = DrawerDefaults.Elevation,
    drawerBackgroundColor: Color = MaterialTheme.colors.surface,
    drawerContentColor: Color = contentColorFor(drawerBackgroundColor),
    drawerScrimColor: Color = DrawerDefaults.scrimColor,
    backgroundColor: Color = MaterialTheme.colors.background,
    contentColor: Color = contentColorFor(backgroundColor),
    content: @Composable (PaddingValues) -> Unit
)
date    .text = string(R.string.attendance_detail_header_date)
category.text = string(R.string.attendance_detail_header_category)
time    .text = string(R.string.attendance_detail_header_time)
duration.text = string(R.string.attendance_detail_header_duration)
shift   .text = string(R.string.attendance_detail_header_time)
arrival .text = string(R.string.attendance_detail_header_arrival)
date.text = string(R.string.attendance_detail_header_date)
category.text = string(R.string.attendance_detail_header_category)
time.text = string(R.string.attendance_detail_header_time)
duration.text = string(R.string.attendance_detail_header_duration)
shift.text = string(R.string.attendance_detail_header_time)
arrival.text = string(R.string.attendance_detail_header_arrival)
fun View.actionsPage(
    actions: List<Action>,
    grid: Grid,
    itemsPerPage: Int,
    position: Int,
    settings: Settings
) = whenAttached { }


fun View.actionsPage(
    actions      : List<Action>,
    grid         : Grid,
    itemsPerPage : Int,
    position     : Int,
    settings     : Settings
) = whenAttached { }
data class EmployeeDetail(
    val employee: Employee,
    val personalNumber: PersonalNumber,
    val hasCard: Boolean,
    val hasPin: Boolean,
    val fingerprints: List<Finger>
)


data class EmployeeDetail(
    val employee       : Employee,
    val personalNumber : PersonalNumber,
    val hasCard        : Boolean,
    val hasPin         : Boolean,
    val fingerprints   : List<Finger>
)
class FunctionProcessorProvider : SymbolProcessorProvider {

    override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
        return FunctionProcessor(
            options = environment.options,
            logger = environment.logger,
            codeGenerator = environment.codeGenerator
        )
    }
}
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
enum class PaymentOption {
    CASH,
    CARD,
    TRANSFER
}

fun PaymentOption.startPayment(transaction: TransactionData) {
    when (this) {
        PaymentOption.CASH -> showCashPaimentInfo(transaction)
        PaymentOption.CARD -> moveToCardPaymentPage(transaction)
        PaymentOption.TRANSFER -> {
            showMoneyTransferInfo()
            setupPaymentWatcher(transaction)
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>

  <ScrollView

        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:fillViewport="true"
  >

    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/constraint_layout1"
            >


        <com.google.android.material.textfield.TextInputLayout

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toTopOf="@+id/username_input_layout"
                android:padding="16dp"
                app:helperText="Email"
                android:id="@+id/email_input_layout"
                app:layout_constraintVertical_chainStyle="packed"
                app:layout_constraintVertical_bias=".1"

        >

            <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/email"
                    android:textColor="#000"
                    android:hint="@string/your_email"
                    android:textSize="20sp"
            />

        </com.google.android.material.textfield.TextInputLayout>


        <com.google.android.material.textfield.TextInputLayout

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/email_input_layout"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toTopOf="@+id/change_password"
                android:padding="16dp"
                app:helperText="Username"
                android:id="@+id/username_input_layout"

        >

            <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/username"
                    android:textColor="#000"
                    android:hint="@string/your_username"
                    android:textSize="20sp"

            />

        </com.google.android.material.textfield.TextInputLayout>


        <TextView

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/username_input_layout"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:textSize="18sp"
                android:textColor="@color/link_blue"
                android:text="@string/change_password"
                android:id="@+id/change_password"
                android:gravity="center"

        />

        <Button

                android:id="@+id/logout_button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/change_password"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:background="@drawable/red_button_drawable"
                android:text="Log out"
                android:textAllCaps="false"
                android:textColor="#fff"
                android:textSize="16sp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginTop="50dp"
                android:layout_marginBottom="30dp"

        />
                  
    </androidx.constraintlayout.widget.ConstraintLayout>


</ScrollView>
// Create an array and instantiate a listview
val myArray : MutableList<BigInteger> = mutableListOf(); val lstView = findViewById<ListView>(R.id.lsvw)

// Create an adapter and link it to the listview
val arrayAdapter : ArrayAdapter<BigInteger> = ArrayAdapter<BigInteger(this, android.R.layout.simple_list_item_1, myArray)
lstView.adapter = arrayAdapter

// Add data to the array and push it to the adapter
myArray.add(<data>)
arrayAdapter.notifyDataSetChanged()
userInput.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->

	if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {

		//code
		return@OnKeyListener true

	}

	false

})
var a = 1;
var b = 2;
    
a = b.also { b = a } // now a = 2, b = 1
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.Group
	android:id="@+id/group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="text,button"/>

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Text"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"
        app:layout_constraintTop_toBottomOf="@id/text"/>
    
</androidx.constraintlayout.widget.ConstraintLayout>
class SleepTrackerViewModelFactory(
       private val dataSource: SleepDatabaseDao,
       private val application: Application) : ViewModelProvider.Factory {
   @Suppress("unchecked_cast")
   override fun <T : ViewModel?> create(modelClass: Class<T>): T {
       if (modelClass.isAssignableFrom(SleepTrackerViewModel::class.java)) {
           return SleepTrackerViewModel(dataSource, application) as T
       }
       throw IllegalArgumentException("Unknown ViewModel class")
   }
}
// MyFragment.kt

class MyFragment : Fragment(R.layout.fragment_my) {
  
  private var _binding: MyFragmentBinding? = null
  private val binding get() = _binding!!

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    _binding = MyFragmentBinding.bind(view)
    
    binding.someview.text = "bla bla"
  }

  override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
  }
}
@RequestMapping(produces = [MediaType.TEXT_HTML_VALUE, CustomMediaType.TURBO_STREAM_VALUE])
suspend fun pinger(model: Model): String {
    model.addAttribute("pingTime", pingService.ping(hostname, port))
    return "ping.turbo-stream"
}
listOf(0,1,2,null,4,null,6,7).forEach{
     it?.let{
         println(it)
     } ?: println("null detected")
 }
package adapter

import android.content.Context
import android.view.ViewGroup
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import domain.ViewType
import domain.movie.ListaItemFilme
import pessoaspopulares.adapter.LoadingDelegateAdapter
import pessoaspopulares.adapter.ViewTypeDelegateAdapter
import utils.Constant

/**
 * Created by icaro on 14/08/16.
 */
class ListUserAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val listaResult = ArrayList<ViewType>()
    private val delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()

    init {
        delegateAdapters.put(Constant.ViewTypesIds.LOADING, LoadingDelegateAdapter())
        delegateAdapters.put(Constant.ViewTypesIds.NEWS, ListasDelegateAdapter())
        listaResult.add(loading)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, listaResult[position], context)
    }

    override fun getItemViewType(position: Int): Int {
        return listaResult[position].getViewType()
    }

    fun addItens(listaMedia: List<ListaItemFilme?>?, totalResults: Int) {
        if (listaMedia?.isNotEmpty()!!) {
            val initPosition = listaResult.size - 1
            this.listaResult.removeAt(initPosition)
            notifyItemRemoved(initPosition)
            for (result in listaMedia) {
                this.listaResult.add(result!!)
            }
            this.listaResult.sortedBy { (it as ListaItemFilme).releaseDate }
                .reversed()
            notifyItemRangeChanged(initPosition, this.listaResult.size + 1 /* plus loading item */)
            if (listaResult.size < totalResults)
                this.listaResult.add(loading)
        }
    }

    override fun getItemCount(): Int = listaResult.size

    companion object {

        private val loading = object : ViewType {
            override fun getViewType(): Int {
                return Constant.ViewTypesIds.LOADING
            }
        }
    }
}





@Keep
interface ViewType {
    fun getViewType(): Int
}

interface ViewTypeDelegateAdapter {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder

    fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?)
}



class LoadingDelegateAdapter : ViewTypeDelegateAdapter {

    override fun onCreateViewHolder(parent: ViewGroup) = LoadingViewHolder(parent)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?) {
    }

    class LoadingViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.new_item_loading, parent, false))
}


class ListasDelegateAdapter : ViewTypeDelegateAdapter {

	override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
		ListViewHolder(parent)

	override fun onBindViewHolder(
		holder: RecyclerView.ViewHolder,
		item: ViewType?,
		context: Context?
	) {
		(holder as ListViewHolder).bind(item as ListaItemFilme)
	}

	inner class ListViewHolder(parent: ViewGroup) :
		RecyclerView.ViewHolder(
			LayoutInflater.from(parent.context).inflate(R.layout.lista, parent, false)
		) {

		fun bind(item: ListaItemFilme) = with(itemView) {

			img_lista.setPicassoWithCache(item.posterPath, 3)
			when (item.mediaType) {
				"tv" -> date_oscar.text =
					if (!item.first_air_date.isNullOrEmpty() && item.first_air_date.length > 3)
						item.first_air_date.subSequence(0, 4) else "-"
				"movie" -> date_oscar.text =
					if (!item.releaseDate.isNullOrEmpty() && item.releaseDate.length > 3)
						item.releaseDate.subSequence(0, 4) else "-"
			}

			progress.visibility = View.GONE
			itemView.setOnClickListener {
				when (item.mediaType) {
					"tv" -> {
						val intent = Intent(context, TvShowActivity::class.java).apply {
							putExtra(Constant.TVSHOW_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
					"movie" -> {
						val intent = Intent(context, MovieDetailsActivity::class.java).apply {
							putExtra(Constant.FILME_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
				}
			}
		}
	}
}

  
package utils

import android.animation.Animator
import android.animation.Animator.*
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.util.Log
import android.view.View
import android.view.ViewGroup.*
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.marginTop
import androidx.fragment.app.FragmentActivity
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import applicaton.BaseViewModel.*
import applicaton.BaseViewModel.BaseRequest.*
import br.com.icaro.filme.R
import com.github.clans.fab.FloatingActionMenu
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.gson.Gson
import com.squareup.picasso.Callback
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import domain.reelgood.movie.Availability
import domain.tvshow.Tvshow
import error.BottomSheetError
import error.CallBackError
import java.text.DateFormat
import java.text.Normalizer
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Created by icaro on 03/09/17.
 */
/**
 * IMAGEVIEW
 */
fun ImageView.setPicasso(
	stillPath: String?,
	patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE)
		.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCache(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCacheAndHolder(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
	holder: Int,
): ImageView {
	Picasso.get()
		.load(UtilsApp.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath)
		.placeholder(holder)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.loadPallet(): Int? {
	val color = (drawable as? BitmapDrawable)?.run {
		Palette.Builder(this.bitmap).generate().swatches.first().rgb
	}
	return color ?: 0
}

fun loadPalette(view: ImageView): Int { // Todo Usar ext
	val imageView = view as ImageView
	val drawable = imageView.drawable as? BitmapDrawable
	if (drawable != null) {
		return Palette.Builder(drawable.bitmap).generate().swatches.last().rgb
	}
	return 0
}

/**
 * ACTIVITY
 */
fun Activity.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Activity.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * Context
 */
fun Context.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * VIEW
 */
fun View.gone() {
	this.visibility = View.GONE
}

fun View.visible() {
	this.visibility = View.VISIBLE
}

fun View.invisible() {
	this.visibility = View.INVISIBLE
}

fun View.animeRotation(
	end: () -> Unit = {},
	cancel: () -> Unit = {},
	start: () -> Unit = {},
	repeat: () -> Unit = {},
) {
	ObjectAnimator
		.ofPropertyValuesHolder(
			this,
			PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f)
		)
		.apply {
			duration = 790
			addListener(object : AnimatorListener {
				override fun onAnimationRepeat(animation: Animator?) {
					repeat()
				}

				override fun onAnimationEnd(animation: Animator?) {
					end()
				}

				override fun onAnimationCancel(animation: Animator?) {
					cancel()
				}

				override fun onAnimationStart(animation: Animator?) {
					start()
				}
			})
		}.start()
}

/**
 * Any
 */
fun Any.putString(cxt: Context): String = when (this) {
	is String -> this
	is Int -> cxt.getString(this)
	else -> {
		require(false) { "Need R.string.id or string" }
		""
	}
}

/**
 * STRING
 */
fun String.removerAcentos(): String {
	this.replace(".", "")
	this.replace(":", "")
	this.replace("/", "")
	this.replace(";", "")
	return Normalizer.normalize(this, Normalizer.Form.NFD).replace("[^\\p{ASCII}]".toRegex(), "")
}

fun String.parseDate(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun String.parseDateShot(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun verifyLaunch(air_date: Date?): Boolean {
	if (air_date == null) return false
	val now = Calendar.getInstance().time
	return if (air_date.before(now)) {
		true
	} else !air_date.after(now)
}

fun String.getDate(format: String = "yyyy-MM-dd"): Date? {
	return try {
		let {
			val sdf = SimpleDateFormat(format, Locale.getDefault())
			sdf.parse(it)
		}
	} catch (e: ParseException) {
		e.printStackTrace()
		null
	}
}

fun String.released(): Boolean {
	val data = getDate()
	return verifyLaunch(data)
}

@Throws(Exception::class)
fun String.yearDate(): String {
	return if (this.length >= 4) this.substring(0, 4) else ""
}

fun String.periodLaunch(): Boolean {
	val oneWeekBack = Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -7) }.time
	return getDate() != null && getDate()!!.after(oneWeekBack) //valida data
}

fun String.getNameTypeReel(): String {
	return replace(":", "-")
		.replace(" ", "-")
		.replace("&", "and")
		.replace(".", "")
		.replace("é", "e")
		.replace("ẽ", "e")
		.replace("è", "e")
		.replace("ë", "e")
		.replace("ç", "c")
		.replace("â", "a")
		.replace("ã", "a")
		.replace("á", "a")
		.replace("à", "a")
		.replace("ä", "a")
		.replace("ä", "a")
		.replace("'", "")
		.replace("\"", "")
		.replace("´", "")
		.replace("~", "")
		.replace("^", "")
		.replace("---", "-")
		.replace("----", "-")
		.replace("--", "-")
		.toLowerCase()
}

fun String?.notNullOrEmpty() = !this.isNullOrEmpty()
fun <T> Gson.fromJsonWithLog(json: String?, classOfT: Class<T>): T {
	return this.fromJson<T>(json, classOfT).apply {
		this.toString().log(classOfT.name)
	}
}

fun String.log(tag: String = "") = Log.i(tag, this)

fun Tvshow.createIdReal() = createIdReal(this.originalName ?: "", this.firstAirDate ?: "")
private fun createIdReal(originalName: String, data: String) =
	"${originalName.getNameTypeReel()}-${data.yearDate()}"

/**
 * RECYCLER
 */
fun RecyclerView.setScrollInvisibleFloatMenu(floatButton: FloatingActionMenu) {
	addOnScrollListener(object : RecyclerView.OnScrollListener() {
		override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
			when (newState) {
				RecyclerView.SCROLL_STATE_IDLE -> floatButton.visible()
				RecyclerView.SCROLL_STATE_DRAGGING -> floatButton.invisible()
				RecyclerView.SCROLL_STATE_SETTLING -> floatButton.invisible()
			}
		}
	})
}

@SuppressLint("WrongConstant")
fun RecyclerView.patternRecyler(horizont: Boolean = true): RecyclerView {
	val typeOrient = if (horizont) LinearLayoutManager.HORIZONTAL else LinearLayoutManager.VERTICAL
	layoutManager = LinearLayoutManager(context, typeOrient, false)
	itemAnimator = DefaultItemAnimator()
	setHasFixedSize(true)
	return this
}

fun RecyclerView.patternRecyclerGrid(quant: Int = 2): RecyclerView {
	layoutManager = GridLayoutManager(context, quant)
	setHasFixedSize(true)
	itemAnimator = DefaultItemAnimator()
	return this
}

fun RecyclerView.minHeight(): RecyclerView {
	layoutParams.height = 1
	importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
	isFocusable = false
	return this
}

/**
 * AVAILABILITY
 */
fun Availability.getPricePurchase(): String {
	val less = purchaseCostSd?.let { purchaseCostHd?.coerceAtMost(it) }
	val biggest = purchaseCostSd?.let { purchaseCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

fun Availability.getPriceRental(): String {
	val less = rentalCostSd?.let { rentalCostHd?.coerceAtMost(it) }
	val biggest = rentalCostSd?.let { rentalCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

/**
 * BottomSheetBehavior
 */
fun BottomSheetBehavior<View>.setAnimation(container: View, viewHeight: View) {
	ValueAnimator.ofInt(container.measuredHeight, viewHeight.marginTop).apply {
		addUpdateListener {
			peekHeight = it.animatedValue as Int
		}
		duration = 500
	}.start()

	container.post {
		val newLayoutParams = (container.layoutParams as? MarginLayoutParams)
		newLayoutParams?.setMargins(0, 0, 0, viewHeight.marginTop + 1)
		container.layoutParams = newLayoutParams
	}
}

/**
 * MutableList
 */
fun <T> MutableList<T>.replaceItemList(item: T, predicate: (T) -> Boolean): MutableList<T> {
	return this.map {
		if (predicate(it)) item else it
	}.toMutableList()
}

fun <T> Any.listSize(item: T, size: Int): ArrayList<T> {
	return if (size <= 0) {
		arrayListOf()
	} else {
		arrayListOf<T>().apply {
			for (i in 0 until size) {
				add(item)
			}
		}
	}
}

/**
 * BaseRequest
 */
fun <T> BaseRequest<T>.success() = (this as Success<T>).result
fun <T> BaseRequest<T>.resolver(
	activity: FragmentActivity,
	successBlock: (data: T) -> Unit,
	failureBlock: (error: Exception) -> Unit = {},
	loadingBlock: (loading: Boolean) -> Unit = {},
	genericError: CallBackError? = null,
) {
	when (this) {
		is Success -> successBlock(result)
		is Loading -> loadingBlock(loading)
		is Failure -> {
			error.toString().log()
			if (genericError != null) {
				BottomSheetError().newInstance(callBackError = genericError)
					.show(activity.supportFragmentManager, "")
			} else {
				failureBlock(error)
			}
		}
	}
}


star

Wed Sep 18 2024 09:51:26 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Sep 18 2024 09:47:49 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Sep 11 2024 10:04:39 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Sep 11 2024 10:03:42 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Aug 28 2024 10:01:33 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Aug 24 2024 05:57:25 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Aug 21 2024 10:04:37 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Aug 21 2024 10:02:57 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Aug 21 2024 10:02:24 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu May 30 2024 10:10:51 GMT+0000 (Coordinated Universal Time) https://developers.google.com/ad-manager/mobile-ads-sdk/android/browser/webview

#kotlin
star

Thu May 30 2024 10:10:46 GMT+0000 (Coordinated Universal Time) https://developers.google.com/ad-manager/mobile-ads-sdk/android/browser/webview

#kotlin
star

Thu May 30 2024 10:09:57 GMT+0000 (Coordinated Universal Time) https://developers.google.com/ad-manager/mobile-ads-sdk/android/browser/webview

#kotlin
star

Thu May 30 2024 10:09:08 GMT+0000 (Coordinated Universal Time) https://developers.google.com/ad-manager/mobile-ads-sdk/android/browser/webview

#kotlin
star

Thu May 30 2024 10:08:32 GMT+0000 (Coordinated Universal Time) https://developers.google.com/ad-manager/mobile-ads-sdk/android/browser/webview

#kotlin
star

Sun Feb 25 2024 20:31:26 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Feb 25 2024 20:31:12 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Feb 25 2024 20:30:52 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Feb 25 2024 20:30:31 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Dec 18 2023 06:33:06 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/

#swift #javascript #kotlin #mysql
star

Wed Sep 06 2023 06:33:22 GMT+0000 (Coordinated Universal Time) https://snipsave.com/user/iliyafda/snippet/KuvAIDcTtaKEwg9i5A/

#kotlin #android
star

Thu May 18 2023 04:37:03 GMT+0000 (Coordinated Universal Time) https://developer.android.com/google/play/billing/integrate?hl

#kotlin
star

Wed May 17 2023 03:22:09 GMT+0000 (Coordinated Universal Time)

#gradle #kotlin
star

Wed May 17 2023 03:10:58 GMT+0000 (Coordinated Universal Time)

#gradle #kotlin
star

Wed May 17 2023 03:10:58 GMT+0000 (Coordinated Universal Time)

#gradle #kotlin
star

Wed May 03 2023 02:33:53 GMT+0000 (Coordinated Universal Time)

#kotlin #mongodb #graphql
star

Wed May 03 2023 02:30:29 GMT+0000 (Coordinated Universal Time)

#kotlin #mongodb
star

Wed May 03 2023 02:26:59 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Feb 05 2023 14:28:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44493908/setting-text-in-edittext-kotlin

#kotlin #string #editable #extention
star

Tue Jan 10 2023 04:02:50 GMT+0000 (Coordinated Universal Time) https://developer.android.com/jetpack/getting-started?bookmark

#kotlin
star

Fri Dec 16 2022 07:46:15 GMT+0000 (Coordinated Universal Time) https://developer.android.com/develop/ui/views/launch/shortcuts/creating-shortcuts?authuser

#kotlin
star

Tue Dec 13 2022 12:31:46 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 25 2022 11:51:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 25 2022 09:31:37 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 23 2022 09:29:26 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Nov 10 2022 19:24:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/51141970/check-internet-connectivity-android-in-kotlin

#kotlin #android
star

Thu Nov 10 2022 10:42:53 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Nov 10 2022 09:46:39 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 09 2022 10:26:31 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Oct 28 2022 06:50:03 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Sep 24 2022 01:49:44 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Sep 23 2022 22:45:07 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Jul 31 2022 13:42:32 GMT+0000 (Coordinated Universal Time)

#mvvm #kotlin
star

Sat Jul 30 2022 07:39:53 GMT+0000 (Coordinated Universal Time)

#mvvm #kotlin
star

Thu Jul 21 2022 07:33:38 GMT+0000 (Coordinated Universal Time)

#kotlin #android
star

Thu Jun 30 2022 10:31:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Jun 08 2022 03:45:21 GMT+0000 (Coordinated Universal Time)

#kotlin #java
star

Tue Jun 07 2022 18:40:48 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jun 07 2022 18:39:15 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jun 07 2022 18:36:51 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu May 19 2022 09:30:49 GMT+0000 (Coordinated Universal Time) https://www.mo4tech.com/using-livedata-in-snackbar-navigation-and-other-events.html

#kotlin
star

Wed Apr 20 2022 09:11:44 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:11:19 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:10:49 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:10:14 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:09:46 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:09:13 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:08:40 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:08:11 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 09:07:36 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Apr 20 2022 08:54:41 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 10:40:22 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 05:21:40 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 04:48:01 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 04:00:18 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 03:35:50 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 03:15:27 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Apr 15 2022 01:27:39 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Apr 14 2022 19:24:24 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Apr 14 2022 19:20:06 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Apr 14 2022 19:17:24 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Apr 14 2022 19:12:38 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Apr 14 2022 18:49:20 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Mar 30 2022 05:06:07 GMT+0000 (Coordinated Universal Time)

#android #kotlin
star

Wed Mar 30 2022 05:05:19 GMT+0000 (Coordinated Universal Time)

#android #kotlin
star

Wed Mar 30 2022 03:55:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/33968879/onsaveinstancestate-is-not-called-on-orientation-change-before-ondestroy-to-sa

#android #kotlin
star

Wed Jan 26 2022 11:55:22 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Jan 26 2022 11:30:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jan 11 2022 15:17:51 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jan 11 2022 15:17:01 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jan 11 2022 15:16:16 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Jan 11 2022 15:14:38 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Dec 13 2021 08:42:45 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Dec 13 2021 08:42:05 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Dec 13 2021 08:37:24 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Dec 13 2021 08:34:31 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Nov 22 2021 09:56:39 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 13 2021 17:01:28 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 13 2021 17:00:42 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 13 2021 17:00:03 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 13 2021 16:59:37 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 13 2021 16:53:44 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:39:40 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:39:02 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:38:20 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:30:54 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:25:28 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:24:47 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:18:37 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:17:53 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Nov 02 2021 12:11:17 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 10:36:56 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 05:46:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 05:45:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 05:44:24 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 05:43:36 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 04 2021 05:41:58 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 20 2021 09:32:42 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 20 2021 09:32:08 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 20 2021 09:31:33 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 20 2021 09:31:04 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:37:45 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:37:00 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:36:19 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:33:32 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:32:55 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:24:13 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:23:33 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:08:22 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 06:07:19 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 05:57:00 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 05:56:06 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Sep 06 2021 05:55:17 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Aug 16 2021 07:53:09 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Aug 16 2021 07:49:39 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Aug 16 2021 07:48:48 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Aug 16 2021 07:44:42 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Jul 12 2021 18:39:02 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Jun 21 2021 18:47:28 GMT+0000 (Coordinated Universal Time) https://github.com/waliasanchit007/FirstJetpackCompose

#by #kotlin #jetpackcompose
star

Thu Jun 17 2021 13:30:51 GMT+0000 (Coordinated Universal Time) https://blog.kotlin-academy.com/enum-vs-sealed-class-which-one-to-choose-dc92ce7a4df5

#kotlin #extensionfunction #enum
star

Tue May 11 2021 16:05:39 GMT+0000 (Coordinated Universal Time)

#kotlin #android
star

Tue May 11 2021 16:02:40 GMT+0000 (Coordinated Universal Time)

#kotlin #android
star

Tue May 11 2021 15:57:13 GMT+0000 (Coordinated Universal Time)

#kotlin #android
star

Thu Apr 22 2021 13:25:56 GMT+0000 (Coordinated Universal Time) https://medium.com/swlh/kotlin-tips-tricks-you-must-know-in-2021-172700af193a

#kotlin
star

Tue Mar 23 2021 07:48:35 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Feb 26 2021 04:53:44 GMT+0000 (Coordinated Universal Time) https://developer.android.com/codelabs/kotlin-android-training-coroutines-and-room

#kotlin #android
star

Wed Feb 03 2021 13:29:33 GMT+0000 (Coordinated Universal Time)

#kotlin #android
star

Mon Jan 18 2021 05:24:39 GMT+0000 (Coordinated Universal Time)

#kotlin #springframework
star

Wed Dec 16 2020 21:46:45 GMT+0000 (Coordinated Universal Time) http://javaway.info/also-let-apply-with-run-shpargalka-po-funktsiyam-kotlin/

#kotlin
star

Sat Nov 21 2020 21:03:31 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sat Nov 21 2020 20:59:49 GMT+0000 (Coordinated Universal Time)

#kotlin

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension