Snippets Collections
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

Fri Sep 23 2022 22:45:07 GMT+0000 (UTC)

#kotlin
star

Sun Jul 31 2022 13:42:32 GMT+0000 (UTC)

#mvvm #kotlin
star

Sat Jul 30 2022 07:39:53 GMT+0000 (UTC)

#mvvm #kotlin
star

Thu Jul 21 2022 07:33:38 GMT+0000 (UTC)

#kotlin #android
star

Thu Jun 30 2022 10:31:08 GMT+0000 (UTC)

#kotlin
star

Wed Jun 08 2022 03:45:21 GMT+0000 (UTC)

#kotlin #java
star

Tue Jun 07 2022 18:40:48 GMT+0000 (UTC)

#kotlin
star

Tue Jun 07 2022 18:39:15 GMT+0000 (UTC)

#kotlin
star

Tue Jun 07 2022 18:36:51 GMT+0000 (UTC)

#kotlin
star

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

#kotlin
star

Wed Apr 20 2022 09:11:44 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:11:19 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:10:49 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:10:14 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:09:46 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:09:13 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:08:40 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 09:08:11 GMT+0000 (UTC)

#kotlin
star

Wed Apr 20 2022 08:54:41 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 10:40:22 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 05:21:40 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 04:48:01 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 04:00:18 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 03:35:50 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 03:15:27 GMT+0000 (UTC)

#kotlin
star

Fri Apr 15 2022 01:27:39 GMT+0000 (UTC)

#kotlin
star

Thu Apr 14 2022 19:24:24 GMT+0000 (UTC)

#kotlin
star

Thu Apr 14 2022 19:20:06 GMT+0000 (UTC)

#kotlin
star

Thu Apr 14 2022 19:17:24 GMT+0000 (UTC)

#kotlin
star

Thu Apr 14 2022 19:12:38 GMT+0000 (UTC)

#kotlin
star

Thu Apr 14 2022 18:49:20 GMT+0000 (UTC)

#kotlin
star

Wed Mar 30 2022 05:06:07 GMT+0000 (UTC)

#android #kotlin
star

Wed Mar 30 2022 05:05:19 GMT+0000 (UTC)

#android #kotlin
star

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

#android #kotlin
star

Wed Jan 26 2022 11:30:08 GMT+0000 (UTC)

#kotlin
star

Tue Jan 11 2022 15:17:01 GMT+0000 (UTC)

#kotlin
star

Tue Jan 11 2022 15:16:16 GMT+0000 (UTC)

#kotlin
star

Tue Jan 11 2022 15:14:38 GMT+0000 (UTC)

#kotlin
star

Mon Dec 13 2021 08:42:05 GMT+0000 (UTC)

#kotlin
star

Mon Dec 13 2021 08:37:24 GMT+0000 (UTC)

#kotlin
star

Mon Dec 13 2021 08:34:31 GMT+0000 (UTC)

#kotlin
star

Mon Nov 22 2021 09:56:39 GMT+0000 (UTC)

#kotlin
star

Sat Nov 13 2021 17:01:28 GMT+0000 (UTC)

#kotlin
star

Sat Nov 13 2021 17:00:42 GMT+0000 (UTC)

#kotlin
star

Sat Nov 13 2021 17:00:03 GMT+0000 (UTC)

#kotlin
star

Sat Nov 13 2021 16:59:37 GMT+0000 (UTC)

#kotlin
star

Sat Nov 13 2021 16:53:44 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:39:40 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:39:02 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:38:20 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:30:54 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:25:28 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:24:47 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:18:37 GMT+0000 (UTC)

#kotlin
star

Tue Nov 02 2021 12:17:53 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 10:36:56 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:45:08 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:44:24 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:43:36 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:41:58 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:32:42 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:32:08 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:31:33 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:31:04 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:37:45 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:37:00 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:36:19 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:33:32 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:32:55 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:24:13 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:23:33 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:08:22 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:07:19 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:57:00 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:56:06 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:55:17 GMT+0000 (UTC)

#kotlin
star

Mon Aug 16 2021 07:44:42 GMT+0000 (UTC)

#kotlin
star

Mon Jul 12 2021 18:39:02 GMT+0000 (UTC)

#kotlin
star

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

#by #kotlin #jetpackcompose
star

Thu Jun 17 2021 13:30:51 GMT+0000 (UTC) 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 (UTC)

#kotlin #android
star

Tue May 11 2021 16:02:40 GMT+0000 (UTC)

#kotlin #android
star

Tue May 11 2021 15:57:13 GMT+0000 (UTC)

#kotlin #android
star

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

#kotlin
star

Tue Mar 23 2021 07:48:35 GMT+0000 (UTC)

#kotlin
star

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

#kotlin #android
star

Wed Feb 03 2021 13:29:33 GMT+0000 (UTC)

#kotlin #android
star

Mon Jan 18 2021 05:24:39 GMT+0000 (UTC)

#kotlin #springframework
star

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

#kotlin
star

Sat Nov 21 2020 21:03:31 GMT+0000 (UTC)

#kotlin
star

Sat Nov 21 2020 20:59:49 GMT+0000 (UTC)

#kotlin

Save snippets that work with our extensions

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