Snippets Collections
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;

public class XMLValidation {
    public static void main(String[] args) {
        try {
            // Prompt user for XML file name
            System.out.println("Enter the XML file name:");
            String filename = new BufferedReader(new InputStreamReader(System.in)).readLine();
            File file = new File(filename);

            // Check if the file exists
            if (file.exists()) {
                validateXML(file);
            } else {
                System.out.println("File not found.");
            }
        } catch (IOException e) {
            System.out.println("Error reading input: " + e.getMessage());
        }
    }

    private static void validateXML(File file) {
        try {
            // Initialize the SAX parser
            SAXParserFactory.newInstance().newSAXParser().parse(file, new DefaultHandler());
            System.out.println(file.getName() + " is valid XML.");
        } catch (Exception e) {
            System.out.println(file.getName() + " is not valid XML.");
        }
    }
}


hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Java Programming</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>XML Development</title>
        <author>Jane Smith</author>
    </book>
</library>
Logics:
1)Tip Calculator
super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
 
        binding.button.setOnClickListener() {
            calculateTip()
        }
    }
    fun calculateTip()
    {
        val cost =(binding.cost.text.toString()).toDouble()
        val selected =binding.RG.checkedRadioButtonId
        val tipPercent=when(selected)
        {
            R.id.radioButton ->15
            R.id.radioButton2 ->18
            else -> 20
        }
        var tip=tipPercent*cost
        if(binding.switch2.isChecked)
        {
            tip= ceil(tip)
        }
        binding.textView7.text=tip.toString()
    }
}
2)Toast message
val button:Button=findViewById(R.id.button)
        button.setOnClickListener{
            Toast.makeText(this,"Clicked",Toast.LENGTH_LONG).show()
        }
3)dice roller
val button: Button=findViewById(R.id.button)
        button.setOnClickListener{
            rollDice()
        }
    }
    private fun rollDice(){
        val dice=Dice(6)
        val diceRoll=dice.roll()
        val img :ImageView=findViewById(R.id.imageView)
        val drawableResource = when(diceRoll){
            1->R.drawable.dice1
            2->R.drawable.dice2
            3->R.drawable.dice3
            4->R.drawable.dice4
            5->R.drawable.dice5
            else->R.drawable.dice5
        }
        img.setImageResource(drawableResource)
    }
}
class Dice(private val numsides:Int){
    fun roll():Int{
        return (1..numsides).random()
    }
}
4)explicit intent
//Explicit Intent
        var t: TextView = findViewById(R.id.textView)
        var f: FloatingActionButton = findViewById(R.id.floatingActionButton)
        f.setOnClickListener()
        {
            var i = Intent(this, MainActivity2::class.java)
            startActivity(i)
        }
    }
}
5)activity lifecycle
@SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }
}
6)copy and paste
setContentView(R.layout.activity_main)
        val button:Button=findViewById(R.id.button)
        val et:EditText=findViewById(R.id.editTextText)
        val tv:TextView=findViewById(R.id.textView)
 
        button.setOnClickListener{
            tv.text=et.text.toString()
            Toast.makeText(this,"Text Copied",Toast.LENGTH_LONG).show()
        }
    }
}
7)hello world
<TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        android:textAllCaps="true"
        android:textColor="#289428"
        android:text="MAD LAB"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
8)implicit intent
//implicit
        val url = "https://www.google.com"
        val implicitButton : FloatingActionButton = findViewById(R.id.floatingActionButton)
        implicitButton.setOnClickListener{
            val implicitIntent =Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(implicitIntent)
        }
    }
}
9)login module
setContentView(R.layout.activity_main)
 
        userET = findViewById(R.id.editTextText3)
        passET = findViewById(R.id.editTextText4)
        loginBtn =findViewById(R.id.button3)
        loginBtn.setOnClickListener {
 
            if(userET.text.toString()=="cvr" && passET.text.toString()=="cvr123")
            {
                val intent= Intent(this,MainActivity2::class.java)
                intent.putExtra("Username",userET.text.toString())
                intent.putExtra("Password",passET.text.toString())
                startActivity(intent)
                Toast.makeText(this,"login success",Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(this,"error login ",Toast.LENGTH_LONG).show()
            }
        }
 
 
 
    }
}
ActivityMain.kt: 
package com.example.quizapp 
 
import androidx.appcompat.app.AppCompatActivity 
import android.os.Bundle 
 
class MainActivity : AppCompatActivity() { 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContentView(R.layout.activity_main) 
 
    } 
    companion object{ 
        var count:Int=0 
    } 
} 
main_activity: 
<?xml version="1.0" encoding="utf-8"?> 
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity"> 
 
    <androidx.fragment.app.FragmentContainerView 
        android:id="@+id/fragmentContainerView" 
        android:name="androidx.navigation.fragment.NavHostFragment" 
        android:layout_width="409dp" 
        android:layout_height="729dp" 
        app:defaultNavHost="true" 
        app:layout_constraintBottom_toBottomOf="parent" 
        app:layout_constraintEnd_toEndOf="parent" 
        app:layout_constraintStart_toStartOf="parent" 
        app:layout_constraintTop_toTopOf="parent" 
        app:navGraph="@navigation/navgraph" /> 
</androidx.constraintlayout.widget.ConstraintLayout> 
win.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import android.widget.TextView 
import androidx.navigation.Navigation 
 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
class win : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
        var view:View=inflater.inflate(R.layout.fragment_win, container, false) 
        var tv:TextView=view.findViewById(R.id.textView) 
        var btn:Button=view.findViewById(R.id.next) 
        if(MainActivity.count==4) 
            tv.text="Congratulations you won the quiz \n score : "+MainActivity.count 
        else 
            tv.text="" 
        btn.setOnClickListener{ 
            tv.text="" 
            MainActivity.count=0 
            Navigation.findNavController(view).navigate(R.id.action_win2_to_quest1) 
        } 
        return view 
    } 
 
    companion object { 
                @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            win().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_win.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".win"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Start quiz" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.314" /> 
 
        <TextView 
            android:id="@+id/textView" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.593" /> 
 
    </androidx.constraintlayout.widget.ConstraintLayout> 
 
</FrameLayout> 
lose.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import androidx.navigation.Navigation 
 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
class lose : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
 
        var view:View= inflater.inflate(R.layout.fragment_lose, container, false) 
        var btn:Button=view.findViewById(R.id.next) 
        btn.setOnClickListener { 
            Navigation.findNavController(view).navigate(R.id.action_lose_to_win2) 
 
        } 
        return view 
    } 
 
    companion object { 
        @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            lose().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_lose.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".lose"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Try again" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/textView" 
            app:layout_constraintVertical_bias="0.5" /> 
 
        <TextView 
            android:id="@+id/textView" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Sorry you lost the quiz" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.357" /> 
 
    </androidx.constraintlayout.widget.ConstraintLayout> 
</FrameLayout> 
quest1.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import android.provider.MediaStore.Audio.Radio 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import android.widget.RadioGroup 
import androidx.lifecycle.findViewTreeViewModelStoreOwner 
import androidx.navigation.Navigation 
 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
class quest1 : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
        var view:View= inflater.inflate(R.layout.fragment_quest1, container, false) 
        var btn:Button=view.findViewById(R.id.next) 
        var rg:RadioGroup=view.findViewById(R.id.radioGroup) 
        btn.setOnClickListener{ 
            if(rg.checkedRadioButtonId==R.id.radio1) 
                MainActivity.count++ 
            Navigation.findNavController(view).navigate(R.id.action_quest1_to_quest2) 
        } 
        return view 
    } 
 
    companion object { 
        @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            quest1().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_quest1.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".quest1"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
        <TextView 
            android:id="@+id/textView" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="welcome to quiz" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.059" /> 
 
        <TextView 
            android:id="@+id/quest" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Quest1 : who is chiranjeevi" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.18" /> 
 
        <RadioGroup 
            android:id="@+id/radioGroup" 
            android:layout_width="180dp" 
            android:layout_height="wrap_content" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.168" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/quest" 
            app:layout_constraintVertical_bias="0.114"> 
 
            <RadioButton 
                android:id="@+id/radio1" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="actor" /> 
 
            <RadioButton 
                android:id="@+id/radio2" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="cricketer" /> 
 
            <RadioButton 
                android:id="@+id/radio3" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="comedian" /> 
 
            <RadioButton 
                android:id="@+id/radio4" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="Prime minister" 
                app:layout_constraintBottom_toBottomOf="parent" 
                app:layout_constraintTop_toTopOf="parent" /> 
        </RadioGroup> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="next" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/radioGroup" 
            app:layout_constraintVertical_bias="0.361" /> 
    </androidx.constraintlayout.widget.ConstraintLayout> 
</FrameLayout> 
quest2.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import android.widget.RadioGroup 
import androidx.navigation.Navigation 
 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
/** 
 * A simple [Fragment] subclass. 
 * Use the [quest2.newInstance] factory method to 
 * create an instance of this fragment. 
 */ 
class quest2 : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
        // Inflate the layout for this fragment 
        var view:View=inflater.inflate(R.layout.fragment_quest2, container, false) 
        var btn: Button =view.findViewById(R.id.next) 
        var rg: RadioGroup =view.findViewById(R.id.radioGroup) 
        btn.setOnClickListener{ 
            if(rg.checkedRadioButtonId==R.id.radio2) 
                MainActivity.count++ 
            Navigation.findNavController(view).navigate(R.id.action_quest2_to_quest3) 
        } 
        return view 
    } 
 
    companion object { 
        /** 
         * Use this factory method to create a new instance of 
         * this fragment using the provided parameters. 
         * 
         * @param param1 Parameter 1. 
         * @param param2 Parameter 2. 
         * @return A new instance of fragment quest2. 
         */ 
        // TODO: Rename and change types and number of parameters 
        @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            quest2().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_quest2.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".quest2"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
        <TextView 
            android:id="@+id/quest" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Quest2 : who is virat Kohli" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.18" /> 
 
        <RadioGroup 
            android:id="@+id/radioGroup" 
            android:layout_width="180dp" 
            android:layout_height="wrap_content" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.168" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/quest" 
            app:layout_constraintVertical_bias="0.114"> 
 
            <RadioButton 
                android:id="@+id/radio1" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="actor" /> 
 
            <RadioButton 
                android:id="@+id/radio2" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="cricketer" /> 
 
            <RadioButton 
                android:id="@+id/radio3" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="comedian" /> 
 
            <RadioButton 
                android:id="@+id/radio4" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="Prime minister" 
                app:layout_constraintBottom_toBottomOf="parent" 
                app:layout_constraintTop_toTopOf="parent" /> 
        </RadioGroup> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="next" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/radioGroup" 
            app:layout_constraintVertical_bias="0.361" /> 
    </androidx.constraintlayout.widget.ConstraintLayout> 
 
</FrameLayout> 
 
quest3.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import android.widget.RadioGroup 
import androidx.navigation.Navigation 
 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
/** 
 * A simple [Fragment] subclass. 
 * Use the [quest3.newInstance] factory method to 
 * create an instance of this fragment. 
 */ 
class quest3 : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
        // Inflate the layout for this fragment 
        var view:View= inflater.inflate(R.layout.fragment_quest3, container, false) 
        var btn: Button =view.findViewById(R.id.next) 
        var rg: RadioGroup =view.findViewById(R.id.radioGroup) 
        btn.setOnClickListener{ 
            if(rg.checkedRadioButtonId==R.id.radio3) 
                MainActivity.count++ 
            Navigation.findNavController(view).navigate(R.id.action_quest3_to_quest4) 
        } 
        return view 
    } 
 
    companion object { 
        /** 
         * Use this factory method to create a new instance of 
         * this fragment using the provided parameters. 
         * 
         * @param param1 Parameter 1. 
         * @param param2 Parameter 2. 
         * @return A new instance of fragment quest3. 
         */ 
        // TODO: Rename and change types and number of parameters 
        @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            quest3().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_quest3.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".quest3"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
 
        <TextView 
            android:id="@+id/quest" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Quest3 : who is bramhanandham" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.18" /> 
 
        <RadioGroup 
            android:id="@+id/radioGroup" 
            android:layout_width="180dp" 
            android:layout_height="wrap_content" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.168" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/quest" 
            app:layout_constraintVertical_bias="0.114"> 
 
            <RadioButton 
                android:id="@+id/radio1" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="actor" /> 
 
            <RadioButton 
                android:id="@+id/radio2" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="cricketer" /> 
 
            <RadioButton 
                android:id="@+id/radio3" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="comedian" /> 
 
            <RadioButton 
                android:id="@+id/radio4" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="Prime minister" 
                app:layout_constraintBottom_toBottomOf="parent" 
                app:layout_constraintTop_toTopOf="parent" /> 
        </RadioGroup> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="next" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/radioGroup" 
            app:layout_constraintVertical_bias="0.361" /> 
    </androidx.constraintlayout.widget.ConstraintLayout> 
 
</FrameLayout> 
quest4.kt: 
package com.example.quizapp 
 
import android.os.Bundle 
import androidx.fragment.app.Fragment 
import android.view.LayoutInflater 
import android.view.View 
import android.view.ViewGroup 
import android.widget.Button 
import android.widget.RadioGroup 
import androidx.navigation.Navigation 
 
// TODO: Rename parameter arguments, choose names that match 
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
private const val ARG_PARAM1 = "param1" 
private const val ARG_PARAM2 = "param2" 
 
/** 
 * A simple [Fragment] subclass. 
 * Use the [quest4.newInstance] factory method to 
 * create an instance of this fragment. 
 */ 
class quest4 : Fragment() { 
    // TODO: Rename and change types of parameters 
    private var param1: String? = null 
    private var param2: String? = null 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        arguments?.let { 
            param1 = it.getString(ARG_PARAM1) 
            param2 = it.getString(ARG_PARAM2) 
        } 
    } 
 
    override fun onCreateView( 
        inflater: LayoutInflater, container: ViewGroup?, 
        savedInstanceState: Bundle? 
    ): View? { 
        // Inflate the layout for this fragment 
        var view:View= inflater.inflate(R.layout.fragment_quest4, container, false) 
        var btn: Button =view.findViewById(R.id.next) 
        var rg: RadioGroup =view.findViewById(R.id.radioGroup) 
        btn.setOnClickListener{ 
            if(rg.checkedRadioButtonId==R.id.radio4) 
                MainActivity.count++ 
            if(MainActivity.count==4) 
                Navigation.findNavController(view).navigate(R.id.action_quest4_to_win2) 
            else 
                Navigation.findNavController(view).navigate(R.id.action_quest4_to_lose) 
        } 
        return view 
    } 
 
    companion object { 
        /** 
         * Use this factory method to create a new instance of 
         * this fragment using the provided parameters. 
         * 
         * @param param1 Parameter 1. 
         * @param param2 Parameter 2. 
         * @return A new instance of fragment quest4. 
         */ 
        // TODO: Rename and change types and number of parameters 
        @JvmStatic 
        fun newInstance(param1: String, param2: String) = 
            quest4().apply { 
                arguments = Bundle().apply { 
                    putString(ARG_PARAM1, param1) 
                    putString(ARG_PARAM2, param2) 
                } 
            } 
    } 
} 
fragment_quest4.xml: 
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 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=".quest4"> 
 
    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 
 
 
        <TextView 
            android:id="@+id/quest" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Quest4 : who is narendra modi" 
            android:textColor="#000000" 
            android:textSize="28dp" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toTopOf="parent" 
            app:layout_constraintVertical_bias="0.18" /> 
 
        <RadioGroup 
            android:id="@+id/radioGroup" 
            android:layout_width="180dp" 
            android:layout_height="wrap_content" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.168" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/quest" 
            app:layout_constraintVertical_bias="0.114"> 
 
            <RadioButton 
                android:id="@+id/radio1" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="actor" /> 
 
            <RadioButton 
                android:id="@+id/radio2" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="cricketer" /> 
 
            <RadioButton 
                android:id="@+id/radio3" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="comedian" /> 
 
            <RadioButton 
                android:id="@+id/radio4" 
                android:layout_width="match_parent" 
                android:layout_height="wrap_content" 
                android:text="Prime minister" 
                app:layout_constraintBottom_toBottomOf="parent" 
                app:layout_constraintTop_toTopOf="parent" /> 
        </RadioGroup> 
 
        <Button 
            android:id="@+id/next" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="submit" 
            app:layout_constraintBottom_toBottomOf="parent" 
            app:layout_constraintEnd_toEndOf="parent" 
            app:layout_constraintHorizontal_bias="0.498" 
            app:layout_constraintStart_toStartOf="parent" 
            app:layout_constraintTop_toBottomOf="@+id/radioGroup" 
            app:layout_constraintVertical_bias="0.361" /> 
    </androidx.constraintlayout.widget.ConstraintLayout> 
 
</FrameLayout> 
Navgraph: 
fragment_win: 
fragment_lose: 
fragment_quest1: 
fragment_quest2: 
fragment_quest3: 
fragment_quest4: 
PROCEDURE TO FOLLOW IN NAVIGATION USING FRAGMENTS APP 
1) Create empty Activity 
2) Create layout folder and add “activity_main.xml” file in it 
3) How to create Navigation folder and navigation graph: 
i) 
Add dependencies in build.gradle file 
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.0
alpha08") 
implementation("androidx.navigation:navigation-fragment-ktx:2.3.5") 
implementation("androidx.navigation:navigation-ui-ktx:2.3.5") 
implementation("androidx.navigation:navigation-dynamic-features
fragment:2.3.5") 
ii) 
iii) 
Create navigation folder and add nav_graph.xml in it 
Create “new destination” in nav_graph.xml then select 2 blank fragments and 
name it as “HomeFragment” and “DataFragment” 
4) Add the following steps in activity_main.xml: 
i) 
Add constraint layout 
ii) 
Drag and drop fragment container view and select “HomeFragment.kt” 
add:navGraph=”@navigation/nav_graph” 
5) Add the following steps in HomeFragment in xml: 
i) 
Add Constraint View 
ii) 
iii) 
Add Text View 
Add Button  
6) Add the following steps in DataFragment in xml: 
i) 
Add Constraint View 
ii) 
iii) 
Add Text View 
Add Button 
MainActivity:
package com.example.myapp

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

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

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

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="409dp"
        android:layout_height="729dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:navGraph="@navigation/nav_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>
nav_graph.xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.example.myapp.homeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >
        <action
            android:id="@+id/action_homeFragment_to_dataFragment"
            app:destination="@id/dataFragment" />
    </fragment>
    <fragment
        android:id="@+id/dataFragment"
        android:name="com.example.myapp.dataFragment"
        android:label="fragment_data"
        tools:layout="@layout/fragment_data" >
        <action
            android:id="@+id/action_dataFragment_to_homeFragment"
            app:destination="@id/homeFragment" />
    </fragment>
</navigation>
HomeFragment.kt:
package com.example.myapp

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.navigation.Navigation

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [homeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class homeFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        val view:View=inflater.inflate(R.layout.fragment_home, container, false)
        val btn:Button=view.findViewById(R.id.button)
        btn.setOnClickListener {
            Navigation.findNavController(view).navigate(R.id.action_homeFragment_to_dataFragment)
        }
        return view
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment homeFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            homeFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

fragment_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".homeFragment">
    <!-- TODO: Update blank fragment layout -->
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="home fragment"
            android:textSize="24sp"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.5" />

        <Button
            android:id="@+id/button"
            android:layout_width="125dp"
            android:layout_height="69dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView"
            app:layout_constraintVertical_bias="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>

DataFragment.kt:
package com.example.myapp

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.navigation.Navigation

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [dataFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class dataFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view: View = inflater.inflate(R.layout.fragment_data, container, false)
        val btn: Button = view.findViewById(R.id.button2)
        btn.setOnClickListener() {
            Navigation.findNavController(view).navigate(R.id.action_dataFragment_to_homeFragment)
        }
        return view
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment dataFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            dataFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

fragment_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".dataFragment">

    <!-- TODO: Update blank fragment layout -->


    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="data fragment"
            android:textSize="24sp"
            app:layout_constraintBottom_toTopOf="@+id/button2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.5" />

        <Button
            android:id="@+id/button2"
            android:layout_width="124dp"
            android:layout_height="51dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView2"
            app:layout_constraintVertical_bias="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>

Builde kartle:
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)
}

android {
    namespace = "com.example.myapp"
    compileSdk = 35

    defaultConfig {
        applicationId = "com.example.myapp"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {

    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.appcompat)
    implementation(libs.material)
    implementation(libs.androidx.activity)
    implementation(libs.androidx.constraintlayout)
    implementation(libs.androidx.navigation.fragment.ktx)
    implementation(libs.androidx.navigation.ui.ktx)

    implementation("androidx.navigation:navigation-fragment-ktx:2.8.1")
    implementation("androidx.navigation:navigation-ui-ktx:2.8.1")
    implementation("androidx.navigation:navigation-dynamic-features-fragment:2.8.1")

    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
}
MainActivity.kt:
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton

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

        //implicit
        val url = "https://www.google.com"
        val implicitButton : FloatingActionButton = findViewById(R.id.floatingActionButton)
        implicitButton.setOnClickListener{
            val implicitIntent =Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(implicitIntent)
        }
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to MAD Lab"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="56dp"
        android:layout_height="76dp"
        android:clickable="true"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.5"
        app:maxImageSize="30dp"
        app:srcCompat="@drawable/baseline_add_24"
        tools:ignore="ContentDescription,KeyboardInaccessibleWidget,SpeakableTextPresentCheck,SpeakableTextPresentCheck"/>

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt:
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton

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

        //Explicit Intent
        var t: TextView = findViewById(R.id.textView)
        var f: FloatingActionButton = findViewById(R.id.floatingActionButton)
        f.setOnClickListener()
        {
            var i = Intent(this, MainActivity2::class.java)
            startActivity(i)
        }
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to MAD Lab"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="56dp"
        android:layout_height="76dp"
        android:clickable="true"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.5"
        app:maxImageSize="30dp"
        app:srcCompat="@drawable/baseline_add_24"
        tools:ignore="ContentDescription,KeyboardInaccessibleWidget,SpeakableTextPresentCheck,SpeakableTextPresentCheck"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity2.kt:
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)
    }
}
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSE-A"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity:
package com.cscorner.myapplication5

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
//Bundle is a class in android studio used to transfer data from one UI component activity to another UI component activity to another UI component activity.
import android.widget.Toast
class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
//Bundle defines 2 methods onFreeze() and onCreate() onFreeze() assigns value to UI component in design phase and onCreate() takes parameter of component during runtime
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//R is a resource set in activity_main.xml and used in kt file with resource id
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        android:textAllCaps="true"
        android:textColor="#289428"
        android:text="MAD LAB"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity:
package com.cscorner.myapplication5

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val button:Button=findViewById(R.id.button)
        val et:EditText=findViewById(R.id.editTextText)
        val tv:TextView=findViewById(R.id.textView)

        button.setOnClickListener{
            tv.text=et.text.toString()
            Toast.makeText(this,"Text Copied",Toast.LENGTH_LONG).show()
        }
    }
}
activivty_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        android:minHeight="48dp"
        android:text="Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.279" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.728" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main_Activity .kt:
package com.cscorner.myapplication5

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val button:Button=findViewById(R.id.button)
        button.setOnClickListener{
            Toast.makeText(this,"Clicked",Toast.LENGTH_LONG).show()
        }

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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt:
package com.cscorner.myapplication

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.cscorner.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    private lateinit var userET:EditText
    private lateinit var passET: EditText
    //private lateinit var resetBtn: Button
    lateinit var loginBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)


        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        userET = findViewById(R.id.editTextText3)
        passET = findViewById(R.id.editTextText4)
        loginBtn =findViewById(R.id.button3)
        loginBtn.setOnClickListener {

            if(userET.text.toString()=="cvr" && passET.text.toString()=="cvr123")
            {
                val intent= Intent(this,MainActivity2::class.java)
                intent.putExtra("Username",userET.text.toString())
                intent.putExtra("Password",passET.text.toString())
                startActivity(intent)
                Toast.makeText(this,"login success",Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(this,"error login ",Toast.LENGTH_LONG).show()
            }
        }



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

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <EditText
            android:id="@+id/editTextText3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:minHeight="48dp"
            android:text="Enter Name"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.497"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.276" />

        <EditText
            android:id="@+id/editTextText4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword"
            android:minHeight="48dp"
            android:text="Password"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.497"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.377" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dengu"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
MainActivity2.kt:
package com.cscorner.myapplication

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import android .content.Intent
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity2 : AppCompatActivity() {
    private lateinit var resultTV:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)

        resultTV=findViewById(R.id.textView)
        val intent: Intent =intent
        var user=intent.getStringExtra("Username")
        var pass=intent.getStringExtra("Password")
        resultTV.text=user+" " +pass
    }
}
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

    <TextView
        android:id="@+id/textView"
        android:layout_width="201dp"
        android:layout_height="31dp"
        android:text="Welcome"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
MainActivity:
package com.cscorner.myapplication2

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity


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


        val button: Button=findViewById(R.id.button)
        button.setOnClickListener{
            rollDice()
        }
    }
    private fun rollDice(){
        val dice=Dice(6)
        val diceRoll=dice.roll()
        val img :ImageView=findViewById(R.id.imageView)
        val drawableResource = when(diceRoll){
            1->R.drawable.dice1
            2->R.drawable.dice2
            3->R.drawable.dice3
            4->R.drawable.dice4
            5->R.drawable.dice5
            else->R.drawable.dice5
        }
        img.setImageResource(drawableResource)
    }
}
class Dice(private val numsides:Int){
    fun roll():Int{
        return (1..numsides).random()
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:srcCompat="@drawable/dice_1" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Roll"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.775" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.cscorner.myapplication3

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

  </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.cscorner.myapplication4

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.cscorner.myapplication4.databinding.ActivityMainBinding
import kotlin.math.ceil

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener() {
            calculateTip()
        }
    }
    fun calculateTip()
    {
        val cost =(binding.cost.text.toString()).toDouble()
        val selected =binding.RG.checkedRadioButtonId
        val tipPercent=when(selected)
        {
            R.id.radioButton ->15
            R.id.radioButton2 ->18
            else -> 20
        }
        var tip=tipPercent*cost
        if(binding.switch2.isChecked)
        {
            tip= ceil(tip)
        }
        binding.textView7.text=tip.toString()
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost"
        android:layout_width="241dp"
        android:layout_height="55dp"
        android:ems="10"
        android:inputType="text"
        android:text="Cost"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.119" />

    <RadioGroup
        android:id="@+id/RG"
        android:layout_width="253dp"
        android:layout_height="154dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="UnknownId">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:text="Excelent" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:text="Very Good" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="48dp"
            android:text="Bad" />

    </RadioGroup>

    <Switch
        android:id="@+id/switch2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Switch"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.672"
        tools:ignore="UnknownId,UseSwitchCompatOrMaterialXml" />

    <Button
        android:id="@+id/button"
        android:layout_width="166dp"
        android:layout_height="48dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.79"
        tools:ignore="UnknownId" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="182dp"
        android:layout_height="30dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.91"
        tools:ignore="UnknownId" />

</androidx.constraintlayout.widget.ConstraintLayout>
Build katle
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)
}

android {
    namespace = "com.cscorner.myapplication4"
    compileSdk = 35

    defaultConfig {
        applicationId = "com.cscorner.myapplication4"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures{
        viewBinding= true
    }
}

dependencies {



    implementation(libs.material)
    implementation(libs.androidx.activity)


    androidTestImplementation(libs.androidx.junit)

    implementation ("androidx.core:core-ktx:1.7.0")
    implementation ("androidx.appcompat:appcompat:1.6.1")
    implementation ("com.google.android.material:material:1.9.0")
    implementation ("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation ("junit:junit:4.13.2")
    androidTestImplementation ("androidx.test.ext:junit:1.1.5")
    androidTestImplementation ("androidx.test.espresso:espresso-core:3.5.1")
}
1.	// getter and setter properties

class CSE {
    var name: String = " "
        get() = field        // getter
        set(value) {         // setter
            field = value
        }
}
fun main(args: Array<String>) {
    val c = CSE()
    c.name = "WELCOME TO CSE-B"   // access setter
    println(c.name)               // access getter
}

Output:
WELCOME TO CSE-B
******************************************************************************************
2.   //DWELLINGS PROGRAM
 /**
* Program that implements classes for different kinds of dwellings.
* Shows how to:
* Create class hierarchy, variables and functions with inheritance,
* abstract class, overriding, and private vs. public variables.
*/

import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
   val squareCabin = SquareCabin(6, 50.0)
   val roundHut = RoundHut(3, 10.0)
   val roundTower = RoundTower(4, 15.5)

   with(squareCabin) {
       println("\nSquare Cabin\n============")
       println("Capacity: ${capacity}")
       println("Material: ${buildingMaterial}")
       println("Floor area: ${floorArea()}")
   }

   with(roundHut) {
       println("\nRound Hut\n=========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Carpet size: ${calculateMaxCarpetLength()}")
   }

   with(roundTower) {
       println("\nRound Tower\n==========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Carpet Length: ${calculateMaxCarpetLength()}")
   }
}


/**
* Defines properties common to all dwellings.
* All dwellings have floorspace,
* but its calculation is specific to the subclass.
* Checking and getting a room are implemented here
* because they are the same for all Dwelling subclasses.
*
* @param residents Current number of residents
*/
abstract class Dwelling(private var residents: Int) {
   abstract val buildingMaterial: String
   abstract val capacity: Int

   /**
    * Calculates the floor area of the dwelling.
    * Implemented by subclasses where shape is determined.
    *
    * @return floor area
    */
   abstract fun floorArea(): Double

   /**
    * Checks whether there is room for another resident.
    *
    * @return true if room available, false otherwise
    */
   fun hasRoom(): Boolean {
       return residents < capacity
   }

   /**
    * Compares the capacity to the number of residents and
    * if capacity is larger than number of residents,
    * add resident by increasing the number of residents.
    * Print the result.
    */
   fun getRoom() {
       if (capacity > residents) {
           residents++
           println("You got a room!")
       } else {
           println("Sorry, at capacity and no rooms left.")
       }
   }

   }

/**
* A square cabin dwelling.
*
*  @param residents Current number of residents
*  @param length Length
*/
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
   override val buildingMaterial = "Wood"
   override val capacity = 6

   /**
    * Calculates floor area for a square dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return length * length
   }

}

/**
* Dwelling with a circular floorspace
*
* @param residents Current number of residents
* @param radius Radius
*/
open class RoundHut(
       residents: Int, val radius: Double) : Dwelling(residents) {

   override val buildingMaterial = "Straw"
   override val capacity = 4

   /**
    * Calculates floor area for a round dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return PI * radius * radius
   }

   /**
    *  Calculates the max length for a square carpet
    *  that fits the circular floor.
    *
    * @return length of square carpet
    */
    fun calculateMaxCarpetLength(): Double {
        return sqrt(2.0) * radius
    }
}

/**
* Round tower with multiple stories.
*
* @param residents Current number of residents
* @param radius Radius
* @param floors Number of stories
*/
class RoundTower(
       residents: Int,
       radius: Double,
       val floors: Int = 2) : RoundHut(residents, radius) {

   override val buildingMaterial = "Stone"

   // Capacity depends on the number of floors.
   override val capacity = floors * 4

   /**
    * Calculates the total floor area for a tower dwelling
    * with multiple stories.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return super.floorArea() * floors
   }
}

Output:
Square Cabin
============
Capacity: 6
Material: Wood
Floor area: 2500.0

Round Hut
=========
Material: Straw
Capacity: 4
Floor area: 314.1592653589793
Has room? true
You got a room!
Has room? false
Sorry, at capacity and no rooms left.
Carpet size: 14.142135623730951

Round Tower
==========
Material: Stone
Capacity: 8
Floor area: 1509.5352700498956
Carpet Length: 21.920310216782976
******************************************************************************************
3.4.5.6.	// companion object
class CSE {
    companion object Test  {                 //companion object name Test
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }
}
fun main(args: Array<String>) {
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB
******************************************************************************************
7.	// anonymous function 

// anonymous function  with body as an expression
val anonymous1 = fun(x: Int, y: Int): Int = x + y
// anonymous function with body as a block
val anonymous2 = fun(a: Int, b: Int): Int 
{
			val mul = a * b
			return mul
}
fun main(args: Array<String>) 
{
	//invoking functions
	val sum = anonymous1(3,5)
	val mul = anonymous2(3,5)
	println("The sum of two numbers is: $sum")
	println("The multiply of two numbers is: $mul")
}

Output:
The sum of two numbers is: 8
The multiply of two numbers is: 15
******************************************************************************************
8.   //WHEN DEMONSTRATION
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}

Output:
Thursday
******************************************************************************************
9.//DICE ROLLER PROGRAM USING CLASSES
// Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
//IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. 
//IntRange is a suitable data type for representing the possible values a dice roll can produce.
class Dice {
    var sides = 6
    fun roll(): Int {
        //random() function to generate random numbers. 
        //random() takes a series of numbers as an input and it returns a random Int as an output.
        val randomNumber = (1..sides).random()  
        return randomNumber
    }
}
fun main() {
    val myFirstDice = Dice()
    val diceRoll = myFirstDice.roll()
    println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!")

    myFirstDice.sides = 20
    println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!")
}

Output:
Your 6 sided dice rolled 4!
Your 20 sided dice rolled 1!
 ******************************************************************************************
10.   //  DATA TYPE demonstration
fun main()
{
    val a: Int = 5                // Int
    val b: Double = 5.99        // Double
    val c: Char = 'v'          // Char
    val d: Boolean = true     // Boolean
    val e: String = "CSE B"      // String
    val f: Float = 100.00f      // float
    println("a value is:" +a)
    println("b value is:" +b)
    println("c value is:" +c)
    println("d value is:" +d)
    println("e value is:" +e) 
    println("f value is:" +f)
}

Output:
a value is:5
b value is:5.99
c value is:v
d value is:true
e value is:CSE B
f value is:100.0
******************************************************************************************
11.loops and arrays of
// WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.	// DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}



17.	// FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}


18.	// BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}



19.	//CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}



20.	//RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}



21.	//ARRAY  demonstration
 fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
******************************************************************************************
12.	//  ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}

  Output:
  800
 ******************************************************************************************
13.8.	//primary constructor
fun main(args: Array<String>)
{
	val add = Add(5, 6)
	println("The Sum of numbers 5 and 6 is: ${add.c}")
}
class Add constructor(a: Int,b:Int)
{
	var c = a+b;
}

Output:
The Sum of numbers 5 and 6 is 11


******************************************************************************************
15.arrayOf() functoin , android app using intent 
 
fun main() 
{ 
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5) 
 println("Value at 3rd position : " + n[2]) 
}
Task-2
Write a program to identify the articulation points present in a graph.
Algorithm:
Algorithm Art(u, v)
// u is a start vertex for depth first search. v is its parent if any
// in the depth first spanning tree. It is assumed that the global
// array dfn is initialized to zero and that the global variable
// num is initialized to 1. n is the number of vertices in G.
{
    dfn[u] := num; L[u] := num; num := num + 1;
    for each vertex w adjacent from u do`
    {
        if (dfn[w] = 0) then
        {
            Art(w, u);     // w is unvisited.
            L[u] := min(L[u], L[w]);
        }
        else if (w ≠ v) then L[u] := min(L[u], dfn[w]);
    }
}
Program:
#include <stdio.h>

int dfn[10], a[10][10], l[10], n, num = 1, children[10];
int artp[10]; // Array to store articulation points

// Function to find the minimum of two values
int min(int a, int b) {
    return (a > b ? b : a);
}

// Depth-first search to find articulation points
void art(int u, int v) {
    dfn[u] = num;
    l[u] = num;
    num++;
    children[u] = 0;

    for (int i = 1; i <= n; i++) {
        if (a[u][i] == 1) { // Check if there is an edge from u to i
            int w = i;
            if (dfn[w] == 0) { // w is unvisited
                children[u]++;
                art(w, u);

                // Update the low value of u for parent function calls
                l[u] = min(l[u], l[w]);

                // Check articulation point conditions
                if (v != -1 && l[w] >= dfn[u]) {
                    artp[u] = 1; // Mark u as an articulation point
                }
            } else if (w != v) { // Update low value of u for back edges
                l[u] = min(l[u], dfn[w]);
            }
        }
    }
}

// Main function
int main() {
    printf("Enter no. of vertices: ");
    scanf("%d", &n);

    int s;
    printf("Enter root vertex: ");
    scanf("%d", &s);

    printf("Enter adjacency matrix:\n");
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    // Initialize arrays
    for (int i = 0; i <= n; i++) {
        dfn[i] = 0;
        l[i] = 0;
        children[i] = 0;
        artp[i] = 0;
    }

    printf("Articulation points are:\n");
    
    // Run DFS from the root vertex
    art(s, -1);

    // Check if the root is an articulation point (special case)
    if (children[s] > 1) {
        printf("%d\n", s);
    }

    // Print other articulation points
    for (int i = 1; i <= n; i++) {
        if (artp[i]) {
            printf("%d\n", i);
        }
    }

    return 0;
}
Output:
/tmp/96iN6R0Irx.o
Enter no. of vertices: 6
Enter root vertex: 1
Enter adjacency matrix:
0 1 0 1 0 0
1 0 1 0 0 0
0 1 0 1 1 1
1 0 1 0 0 0
0 0 1 0 0 0
0 0 1 0 0 0
Articulation points are:
3


=== Code Execution Successful ===
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.prog2.ui.theme.Prog2Theme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val nav_Controller = rememberNavController()
            NavHost(navController = nav_Controller, 
                startDestination = "fragment1") {
                composable("fragment1") {
                    Fragment1(nav_Controller)
                }
                composable("fragment2") {
                    Fragment2(nav_Controller) }
            }
        }
    }
}


@Composable
fun Fragment1(navController: NavController){
    Column {
        Button(onClick={ navController.navigate("fragment2")}) {
            Text(text = "Navigate to fragment2 ")
        }
    }
}


@Composable
fun Fragment2(navController: NavController) {
    Row(horizontalArrangement = Arrangement.SpaceEvenly){
        
        Button(onClick = { navController.navigateUp() }) {
            Text(text = "Back to Fragment 1")
        }
    }
}
// MainActivity.kt

package com.example.dbtest

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.room.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

// Room Database-related code (User entity, DAO, and Database class)

// User data class representing the database table
@Entity(tableName = "users")
data class User(
    @PrimaryKey(autoGenerate = true) val uid: Int = 0,
    val username: String,
    val phone: String
)

// DAO interface for database operations
@Dao
interface UserDAO {
    @Insert
    suspend fun insert(user: User)
}

// Room Database class
@Database(entities = [User::class], version = 1)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDAO

    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null

        fun getInstance(context: android.content.Context): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

// Main Activity to set up the content and provide the database instance
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val database = UserDatabase.getInstance(this)
        setContent {
            InsertRecord(database)
        }
    }
}

// Composable function for inserting user data
@Composable
fun InsertRecord(database: UserDatabase) {
    val context = LocalContext.current
    val userDao = database.userDao()

    var name by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }

    val scope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(25.dp))

        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(25.dp))

        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(25.dp))

        Button(onClick = {
            scope.launch(Dispatchers.IO) {
                // Insert user data in the database
                userDao.insert(User(username = name, phone = phone))
                // Display Toast on the main thread
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "Record Inserted Successfully", Toast.LENGTH_LONG).show()
                }
            }
        }) {
            Text(text = "Insert Now")
        }
    }
}



//Plugins

//kotlin("kapt")

//Dependencies

//val room_version = "2.6.1"
//    implementation("androidx.room:room-runtime:$room_version")
//    kapt("androidx.room:room-compiler:$room_version")
//    implementation("androidx.room:room-ktx:$room_version")
java 
Copy code 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.IOException; 
import java.io.PrintWriter; 
public class HelloServlet extends HttpServlet { 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
IOException { 
PrintWriter out = response.getWriter(); 
out.println("Hello from HttpServlet!"); 
} 
} 
Step 1: Install Apache Tomcat 
Download and install Apache Tomcat. 
Set up Tomcat by configuring environment variables (CATALINA_HOME and JAVA_HOME), if needed. 
Step 2: Save and Structure Your Servlet 
Save the servlet code in a file named HelloServlet.java. 
Organize it within the WEB-INF/classes directory inside your web application folder. For example: 
Copy code 
your-webapp 
├── WEB-INF 
│   ├── classes 
│   │   └── HelloServlet.java 
│   └── web.xml 
Step 3: Compile the Servlet 
Open a terminal or command prompt, navigate to WEB-INF/classes, and compile: 
bash 
Copy code 
javac -classpath <path-to-servlet-api.jar> HelloServlet.java 
Replace <path-to-servlet-api.jar> with the path to servlet-api.jar in the lib folder of your Tomcat installation. 
Step 4: Configure web.xml 
In the WEB-INF folder, create or update web.xml with the servlet mapping: 
xml 
Copy code 
<web-app> 
<servlet> 
<servlet-name>HelloServlet</servlet-name> 
<servlet-class>HelloServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>HelloServlet</servlet-name> 
<url-pattern>/hello</url-pattern> 
</servlet-mapping> 
</web-app> 
Step 5: Deploy and Start Tomcat 
Place the your-webapp folder in Tomcat’s webapps directory. 
Start Tomcat by running startup.sh (Linux/Mac) or startup.bat (Windows) in the bin folder. 
Step 6: Access the Servlet 
Open a browser and navigate to: http://localhost:8080/your-webapp/hello 
Expected Output 
If everything is set up correctly, you should see: 
plaintext 
Copy code 
Hello from HttpServlet! 
java 
Copy code 
import javax.servlet.*; 
import java.io.IOException; 
import java.io.PrintWriter; 
public class MyServlet implements Servlet { 
public void init(ServletConfig config) throws ServletException {} 
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { 
PrintWriter out = res.getWriter(); 
out.println("Hello Servlet Lifecycle!"); 
} 
public void destroy() {} 
public ServletConfig getServletConfig() { return null; } 
public String getServletInfo() { return null; } 
} 
Step 1: Install Apache Tomcat 
Download and install Apache Tomcat. 
Set up Tomcat by configuring the environment variables (CATALINA_HOME and JAVA_HOME), if necessary. 
Step 2: Save Your Java Code 
Save your servlet code in a file named MyServlet.java. 
Ensure that this file is located in the WEB-INF/classes directory within your web application directory 
structure. For example: 
Copy code 
your-webapp ├── WEB-INF │   ├── classes │   │   └── MyServlet.java │   └── web.xml  
Step 3: Compile the Servlet 
Open a terminal or command prompt and navigate to the WEB-INF/classes directory. 
Compile the servlet: 
bash 
Copy code 
javac -classpath <path-to-servlet-api.jar> MyServlet.java  
Replace <path-to-servlet-api.jar> with the path to the servlet-api.jar file in your Tomcat installation, typically 
located in the lib folder. 
Step 4: Configure web.xml 
In the WEB-INF folder, create or update the web.xml file with the following content: 
xml 
Copy code 
<web-app>     <servlet>         
class>     
<servlet-name>MyServlet</servlet-name>         
</servlet>     <servlet-mapping>         
<servlet-class>MyServlet</servlet
<servlet-name>MyServlet</servlet-name>         
pattern>/myservlet</url-pattern>     </servlet-mapping> </web-app>  
This configuration maps the servlet to the URL path /myservlet. 
Step 5: Deploy and Run 
<url
Copy your web application folder (your-webapp) into the webapps directory of your Tomcat installation. 
Start Tomcat by running the startup.sh (Linux/Mac) or startup.bat (Windows) file located in the bin directory 
of your Tomcat installation. 
Open a web browser and navigate to http://localhost:8080/your-webapp/myservlet. 
Expected Output 
If the servlet is configured and deployed correctly, you should see: 
plaintext 
Copy code 
Hello Servlet Lifecycle!  
If there’s an error, the Tomcat logs (located in the logs directory of your Tomcat installation) will contain 
information to help you debug. 
java 
Copy code 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
 
public class JDBCPreparedStatementExample { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      PreparedStatement pstmt = con.prepareStatement("INSERT INTO books (title, author) VALUES (?, ?)"); 
      pstmt.setString(1, "Java Programming"); 
      pstmt.setString(2, "Author Name"); 
      pstmt.executeUpdate(); 
      System.out.println("Data inserted successfully"); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
Data inserted successfully
[OR]
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
 
public class App { 
    public static void main(String[] args) { 
        // Database connection details 
        String url = "jdbc:mysql://localhost:3306/testdb"; // Replace with your DB name 
        String user = "root"; // Replace with your DB username 
        String password = "Varun13@"; // Replace with your DB password 
 
        // SQL queries 
        String insertQuery = "INSERT INTO books (title, author) VALUES (?, ?)"; 
        String updateQuery = "UPDATE books SET author = ? WHERE id = ?"; 
        String deleteQuery = "DELETE FROM books WHERE id = ?"; 
 
        try (Connection conn = DriverManager.getConnection(url, user, password)) { 
            System.out.println("Connected to the database!"); 
 
            // INSERT operation 
            try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) { 
                insertStmt.setString(1, "John Doe"); 
                insertStmt.setString(2, "john.doe@example.com"); 
                int rowsInserted = insertStmt.executeUpdate(); 
                System.out.println(rowsInserted + " row(s) inserted."); 
            } 
 
            // UPDATE operation 
            try (PreparedStatement updateStmt = conn.prepareStatement(updateQuery)) { 
                updateStmt.setString(1, "john.newemail@example.com"); 
                updateStmt.setInt(2, 1); // Assuming user with ID 1 exists 
                int rowsUpdated = updateStmt.executeUpdate(); 
                System.out.println(rowsUpdated + " row(s) updated."); 
            } 
 
            // DELETE operation 
            try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery)) { 
                deleteStmt.setInt(1, 1); // Assuming user with ID 1 exists 
                int rowsDeleted = deleteStmt.executeUpdate(); 
                System.out.println(rowsDeleted + " row(s) deleted."); 
            } 
 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } 
    } 
}
java 
Copy code 
import java.sql.Connection; 
import java.sql.DatabaseMetaData; 
import java.sql.DriverManager; 
 
public class DatabaseMetadata { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      DatabaseMetaData dbMeta = con.getMetaData(); 
      System.out.println("Database Product Name: " + dbMeta.getDatabaseProductName()); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
Database Product Name: MySQL
[OR]
import java.sql.*;

public class App {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";
        Connection connection = null;

        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish connection to the database
            connection = DriverManager.getConnection(jdbcURL, username, password);

            // Retrieve and print database metadata
            DatabaseMetaData metaData = connection.getMetaData();
            System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
            System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
            System.out.println("Driver Name: " + metaData.getDriverName());
            System.out.println("Driver Version: " + metaData.getDriverVersion());
        } catch (Exception e) {
            // Handle exceptions
            e.printStackTrace();
        } finally {
            // Close the connection
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
java 
Copy code 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Statement; 
 
public class DatabaseConnection { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      Statement stmt = con.createStatement(); 
      stmt.executeUpdate("INSERT INTO books (title) VALUES ('Sample Book')"); 
      System.out.println("SQL Query Executed"); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
SQL Query Executed
[OR]
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
 
public class App { 
    public static void main(String[] args) { 
        // Database credentials 
        String url = "jdbc:mysql://localhost:3306/testdb"; 
        String user = "root"; 
        String password = "Varun13@"; 
 
        // SQL query 
        String query = "SELECT * FROM books"; 
 
        // Establish connection and execute query 
        try (Connection conn = DriverManager.getConnection(url, user, password); 
             Statement stmt = conn.createStatement(); 
             ResultSet rs = stmt.executeQuery(query)) { 
 
            System.out.println("Connected to the database!"); 
 
            // Process the result set 
            while (rs.next()) { 
                int id = rs.getInt("id"); 
                String name = rs.getString("name"); 
                System.out.println("ID: " + id + ", Name: " + name); 
            } 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
Connected to the database!
XML File (books.xml): 
 
xml 
Copy code 
 
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="books.xsd">
    <book>
        <title>Wings of Fire</title>
        <author>A.P.J Abdul Kalam</author>
        <isbn>81-7371-146-1</isbn>
        <publisher>Arun Tiwar</publisher>
        <edition>1st</edition>
        <price>180</price>
    </book>
<book>
        <title>Introduction to xml</title>
        <author>Jane doe</author>
        <isbn>978-0451524935</isbn>
        <publisher>Tech Books Publisher</publisher>
        <edition>1st</edition>
        <price>29.99</price>
    </book>
</books>

 
 
XSD File (books.xsd):
 
xsd 
Copy code 
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
	xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:element name="books">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="title" type="xs:string" />
				<xs:element name="author" type="xs:string" />
				<xs:element name="isbn" type="xs:string" />
				<xs:element name="publisher" type="xs:string" />
				<xs:element name="edition" type="xs:string" />
				<xs:element name="price" type="xs:decimal" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>
XML File (books.xml): 
 
xml 
Copy code 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
    <book>
        <title>Wings of Fire</title>
        <author>A.P.J Abdul Kalam</author>
        <isbn>81-7371-146-1</isbn>
        <publisher>Arun Tiwar</publisher>
        <edition>1st</edition>
        <price>180</price>
    </book>
    <book>
        <title>Introduction to xml</title>
        <author>Jane doe</author>
        <isbn>978-0451524935</isbn>
        <publisher>Tech Books Publisher</publisher>
        <edition>1st</edition>
        <price>29.99</price>
    </book>
</books>
 

DTD File (books.dtd):

dtd 
Copy code 
<!ELEMENT books (book+)>
<!ELEMENT book (title, author, isbn, publisher, edition, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Web Design</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }


        header {
            background-color: #3498db;
            color: white;
            padding: 20px;
            text-align: center;
        }


        .container {
            padding: 20px;
        }


        .content {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
        }

        .content div {
            background-color: #2980b9;
            color: white;
            text-align: center;
            padding: 20px;
            border-radius: 8px;
        }

        @media (max-width: 768px) {
            .content {
                grid-template-columns: repeat(2, 1fr);

            }
        }


        @media (max-width: 480px) {
            .content {
                grid-template-columns: 1fr;

            }

            header {
                padding: 15px;

            }

            .content div {
                font-size: 14px;

            }
        }
    </style>
</head>

<body>
    <header>
        <h1>Responsive Web Design</h1>
    </header>

    <div class="container">
        <div class="content">
            <div>Item 1</div>
            <div>Item 2</div>
            <div>Item 3</div>
        </div>
    </div>
</body>

</html>
1.	Sample Program
fun main() 
{
    println("Hello, world!!!")
}
2.main() function with parameters
fun main(args : Array<String>) {
println("Hello World")
}
3. val / var demonstration
fun main()
{
var name = "Kotlin"          // String (text)
val birthyear = 2023         // Int (number)

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear

}
OR
// val / var demonstration
fun main()
{
var name: String = "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int

println(name)
println(birthyear)

}
OR
// val / var demonstration
fun main()
{
var name: String 
    name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
//  var demonstration
fun main()
{
var name= "CSE B"
 name = "CVR"  //  can be reassigned
println(name)   
}


//  val demonstration
fun main()
{
val name= "CSE B"
 name = "CVR"  //  cannot be reassigned
println(name)   
}

4.DATA TYPE demonstration
fun main()
{
val a: Int = 5                // Int
val b: Double = 5.99        // Double
val c: Char = 'v'          // Char
val d: Boolean = true     // Boolean
val e: String = "CSE B"      // String
val f: Float = 100.00f      // float
println("a value is:" +a)
println("b value is:" +b)
println("c value is:" +c)
println("d value is:" +d)
println("e value is:" +e) 
println("f value is:" +f)
}
5.escape sequences of character demonstration
fun main()
{
println('\n') //prints a newline character
println('\t') //prints a  tab character
println('\b') //prints a backspace character
println('\r') //prints a form feed character
println('\'') //prints a single quote character
println('\"') //prints a double quote character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
}
6.ARRAY  demonstration
fun main()
{
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5)
 println("Value at 3rd position : " + n[2])
}
7.TYPE CONVERSION demonstration
fun main()
{
    val x: Int = 100
   val y: Long = x.toLong()
   println(y)
}
8.ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}
9.ASSIGNMENT OPERATOR demonstration
fun main()
{
    var sum1 = 100       // ASSIGN A VALUE
    println(sum1)
}
10.COMPARISION  OPERATOR demonstration
fun main() {  
  var x = 5
 var y = 3
  println(x > y) // returns true because 5 is greater than 3
}
11.logical  OPERATOR demonstration
fun main() {  
    var x = 5
  println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10

}
12.STRING demonstration
fun main() {  
    var a:String="CSE B"
  println(a[2]) // DISPLAYS CHARACTER AT LOACTION OR INDEX 2

}
13.IF ELSE demonstration
fun main() {  
  val x = 20
val y = 18
if (x > y) {
  println( "x is greater than y" )
}
else {
        println( "x is lesser than y" ) 
    } }
14.WHEN demonstration
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}
15.WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}
17.FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}
18.BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}
19.CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}
20.RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}
21.ARRAY  demonstration
fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
//Tip Calculator

package com.example.tip

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.tip.ui.theme.TipTheme
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth


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

@Composable
fun TipCalculator(){
    var amount by remember { mutableStateOf("") }
    var tipPercentage by remember { mutableStateOf("") }
    var tipAmount by remember { mutableStateOf(0) }

    Column(
        modifier = Modifier.fillMaxSize()
                    .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    )
    {
        TextField(value = amount,
            onValueChange = {newAmount -> amount = newAmount},
            modifier = Modifier.fillMaxWidth(),
            label = {Text("Enter your total Bill:")})


        Spacer(modifier = Modifier.height(16.dp))


        TextField(value = tipPercentage,
            onValueChange = {newTipPercentage -> tipPercentage = newTipPercentage},
            modifier = Modifier.fillMaxWidth(),
            label = {Text("Enter tip percentage:")})

        Spacer(modifier = Modifier.height(16.dp))

        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick ={
            val billAmount = amount.toIntOrNull() ?: 0
            val tip = tipPercentage.toIntOrNull() ?: 0

            tipAmount = (tip * billAmount)/100 })
        {
            Text(text = "Calculate Tip")
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(text = "Your tip amount is: $tipAmount")
    }
}
package com.example.helloworld

import android.graphics.Color
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.helloworld.ui.theme.HelloworldTheme

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

@Composable
fun HelloWorld(){
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "Hello World", fontWeight = FontWeight.Bold, color = androidx.compose.ui.graphics.Color.Red)
    }
}
//First download images from this url: "https://github.com/google-developer-training/basic-android-kotlin-compose-training-dice-roller/raw/main/dice_images.zip"
//Then extract it
//Now come to android studio
//In Android Studio, click View > Tool Windows > Resource Manager.
//Click + > Import Drawables to open a file browser.
//Click Next.
//Click Import to confirm that you want to import the six images.


package com.example.diceroller

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.diceroller.ui.theme.DicerollerTheme

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

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

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

    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ){
        Image(painter = painterResource(imageResource), contentDescription = result.toString())
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {result = (1..6).random()}){
            Text(text = "Roll  Dice")
        }
    }
}
//Step1: Implement these 3 Dependencies in build.gradle.kts(Module:app)

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

//Step2: Create CounterViewModel.kt

package com.example.incrementviewmodel

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

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

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

//MainActivity.kt

package com.example.incrementviewmodel

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

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

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

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

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

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

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

package com.example.diceroller

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

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


@Composable
fun DiceRollerApp() {
    DiceWithButtonAndImage()
}

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

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

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

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

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

}

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

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

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

@Composable
fun simpleButton(){

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

 Properties:  title,Author,Published_year

Methods:
  displayInfo : to print Book details.

//Program
package com.example.objectoriented

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

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

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



2. Simple class with a Primary Constructor

//Program

package com.example.objectoriented

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

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

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


3. Implelemt a Employee Class with default constructor values

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

  Methods: showdetails()

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

package com.example.objectoriented

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

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

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


}

1.HTML - blockquote tag and q tag

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

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



2. HTML Basics - Formatted tags-Olympics


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

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

    </body>
</html>
MainActivity.kt

package com.example.intent

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

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

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

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

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

activity_main.xml

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

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


</LinearLayout>

DetailsActivity.kt

package com.example.intent

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

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

activity_deatils.xml

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

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

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

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

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

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

</androidx.constraintlayout.widget.ConstraintLayout>






package com.example.imageshuffler

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

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

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

        chngbt.setOnClickListener {

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

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

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

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



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

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

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

</LinearLayout>





package com.example.sum

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

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

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


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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class SettingsActivity : AppCompatActivity() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class MainActivity : AppCompatActivity() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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


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

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

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


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


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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

                android:text="4"/>

        </LinearLayout>

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

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

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

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

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

        </LinearLayout>

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

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

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

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

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

        </LinearLayout>

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

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

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

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

                android:text="=" />

        </LinearLayout>

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

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

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

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

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

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

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

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

        val localFile = File(filePath)

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

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

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

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

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

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


                            outputStream.write(buffer, 0, count)
                        }

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

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

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

                }

            }
        }

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

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

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

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

    shortcutManager.requestPinShortcut(pinShortcutInfo,
            successCallback.intentSender)
}

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

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


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

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


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

        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

        println("Result: $result")
    }

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

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

            else -> "Empate"
        }

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

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

            else -> "Empate"
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

array - ne mozes dodavati nove

lists - mora biti mutableList da mozes dodavati

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

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

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

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

    var isNum1 = true
    var isNum2 = true

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

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

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


class MainActivity : AppCompatActivity() {

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


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


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


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

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

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


    }

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

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

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


    private fun requestPermission() {

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

        val permissionResuest: MutableList<String> = ArrayList()

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

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

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

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


    }

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

// RoomDatabase Libraries

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

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

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


// Retrofit

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



// for enabling view and databinding in android tag

buildFeatures{
        dataBinding true
    }

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

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

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

    private var _binding: T? = null

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

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

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

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

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

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

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

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


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

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

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

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

       button = findViewById(R.id.button)

       counter = findViewById(R.id.counter)

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

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

   }

}

class viewModel() : ViewModel() {

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

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

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

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

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

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

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

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

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

const val riesenieSila = 92
const val riesenieSmer = 15

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

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

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

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

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

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

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

        handler.postDelayed(runnable,10000)
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class MainActivity : AppCompatActivity() {
    val CALL_REQUEST_CODE = 101

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

        setupPermissions()

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

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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

class MyCustomObject: Serializable {

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

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

	constructor()
}

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

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

</RelativeLayout>


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

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

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

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

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

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

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

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

</RelativeLayout>
//EXAMPLE

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

#activity_main.xml

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

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

#new resource layout (card_view_design.xml)

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

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

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

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

	</LinearLayout>

</androidx.cardview.widget.CardView>

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

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

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

		return ViewHolder(view)
	}

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

		val ItemsViewModel = mList[position]

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

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

	}

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

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

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

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

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

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

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

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

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

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

	}
}

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.DynamicPhotoFrame">
        <activity
            android:name=".MainActivity"
            android:exported="true" >
            <intent-filter android:exported="true">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

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


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

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

         name_display.text = name
        email_display.text = email

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

    }

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

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

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

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

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


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

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

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

        spGender.onItemSelectedListener = this
    }

//XML

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

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

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

        handler.postDelayed(runnable,3000)
    }

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

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

//XML

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

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

    init {
        instance = this
    }

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

    override fun onCreate() {
        super.onCreate()

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

open class PrefUtils {

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

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

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

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

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

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

.
.
.

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

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

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

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

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


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

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

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

//OR

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

//OR

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


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


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

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

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

  <ScrollView

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

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


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

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

        >

            <TextView

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

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


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

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

        >

            <TextView

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

            />

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


        <TextView

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

        />

        <Button

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

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


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

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

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

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

		//code
		return@OnKeyListener true

	}

	false

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    override fun getItemCount(): Int = listaResult.size

    companion object {

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





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

interface ViewTypeDelegateAdapter {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder

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



class LoadingDelegateAdapter : ViewTypeDelegateAdapter {

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

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

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


class ListasDelegateAdapter : ViewTypeDelegateAdapter {

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

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

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

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

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

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

  
package utils

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


star

Mon Nov 18 2024 07:10:02 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 15 2024 16:44:05 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 15 2024 16:29:17 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 15 2024 16:20:53 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 15 2024 14:26:12 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 15 2024 14:03:45 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 17:19:51 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 17:07:41 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:53:23 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:31:13 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:25:15 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:23:06 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:20:10 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Wed Nov 06 2024 16:17:57 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Sun Nov 03 2024 12:41:56 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 01 2024 18:15:45 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Fri Nov 01 2024 17:41:32 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Oct 31 2024 16:23:26 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Oct 31 2024 16:20:13 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Oct 31 2024 16:18:17 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Oct 31 2024 16:09:37 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Thu Oct 31 2024 04:39:36 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Tue Oct 29 2024 13:35:36 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 28 2024 16:18:05 GMT+0000 (Coordinated Universal Time)

#kotlin
star

Mon Oct 28 2024 14:21:49 GMT+0000 (Coordinated Universal Time)

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#swift #javascript #kotlin #mysql
star

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

#kotlin #android
star

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

#kotlin
star

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

#gradle #kotlin
star

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

#gradle #kotlin
star

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

#gradle #kotlin
star

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

#kotlin #mongodb #graphql
star

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

#kotlin #mongodb
star

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

#kotlin
star

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

#kotlin #string #editable #extention
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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

#kotlin
star

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