0% found this document useful (0 votes)
7 views

Java Programs

This document provides a laboratory certificate for a student who completed practical experiments for the subject CS-31 Mobile Application Development in Android using Kotlin. It includes the student's name, enrollment number, institute, and signatures of the subject in-charge and head of department.

Uploaded by

Ayush Kothari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Programs

This document provides a laboratory certificate for a student who completed practical experiments for the subject CS-31 Mobile Application Development in Android using Kotlin. It includes the student's name, enrollment number, institute, and signatures of the subject in-charge and head of department.

Uploaded by

Ayush Kothari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

CS – 31 Mobile Application Development in Android using Kotlin

BCA Semester – 6

Journal
H & H Kotak Institute of Science, Rajkot

BCA Department
H & H B Kotak Institute of Science, Rajkot
BCA Department

Laboratory Certificate

This is to certify that Smt./Shri ________________________________________ has

satisfactory completed BCA Semester-6 practical experiments of subject CS-31

Mobile Application Development in Android using Kotlin during the academic year

_____________. Her/His enrollment number is ______________________

registered at Saurashtra University, Rajkot.

Date: _____________

Subject In-Charge Head of the Department


Index
Page Date of Date of
Sr. Name of Experiments Remarks
No. Experiment Supervision
Unit-1
1 Hello World Program 5
2 Mutable Variable 5
3 Basic data types 5
4 Use of Array 5
5 Arithmatic Operator 5
6 UDF 6
Passing parameters and returning
7 6
value by UDF
8 Function recursion 6
9 Range in Kotlin 7
10 If returning value 7
11 For loop with array 7
12 Break and continue 7
13 List Collection 7
14 Set Collection 8
15 Map Collection 8
16 Class and Object 8
17 Constructor 8
18 Inheritance 9
19 Visibility Modes 9
20 Exception Handling 9
Unit-2
21 Hello World in Android 12
22 Activity Life Cycle 13
Unit-3
23 EditText and Toast 15
24 Two EditText and Toast 17
25 Check Box 19
26 Radio Button 21
27 Spinner 22
28 Explicit Intent 24
29 Implicit Intent 27
30 Alert Dialog 28
Unit-4
31 Write data into External Storage 32
32 Shared Preferences 35
33 SQLite Example 39
Unit-5
34 Android device vibdrate 43
35 Telephony API 45
Unit-1

Introduction to Kotlin
Programming
Unit-1 Introduction to Kotlin Programing
1. Hello World Program
1 /*Hello World Program*/
2
3 fun main() {
4 println("Hello World")
5 print("Hello ")
6 print("World")
7 }

2. Mutable variable
1 //Mutable Variable in Kotlin
2 fun main() {
3 var name = "Java Programing"
4 println("Name = $name")
5
6 name = "Kotlin Progaming"
7 println("Name = $name")
8 }

3. Basic data types


1 //Basic data types in kotlin
2
3 fun main(args: Array<String>) {
4 val a: Int = 10000
5 val d: Double = 100.00
6 val f: Float = 100.00f
7 val l: Long = 1000000004
8 val s: Short = 10
9 val b: Byte = 1
10 val letter: Char = 'A'
11 val strVar: String="Kotlin"
12
13 println("Int Value is $a")
14 println("Double Value is $d")
15 println("Float Value is $f")
16 println("Long Value is $l" )
17 println("Short Value is $s")
18 println("Byte Value is $b")
19 println("Char Value is $letter")
20 println("String Value = $strVar")
21 }

4. Use of Array
1 //Array data type in kotlin
2
3 fun main(args: Array<String>) {
4 val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
5 println("Value at 3rd position : " + numbers[2])
6 }

5. Arithmatic Operators
1 //Arithmatic Operators in Kotlin
2
3 fun main() {
4 var a: Int=10
5 var b: Int=20
6 println("a+b= " + (a+b))
Page 5 of 48
CS-31 Mobile Application Development in Android using Kotlin
7 println("a-b= " + (a-b))
8 println("a*b= " + (a*b))
9 println("a/b= " + (a/b))
10 println("a%b= " + (a%b))
11 }

6. UDF
1 //Kotlin UDF.
2 fun main(args: Array<String>) {
3 printHello()
4 }
5
6 fun printHello(){
7 println("Hello, World!")
8 }

7. Passing parameters and returning value by UDF


1 //Parameter pass into function and return value.
2
3 fun main(args: Array<String>) {
4 val a = 10
5 val b = 20
6
7 val result = sumTwo(a, b)
8 println( result )
9
10 }
11
12 fun sumTwo(a:Int, b:Int):Int{
13 val x = a + b
14
15 return x
16 }

8. Function recursion
1 //Function recursion in Kotlin
2
3 fun main(args: Array<String>) {
4 val a = 4
5
6 val result = factorial(a)
7 println( result )
8 }
9
10 fun factorial(a:Int):Int{
11 val result:Int
12
13 if( a <= 1){
14 result = a
15 }else{
16 result = a*factorial(a-1)
17 }
18 return result
19 }
Unit-1 Introduction to Kotlin Programing
9. Range in Kotlin
1 //when loop with range.
2
3 fun main(args: Array<String>) {
4 val day = 2
5 when (day) {
6 in 1..5 -> println("Weekday")
7 else -> println("Weekend")
8 }
9 }

10. if returning value


1 //if returning value.
2
3 fun main(args: Array<String>) {
4 val age:Int = 10
5
6 val result = if (age > 18) {
7 "Adult"
8 } else {
9 "Minor"
10 }
11 println(result)
12 }

11. for loop with array


1 //for loop with array.
2
3 fun main(args: Array<String>) {
4 var fruits = arrayOf("Orange", "Apple", "Mango", "Banana")
5
6 for (item in fruits) {
7 println(item)
8 }
9 }

12. Break and Continue


1 //use of Break and Continue.
2
3 fun main(){
4 var a: Int = 0
5 while(true) {
6 a++
7 if(a%2==0) continue
8 if(a>10) break
9 println(a)
10 }
11 }

13. List Collection


1 //Creating and Display List (Collection).
2
3 fun main() {
4 val theList = mutableListOf("one", "two", "three", "four")
5 theList.add("five")
6 println(theList.toString())
7 }
Page 7 of 48
CS-31 Mobile Application Development in Android using Kotlin

14. Set Collection


1 //Creating and Display Sets (Collection).
2
3 fun main() {
4 val theSet = mutableSetOf("one", "two", "three", "four")
5 theSet.add("five")
6 println(theSet.sorted())
7 }

15. Map Collection


1 //Creating and Display Map (Collection).
2
3 fun main() {
4 val theMap = mapOf(Pair("one", 1), Pair("two", 2),
5 Pair("three", 3))
6 //val theMap = mapOf(Pair("one", 1), Pair("two", 2),
7 Pair("three", 3))
8 println(theMap)
9 println("Entries: " + theMap.entries)
10 println("Keys:" + theMap.keys)
11 println("Values:" + theMap.values)
12 }

16. Class and Objects


1 //Class and Object in Kotlin
2
3 class myClass {
4 // Property (data member)
5 private var name: String = "Kotlin Programing"
6
7 // Member function
8 fun printMe() {
9 print("New Programing Language - " + name)
10 }
11 }
12 fun main(args: Array<String>) {
13 val obj = myClass() // Create object obj of myClass class
14 obj.printMe() // Call a member function using object
15 }

17. Constructor
1 //Constructor in Kotlin
2
3 class Person{
4 // Member Variables
5 var name: String
6 var age: Int
7
8 // Initializer Block
9 init {
10 println("Initializer Block")
11 }
12
13 // Secondary Constructor
14 constructor ( _name: String, _age: Int) {
15 this.name = _name
Unit-1 Introduction to Kotlin Programing
16 this.age = _age
17 println("Name = $name")
18 println("Age = $age")
19 }
20 }
21
22 fun main(args: Array<String>) {
23 val zara = Person("Malay Dave", 40)
24 }

18. Inheritance
1 //Inheritance in Kotlin
2
3 open class ABC {
4 open fun think () {
5 print("Hey!! i am thinking ")
6 }
7 }
8 class BCD: ABC() { // inheritance happens using default
9 constructor
10 override fun think() {
11 print("I Am from Child")
12 }
13 }
14 fun main(args: Array<String>) {
15 var a = BCD()
16 a.think()
17 }

19. Visibility Modes


1 //Protected Visibility Control in Kotlin
2
3 open class A() {
4 protected val i = 1
5 }
6 class B : A() {
7 fun getValue() : Int {
8 return i
9 }
10 }
11
12 fun main() {
13 var obj = B()
14 println(obj.getValue())
15 }

20. Exception Handling


1 //Exception Handling in Kotlin
2
3 fun main(args: Array<String>) {
4 try {
5 val myVar:Int = 12;
6 val v:String = "Kotlin Programing";
7 v.toInt();
8 } catch(e:Exception) {
9 e.printStackTrace();
10 } finally {
Page 9 of 48
CS-31 Mobile Application Development in Android using Kotlin
11 println("Exception Handeling in Kotlin");
12 }
13 }
Unit – 2

Introduction to Android &


Android Application Design
Unit-2 Introduction to Android
21. Hello World in Android
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
11 android:layout_width="wrap_content"
12 android:layout_height="wrap_content"
13 android:text="@string/hello"
14 android:textSize="24sp"
15 app:layout_constraintBottom_toBottomOf="parent"
16 app:layout_constraintEnd_toEndOf="parent"
17 app:layout_constraintStart_toStartOf="parent"
18 app:layout_constraintTop_toTopOf="parent" />
19
20 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.helloworldkotlin
2
3 import androidx.appcompat.app.AppCompatActivity
4 import android.os.Bundle
5
6 class MainActivity : AppCompatActivity() {
7 override fun onCreate(savedInstanceState: Bundle?) {
8 super.onCreate(savedInstanceState)
9 setContentView(R.layout.activity_main)
10 }
11 }
----------------------------------------------------------------
Strings.xml
-----------
1 <resources>
2 <string name="app_name">HelloWorldKotlin</string>
3 <string name="hello">Hello World</string>
4 </resources>
Unit-2 Introduction to Android

22. Acitivity Life Cycle


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity"/>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.activitylifecyclekotlin
2
3 import androidx.appcompat.app.AppCompatActivity
4 import android.os.Bundle
5 import android.util.Log
6
7 class MainActivity : AppCompatActivity() {
8 override fun onCreate(savedInstanceState: Bundle?) {
9 super.onCreate(savedInstanceState)
10 setContentView(R.layout.activity_main)
11 print("onCreate")
12 }
13
14 override fun onStart() {
15 super.onStart()
16 print("onStart")
17 }
18
19 override fun onResume() {
20 super.onResume()
21 print("onResume")
22 }
23
24 override fun onPause() {
25 super.onPause()
26 print("onPause")
27 }
28
Page 13 of 48
CS-31 Mobile Application Development in Android using Kotlin
29 override fun onStop() {
30 super.onStop()
31 print("onStop")
32 }
33
34 override fun onRestart() {
35 super.onRestart()
36 print("onRestart")
37 }
38
39 override fun onDestroy() {
40 super.onDestroy()
41 print("onDestroy")
42 }
43
44 fun print(msg: String){
45 Log.d("Activity State ",msg)
46 }
47
48 }
Unit – 3

Android User Interface Design


Unit-3 Android User Interface Design
23. EditText and Toast
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <EditText
11 android:id="@+id/editTextTextPersonName2"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginStart="156dp"
15 android:ems="10"
16 android:inputType="textPersonName"
17 android:textAlignment="textStart"
18 app:layout_constraintStart_toStartOf="parent"
19 tools:ignore="MissingConstraints"
20 tools:layout_editor_absoluteY="68dp" />
21
22 <Button
23 android:id="@+id/button2"
24 android:layout_width="wrap_content"
25 android:layout_height="wrap_content"
26 android:layout_marginTop="32dp"
27 android:text="Show Text"
28 app:layout_constraintEnd_toEndOf="parent"
29 app:layout_constraintHorizontal_bias="0.498"
30 app:layout_constraintStart_toStartOf="parent"
31 app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName2" />
32
33 <TextView
34 android:id="@+id/textView"
35 android:layout_width="wrap_content"
36 android:layout_height="wrap_content"
37 android:text="Enter Text:"
38 android:textSize="24sp"
39 tools:layout_editor_absoluteX="16dp"
40 tools:layout_editor_absoluteY="68dp"
41 tools:ignore="MissingConstraints" />
42
43
44 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.helloworld
2
3 import androidx.appcompat.app.AppCompatActivity
4 import android.os.Bundle
5 import android.widget.Button;
6 import android.view.View;
7 import android.widget.EditText;
8 import android.widget.Toast;
9
10 class MainActivity : AppCompatActivity() {
11
12 override fun onCreate(savedInstanceState: Bundle?) {
13 super.onCreate(savedInstanceState)
Unit-3 Android User Interface Design
14 setContentView(R.layout.activity_main)
15
16 val but1 = findViewById<Button>(R.id.button2);
17 val txt1 = findViewById<EditText>(R.id.editTextTextPersonName2);
18
19 but1.setOnClickListener {
20
21 Toast.makeText(applicationContext,txt1.text.toString(),Toast.LENGTH_LONG).show()
22 }
23 }
24 }

24. Two EditText and Toast


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginStart="36dp"
15 android:layout_marginTop="92dp"
16 android:text="Enter Text:"
17 android:textSize="20sp"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent" />
20
21 <EditText
22 android:id="@+id/editTextTextPersonName"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_marginStart="28dp"
26 android:layout_marginTop="76dp"
27 android:ems="10"
28 android:inputType="textPersonName"

Page 17 of 48
CS-31 Mobile Application Development in Android using Kotlin
29 android:textSize="20sp"
30 app:layout_constraintStart_toEndOf="@+id/textView"
31 app:layout_constraintTop_toTopOf="parent" />
32
33 <TextView
34 android:id="@+id/textView2"
35 android:layout_width="98dp"
36 android:layout_height="34dp"
37 android:layout_marginStart="36dp"
38 android:layout_marginTop="64dp"
39 android:text="Your text:"
40 android:textSize="20sp"
41 app:layout_constraintStart_toStartOf="parent"
42 app:layout_constraintTop_toBottomOf="@+id/textView" />
43 <EditText
44 android:id="@+id/editTextTextPersonName2"
45 android:layout_width="wrap_content"
46 android:layout_height="wrap_content"
47 android:layout_marginStart="24dp"
48 android:layout_marginTop="60dp"
49 android:ems="10"
50 android:inputType="textPersonName"
51 android:textSize="20sp"
52 app:layout_constraintStart_toEndOf="@+id/textView2"
53 app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" />
54 <Button
55 android:id="@+id/button"
56 android:layout_width="wrap_content"
57 android:layout_height="wrap_content"
58 android:layout_marginTop="312dp"
59 android:text="Display Text"
60 app:layout_constraintEnd_toEndOf="parent"
61 app:layout_constraintHorizontal_bias="0.46"
62 app:layout_constraintStart_toStartOf="parent"
63 app:layout_constraintTop_toTopOf="parent" />
64 </androidx.constraintlayout.widget.ConstraintLayout>
65 ----------------------------------------------------------------
66 MainActivity.kt
----------------
package com.example.edittext2

1 import androidx.appcompat.app.AppCompatActivity
2 import android.os.Bundle
3 import android.widget.Button
4 import android.widget.EditText
5 import android.widget.Toast
6
7 class MainActivity : AppCompatActivity() {
8 override fun onCreate(savedInstanceState: Bundle?) {
9 super.onCreate(savedInstanceState)
10 setContentView(R.layout.activity_main)
11 val text1 = findViewById<EditText>(R.id.editTextTextPersonName)
12 val text2 = findViewById<EditText>(R.id.editTextTextPersonName2)
13 val but1=findViewById<Button>(R.id.button)
14
15 but1.setOnClickListener {
16 text2.setText(text1.text.toString())
17
18 Toast.makeText(applicationContext,text1.text.toString(),Toast.LENGTH_LONG).show()
19 }
20 }
21 }
Unit-3 Android User Interface Design

25. Check Box


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="Select Item(s):"
15 android:textSize="24sp"
16 app:layout_constraintBottom_toBottomOf="parent"
17 app:layout_constraintEnd_toEndOf="parent"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent"
20 app:layout_constraintVertical_bias="0.14" />
21
22 <LinearLayout
23 android:layout_width="315dp"
24 android:layout_height="160dp"
25 android:layout_marginTop="160dp"
26 android:orientation="vertical"
27 app:layout_constraintEnd_toEndOf="parent"
28 app:layout_constraintStart_toStartOf="parent"
29 app:layout_constraintTop_toTopOf="parent">
30
31 <CheckBox
32 android:id="@+id/chkPizza"
33 android:layout_width="wrap_content"
34 android:layout_height="wrap_content"
35 android:text="Pizza"
36 android:textSize="24sp" />
37
38 <CheckBox
39 android:id="@+id/chkHotDog"
40 android:layout_width="wrap_content"
41 android:layout_height="wrap_content"
42 android:text="Hot Dog"
43 android:textSize="24sp" />
Page 19 of 48
CS-31 Mobile Application Development in Android using Kotlin
44
45 <CheckBox
46 android:id="@+id/chkBurgur"
47 android:layout_width="wrap_content"
48 android:layout_height="wrap_content"
49 android:text="Burgur"
50 android:textSize="24sp" />
51
52 </LinearLayout>
53
54 <Button
55 android:id="@+id/button"
56 android:layout_width="wrap_content"
57 android:layout_height="wrap_content"
58 android:layout_marginTop="380dp"
59 android:text="Gnerate Bill"
60 app:layout_constraintEnd_toEndOf="parent"
61 app:layout_constraintHorizontal_bias="0.498"
62 app:layout_constraintStart_toStartOf="parent"
63 app:layout_constraintTop_toTopOf="parent" />
64
65 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.checkboxkotlin
2
3 import android.os.Bundle
4 import android.widget.Button
5 import android.widget.CheckBox
6 import android.widget.Toast
7 import androidx.appcompat.app.AppCompatActivity
8
9 class MainActivity : AppCompatActivity() {
10 override fun onCreate(savedInstanceState: Bundle?) {
11 super.onCreate(savedInstanceState)
12 setContentView(R.layout.activity_main)
13
14 val p=findViewById<CheckBox>(R.id.chkPizza)
15 val h=findViewById<CheckBox>(R.id.chkHotDog)
16 val b=findViewById<CheckBox>(R.id.chkBurgur)
17 val g=findViewById<Button>(R.id.button)
18
19 g.setOnClickListener {
20
21 var totalamount = 0
22 var result = StringBuilder()
23 result.append("Selected Items:")
24 if(p.isChecked()){
25 result.append("\nPizza 100Rs")
26 totalamount+=100
27 }
28 if(h.isChecked()){
29 result.append("\nHot Dog 80Rs")
30 totalamount+=80
31 }
32 if(b.isChecked()){
33 result.append("\nBurgur 50Rs")
34 totalamount+=50
35 }
36 result.append("\nTotal: "+totalamount+"Rs")
37 Toast.makeText(applicationContext, result.toString(),
38 Toast.LENGTH_LONG).show()
Unit-3 Android User Interface Design
39 }
40 }
41 }

26. Radio Button


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <RadioGroup
11 android:id="@+id/radioGroup"
12 android:layout_width="203dp"
13 android:layout_height="115dp"
14 app:layout_constraintEnd_toEndOf="parent"
15 app:layout_constraintStart_toStartOf="parent"
16 tools:layout_editor_absoluteY="90dp">
17
18 <RadioButton
19 android:id="@+id/radioButton"
20 android:layout_width="match_parent"
21 android:layout_height="wrap_content"
22 android:text="Male"
23 android:textSize="24sp" />
24
25 <RadioButton
26 android:id="@+id/radioButton2"
27 android:layout_width="match_parent"
28 android:layout_height="wrap_content"
29 android:text="Female"
30 android:textSize="24sp" />
31 </RadioGroup>
32
33 <Button
34 android:id="@+id/button"
35 android:layout_width="wrap_content"
36 android:layout_height="wrap_content"
37 android:layout_marginStart="156dp"
38 android:layout_marginTop="288dp"
39 android:text="Click"
Page 21 of 48
CS-31 Mobile Application Development in Android using Kotlin
40 app:layout_constraintStart_toStartOf="parent"
41 app:layout_constraintTop_toTopOf="parent" />
42 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.radiobuttonkotlin
2
3 import androidx.appcompat.app.AppCompatActivity
4 import android.os.Bundle
5 import android.widget.Button
6 import android.widget.RadioButton
7 import android.widget.RadioGroup
8 import android.widget.Toast
9
10 class MainActivity : AppCompatActivity() {
11 override fun onCreate(savedInstanceState: Bundle?) {
12 super.onCreate(savedInstanceState)
13 setContentView(R.layout.activity_main)
14
15 val radioGroup=findViewById<RadioGroup>(R.id.radioGroup)
16 val button=findViewById<Button>(R.id.button)
17
18 button.setOnClickListener {
19 var selectedId:Int = radioGroup.getCheckedRadioButtonId()
20 var generatedButton = findViewById<RadioButton>(selectedId)
21 if (selectedId==-1)
22 {
23 Toast.makeText(applicationContext,"Nothing selected",
24 Toast.LENGTH_SHORT).show()
25 }
26 else
27 {
28
29 Toast.makeText(applicationContext,generatedButton.text.toString(),
Toast.LENGTH_SHORT).show()
30 }
31 }
32 }
33 }
Unit-3 Android User Interface Design
27. Spinner
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="Select Languages:"
15 app:layout_constraintBottom_toBottomOf="parent"
16 app:layout_constraintEnd_toEndOf="parent"
17 app:layout_constraintStart_toStartOf="parent"
18 app:layout_constraintTop_toTopOf="parent"
19 app:layout_constraintVertical_bias="0.195" />
20
21 <Spinner
22 android:id="@+id/spinner"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_marginTop="76dp"
26 app:layout_constraintEnd_toEndOf="parent"
27 app:layout_constraintStart_toStartOf="parent"
28 app:layout_constraintTop_toBottomOf="@+id/textView" />
29
30 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
strings.xml
------------
1 <resources>
2 <string name="app_name">SpinnerKotlin</string>
3 <string-array name="Languages">
4 <item>Java</item>
5 <item>Kotlin</item>
6 <item>Swift</item>
7 <item>Python</item>
8 <item>Scala</item>
9 <item>Perl</item>
10 </string-array>
11 </resources>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.spinnerkotlin
2
3 import androidx.appcompat.app.AppCompatActivity
4 import android.os.Bundle
5 import android.view.View
6 import android.widget.AdapterView
7 import android.widget.ArrayAdapter
8 import android.widget.Spinner
9 import android.widget.Toast
10
11 class MainActivity : AppCompatActivity() {
12 override fun onCreate(savedInstanceState: Bundle?) {
13 super.onCreate(savedInstanceState)
Page 23 of 48
CS-31 Mobile Application Development in Android using Kotlin
14 setContentView(R.layout.activity_main)
15
16 val languages = resources.getStringArray(R.array.Languages)
17
18 // access the spinner
19 val spinner = findViewById<Spinner>(R.id.spinner)
20 if (spinner != null) {
21 val adapter = ArrayAdapter(this,
22 android.R.layout.simple_spinner_item, languages)
23 spinner.adapter = adapter
24
25 spinner.onItemSelectedListener = object :
26 AdapterView.OnItemSelectedListener {
27 override fun onItemSelected(parent: AdapterView<*>,
28 view: View, position: Int, id: Long)
{
29 Toast.makeText(this@MainActivity,
"Language: " +
"" + languages[position],
Toast.LENGTH_SHORT).show()
}
30
31 override fun onNothingSelected(parent: AdapterView<*>) {
32 // write code to perform some action
33 }
34 }
35 }
36 }
37 }

28. Explcit Intent


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
Unit-3 Android User Interface Design
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="First Activity"
15 android:textSize="24sp"
16 app:layout_constraintBottom_toBottomOf="parent"
17 app:layout_constraintEnd_toEndOf="parent"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent" />
20
21 <Button
22 android:id="@+id/button"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_marginTop="52dp"
26 android:text="Next"
27 app:layout_constraintEnd_toEndOf="parent"
28 app:layout_constraintHorizontal_bias="0.498"
29 app:layout_constraintStart_toStartOf="parent"
30 app:layout_constraintTop_toBottomOf="@+id/textView" />
31
32 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
activity_main2.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity2">
9
10 <TextView
11 android:id="@+id/textView2"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="Second Activity"
15 android:textSize="24sp"
16 app:layout_constraintBottom_toBottomOf="parent"
17 app:layout_constraintEnd_toEndOf="parent"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent" />
20
21 <Button
22 android:id="@+id/button2"
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_marginTop="56dp"
26 android:text="Previous"
27 app:layout_constraintEnd_toEndOf="parent"
28 app:layout_constraintHorizontal_bias="0.498"
29 app:layout_constraintStart_toStartOf="parent"
30 app:layout_constraintTop_toBottomOf="@+id/textView2" />
31 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.intentdemo;
2
3 import androidx.appcompat.app.AppCompatActivity;
4

Page 25 of 48
CS-31 Mobile Application Development in Android using Kotlin
5 import android.content.Intent;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.widget.Button;
9
10 public class MainActivity extends AppCompatActivity {
11
12 Button but1;
13
14 @Override
15 protected void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.activity_main);
18
19 process();
20 }
21 void process() {
22 but1=(Button) findViewById(R.id.button);
23
24 but1.setOnClickListener(new View.OnClickListener() {
25 @Override
26 public void onClick(View view) {
27 Intent i = new Intent(getApplicationContext(),
MainActivity2.class);
28 i.putExtra("Value1", "Intent Example");
29 i.putExtra("Value2", "By Dr. Malay Dave");
30 startActivity(i);
31 }
32 });
33
34 }
35 }
----------------------------------------------------------------
1 MainActivity2.kt
2 ----------------
3 package com.example.intentdemo;
4
5 import androidx.appcompat.app.AppCompatActivity;
6
7 import android.content.Intent;
8 import android.os.Bundle;
9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.Toast;
12
13 public class MainActivity2 extends AppCompatActivity {
14
15 Button but2;
16
17 @Override
18 protected void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main2);
21
22 Bundle extras = getIntent().getExtras();
23 String value1 = extras.getString("Value1");
String value2 = extras.getString("Value2");
24 Toast.makeText(getApplicationContext(), "Values are:\n First value: " +
25 value1 + "\n Second Value: " + value2, Toast.LENGTH_LONG).show();
26
27 process();
28 }
29
Unit-3 Android User Interface Design
30 void process() {
31 but2=(Button) findViewById(R.id.button2);
32 but2.setOnClickListener(new View.OnClickListener() {
33 @Override
public void onClick(View view) {
34 Intent i = new Intent(getApplicationContext(),
35 MainActivity.class);
36 startActivity(i);
37 }
38 });
}
}

29. Implicit Intent


activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <TextView
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:text="Implicit Intent"
15 android:textSize="24sp"
16 app:layout_constraintBottom_toBottomOf="parent"
17 app:layout_constraintEnd_toEndOf="parent"
18 app:layout_constraintStart_toStartOf="parent"
19 app:layout_constraintTop_toTopOf="parent"
20 app:layout_constraintVertical_bias="0.188" />
21
22 <Button
23 android:id="@+id/button"
24 android:layout_width="wrap_content"
25 android:layout_height="wrap_content"
26 android:layout_marginTop="68dp"
27 android:text="Share"
28 app:layout_constraintEnd_toEndOf="parent"
29 app:layout_constraintHorizontal_bias="0.498"
30 app:layout_constraintStart_toStartOf="parent"
Page 27 of 48
CS-31 Mobile Application Development in Android using Kotlin
31 app:layout_constraintTop_toBottomOf="@+id/textView" />
32
33 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.implicitintent;
2
3 import androidx.appcompat.app.AppCompatActivity;
4
5 import android.content.Intent;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.widget.Button;
9
10 public class MainActivity extends AppCompatActivity {
11
12 Button but;
13
14 @Override
15 protected void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.activity_main);
18
19 but=(Button) findViewById(R.id.button);
20
21 but.setOnClickListener(new View.OnClickListener() {
22 @Override
23 public void onClick(View view) {
24 Intent shareIntent = new
25 Intent(android.content.Intent.ACTION_SEND);
26 shareIntent.setType("text/plain");
27 shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Insert Subject here");
28 String app_url = " https://www.google.co.in";
29 shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,app_url);
30 startActivity(Intent.createChooser(shareIntent, "Share via"));
31 }
32 });
33
34 }
35 }
Unit-3 Android User Interface Design
30. AlertDialog
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <android.support.constraint.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context="example.com.kotlinalertdialog.MainActivity">
9
10 <Button
11 android:id="@+id/button"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_marginBottom="8dp"
15 android:layout_marginEnd="8dp"
16 android:layout_marginStart="8dp"
17 android:layout_marginTop="8dp"
18 android:text="@string/button"
19 app:layout_constraintBottom_toBottomOf="parent"
20 app:layout_constraintEnd_toEndOf="parent"
21 app:layout_constraintStart_toStartOf="parent"
22 app:layout_constraintTop_toTopOf="parent" />
23
24 </android.support.constraint.ConstraintLayout>
----------------------------------------------------------------
strings.xml
-----------
1 <resources>
2 <string name="app_name">Kotlin AlertDialog</string>
3 <string name="button">click button</string>
4 <string name="dialogTitle">Delete File</string>
5 <string name="dialogMessage">Deleting file may be harm your system</string>
6
7 </resources>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package example.com.kotlinalertdialog
2
3 import android.support.v7.app.AppCompatActivity
4 import android.os.Bundle
5 import android.support.v7.app.AlertDialog
6 import android.widget.Button
7 import android.widget.Toast
8
9 class MainActivity : AppCompatActivity() {
10
11 override fun onCreate(savedInstanceState: Bundle?) {
12 super.onCreate(savedInstanceState)
13 setContentView(R.layout.activity_main)
14
15 val button = findViewById<Button>(R.id.button)
16
17 button.setOnClickListener {
18 val builder = AlertDialog.Builder(this)
19 //set title for alert dialog
20 builder.setTitle(R.string.dialogTitle)
21 //set message for alert dialog
22 builder.setMessage(R.string.dialogMessage)
23 builder.setIcon(android.R.drawable.ic_dialog_alert)
Page 29 of 48
CS-31 Mobile Application Development in Android using Kotlin
24
25 //performing positive action
26 builder.setPositiveButton("Yes"){dialogInterface, which ->
27 Toast.makeText(applicationContext,"clicked
28 yes",Toast.LENGTH_LONG).show()
29 }
30 //performing cancel action
31 builder.setNeutralButton("Cancel"){dialogInterface , which ->
32 Toast.makeText(applicationContext,"clicked cancel\n operation
33 cancel",Toast.LENGTH_LONG).show()
34 }
35 //performing negative action
36 builder.setNegativeButton("No"){dialogInterface, which ->
37 Toast.makeText(applicationContext,"clicked
38 No",Toast.LENGTH_LONG).show()
39 }
40 // Create the AlertDialog
41 val alertDialog: AlertDialog = builder.create()
42 // Set other dialog properties
43 alertDialog.setCancelable(false)
44 alertDialog.show()
45 }
46 }
48 }
Unit – 4

Database Connectivity Using


SQLite and Content Provider
Unit-4 Data Base Connectivity and Content Provider
31. Write Data into External Storage
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 xmlns:tools="http://schemas.android.com/tools"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent"
7 tools:context="example.com.kotlinexternalstoragereadwrite.MainActivity">
8
9
10 <TextView
11 android:id="@+id/textView"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_alignLeft="@+id/textView2"
15 android:layout_alignParentTop="true"
16 android:layout_alignStart="@+id/textView2"
17 android:layout_marginTop="68dp"
18 android:text="File Name"
19 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
20 app:layout_constraintBottom_toBottomOf="parent"
21 app:layout_constraintEnd_toEndOf="parent"
22 app:layout_constraintHorizontal_bias="0.027"
23 app:layout_constraintStart_toStartOf="parent"
24 app:layout_constraintTop_toTopOf="parent"
25 app:layout_constraintVertical_bias="0.065" />
26
27 <TextView
28 android:id="@+id/textView2"
29 android:layout_width="wrap_content"
30 android:layout_height="wrap_content"
31 android:layout_alignBottom="@+id/editTextData"
32 android:layout_alignParentLeft="true"
33 android:layout_alignParentStart="true"
34 android:layout_marginBottom="36dp"
35 android:layout_marginLeft="50dp"
36 android:layout_marginStart="50dp"
37 android:text="File Data"
38 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
39 app:layout_constraintBottom_toBottomOf="parent"
40 app:layout_constraintEnd_toEndOf="parent"
41 app:layout_constraintHorizontal_bias="0.027"
42 app:layout_constraintStart_toStartOf="parent"
43 app:layout_constraintTop_toBottomOf="@+id/textView"
44 app:layout_constraintVertical_bias="0.167" />
45
46 <EditText
47 android:id="@+id/editTextFile"
48 android:layout_width="wrap_content"
49 android:layout_height="wrap_content"
50 android:layout_alignLeft="@+id/editTextData"
51 android:layout_alignStart="@+id/editTextData"
52 android:layout_alignTop="@+id/textView"
53 android:ems="10"
54 android:inputType="none" />
55
56 <EditText
57 android:id="@+id/editTextData"
58 android:layout_width="wrap_content"
59 android:layout_height="wrap_content"
60 android:layout_alignParentEnd="true"
Page 32 of 48
Unit-4 Data Base Connectivity and Content Provider
61 android:layout_alignParentRight="true"
62 android:layout_below="@+id/editTextFile"
63 android:layout_marginEnd="37dp"
64 android:layout_marginRight="37dp"
65 android:layout_marginTop="30dp"
66 android:ems="10"
67 android:inputType="none"
68 android:lines="5" />
69
70 <Button
71 android:id="@+id/button_save"
72 android:layout_width="wrap_content"
73 android:layout_height="wrap_content"
74 android:layout_alignParentBottom="true"
75 android:layout_marginBottom="68dp"
76 android:layout_toLeftOf="@+id/editTextData"
77 android:layout_toStartOf="@+id/editTextData"
78 android:text="Save" />
79
80 <Button
81 android:id="@+id/button_view"
82 android:layout_width="wrap_content"
83 android:layout_height="wrap_content"
84 android:layout_alignBottom="@+id/button_save"
85 android:layout_alignEnd="@+id/editTextData"
86 android:layout_alignRight="@+id/editTextData"
87 android:layout_marginEnd="43dp"
88 android:layout_marginRight="43dp"
89 android:text="View" />
90
91 </RelativeLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package example.com.kotlinexternalstoragereadwrite
2
3 import android.support.v7.app.AppCompatActivity
4 import android.os.Bundle
5 import android.view.View
6 import android.widget.Button
7 import android.widget.EditText
8 import android.widget.Toast
9 import android.os.Environment
10 import java.io.*
11
12 class MainActivity : AppCompatActivity() {
13 private val filepath = "MyFileStorage"
14 internal var myExternalFile: File?=null
15 private val isExternalStorageReadOnly: Boolean get() {
16 val extStorageState = Environment.getExternalStorageState()
17 return if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
18 true
19 } else {
20 false
21 }
22 }
23 private val isExternalStorageAvailable: Boolean get() {
24 val extStorageState = Environment.getExternalStorageState()
25 return if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
26 true
27 } else{
28 false
29 }

Page 33 of 48
CS-31 Mobile Application Development in Android using Kotlin
30 }
31
32 override fun onCreate(savedInstanceState: Bundle?) {
33 super.onCreate(savedInstanceState)
34 setContentView(R.layout.activity_main)
35 val fileName = findViewById(R.id.editTextFile) as EditText
36 val fileData = findViewById(R.id.editTextData) as EditText
37 val saveButton = findViewById<Button>(R.id.button_save) as Button
38 val viewButton = findViewById(R.id.button_view) as Button
39
40 saveButton.setOnClickListener(View.OnClickListener {
41 myExternalFile = File(getExternalFilesDir(filepath),
fileName.text.toString())
42 try {
43 val fileOutPutStream = FileOutputStream(myExternalFile)
44 fileOutPutStream.write(fileData.text.toString().toByteArray())
45 fileOutPutStream.close()
46 } catch (e: IOException) {
47 e.printStackTrace()
48 }
49 Toast.makeText(applicationContext,"data save",Toast.LENGTH_SHORT).show()
50 })
51 viewButton.setOnClickListener(View.OnClickListener {
52 myExternalFile = File(getExternalFilesDir(filepath),
fileName.text.toString())
53
54 val filename = fileName.text.toString()
55 myExternalFile = File(getExternalFilesDir(filepath),filename)
56 if(filename.toString()!=null && filename.toString().trim()!=""){
57 var fileInputStream =FileInputStream(myExternalFile)
58 var inputStreamReader: InputStreamReader =
InputStreamReader(fileInputStream)
59 val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)
60 val stringBuilder: StringBuilder = StringBuilder()
61 var text: String? = null
62 while ({ text = bufferedReader.readLine(); text }() != null) {
63 stringBuilder.append(text)
64 }
65 fileInputStream.close()
66 //Displaying data on EditText
67
Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_SHORT).show()
68 }
69 })
70
71 if (!isExternalStorageAvailable || isExternalStorageReadOnly) {
72 saveButton.isEnabled = false
73 }
74 }
75 }
---------------------------------------------------------------------------------
AndroidManifest.xml
1 ---------------------
2 <?xml version="1.0" encoding="utf-8"?>
3 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
4 package="example.javatpoint.com.kotlinexternalstoragereadwrite">
5 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
6 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
7 <application
8 android:allowBackup="true"
9 android:icon="@mipmap/ic_launcher"
10 android:label="@string/app_name"
11 android:roundIcon="@mipmap/ic_launcher_round"
12 android:supportsRtl="true"
Unit-4 Data Base Connectivity and Content Provider
13 android:theme="@style/AppTheme">
14 <activity android:name=".MainActivity">
15 <intent-filter>
16 <action android:name="android.intent.action.MAIN" />
17
18 <category android:name="android.intent.category.LAUNCHER" />
19 </intent-filter>
20 </activity>
21 </application>
22
</manifest>

32. SharedPreferences
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <android.support.constraint.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context="example.com.kotlinsharedpreference.MainActivity">
9
10 <TableLayout
11 android:layout_width="368dp"
12 android:layout_height="495dp"
13 android:layout_marginBottom="8dp"
14 android:layout_marginEnd="8dp"
15 android:layout_marginStart="8dp"
16 android:layout_marginTop="8dp"
Page 35 of 48
CS-31 Mobile Application Development in Android using Kotlin
17 app:layout_constraintBottom_toBottomOf="parent"
18 app:layout_constraintEnd_toEndOf="parent"
19 app:layout_constraintStart_toStartOf="parent"
20 app:layout_constraintTop_toTopOf="parent">
21 <TableRow>
22 <TextView
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:layout_column="0"
26 android:layout_marginLeft="10sp"
27 android:layout_marginStart="10sp"
28 android:text="Enter Id"
29 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
30 <EditText
31 android:id="@+id/editId"
32 android:layout_width="201dp"
33 android:layout_height="wrap_content"
34 android:layout_column="1"
35 android:layout_marginLeft="50sp"
36 android:layout_marginStart="50sp"
37 android:hint="id"
38 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
39 </TableRow>
40 <TableRow>
41
42 <TextView
43 android:layout_width="wrap_content"
44 android:layout_height="wrap_content"
45 android:layout_column="0"
46 android:layout_marginLeft="10sp"
47 android:layout_marginStart="10sp"
48 android:text="Enter Name"
49 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
50
51 <EditText
52 android:id="@+id/editName"
53 android:layout_width="wrap_content"
54 android:layout_height="wrap_content"
55 android:layout_column="1"
56 android:layout_marginLeft="50sp"
57 android:layout_marginStart="50sp"
58 android:hint="name"
59 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
60 </TableRow>
61 <TableRow android:layout_marginTop="60dp">
62
63 <TextView
64 android:layout_width="wrap_content"
65 android:layout_height="wrap_content"
66 android:layout_column="0"
67 android:layout_marginLeft="10sp"
68 android:layout_marginStart="10sp"
69 android:text="Your Id"
70 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
71 <TextView
72 android:id="@+id/textViewShowId"
73 android:layout_width="wrap_content"
74 android:layout_height="wrap_content"
75 android:layout_column="1"
Unit-4 Data Base Connectivity and Content Provider
76 android:layout_marginLeft="50sp"
77 android:layout_marginStart="50sp"
78 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
79 />
</TableRow>
80 <TableRow android:layout_marginTop="20dp">
81 <TextView
82 android:layout_width="wrap_content"
83 android:layout_height="wrap_content"
84 android:layout_column="0"
85 android:layout_marginLeft="10sp"
86 android:layout_marginStart="10sp"
87 android:text="Your Name"
88 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>
89 <TextView
90 android:id="@+id/textViewShowName"
91 android:layout_width="wrap_content"
92 android:layout_height="wrap_content"
93 android:layout_column="1"
94 android:layout_marginLeft="50sp"
95 android:layout_marginStart="50sp"
96 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
97 />
98 </TableRow>
99 </TableLayout>
100
101 <LinearLayout
102 android:layout_width="fill_parent"
103 android:layout_height="wrap_content"
104 android:layout_marginBottom="16dp"
105 android:layout_marginEnd="8dp"
106 android:layout_marginStart="8dp"
107 android:orientation="horizontal"
108 android:gravity="center"
109 app:layout_constraintBottom_toBottomOf="parent"
110 app:layout_constraintEnd_toEndOf="parent"
111 app:layout_constraintHorizontal_bias="0.0"
112 app:layout_constraintStart_toStartOf="parent">
113 <Button
114 android:id="@+id/save"
115 android:layout_width="wrap_content"
116 android:layout_height="wrap_content"
117 android:text="Save" />
118 <Button
119 android:id="@+id/view"
120 android:layout_width="wrap_content"
121 android:layout_height="wrap_content"
122 android:text="View" />
123 <Button
124 android:id="@+id/clear"
125 android:layout_width="wrap_content"
126 android:layout_height="wrap_content"
127 android:text="Clear" />
128 </LinearLayout>
129 </android.support.constraint.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package example.com.kotlinsharedpreference
2
3 import android.content.Context
4 import android.content.SharedPreferences

Page 37 of 48
CS-31 Mobile Application Development in Android using Kotlin
5 import android.support.v7.app.AppCompatActivity
6 import android.os.Bundle
7 import android.view.View
8 import android.widget.Button
9 import android.widget.EditText
10 import android.widget.TextView
11
12
13
14 class MainActivity : AppCompatActivity() {
15
16 private val sharedPrefFile = "kotlinsharedpreference"
17
18 override fun onCreate(savedInstanceState: Bundle?) {
19 super.onCreate(savedInstanceState)
20 setContentView(R.layout.activity_main)
21
22 val inputId = findViewById<EditText>(R.id.editId)
23 val inputName = findViewById<EditText>(R.id.editName)
24 val outputId = findViewById<TextView>(R.id.textViewShowId)
25 val outputName = findViewById<TextView>(R.id.textViewShowName)
26
27 val btnSave = findViewById<Button>(R.id.save)
28 val btnView = findViewById<Button>(R.id.view)
29 val btnClear = findViewById<Button>(R.id.clear)
30 val sharedPreferences: SharedPreferences =
31 this.getSharedPreferences(sharedPrefFile,Context.MODE_PRIVATE)
32 btnSave.setOnClickListener(View.OnClickListener {
33 val id:Int = Integer.parseInt(inputId.text.toString())
34 val name:String = inputName.text.toString()
35 val editor:SharedPreferences.Editor = sharedPreferences.edit()
36 editor.putInt("id_key",id)
37 editor.putString("name_key",name)
38 editor.apply()
39 editor.commit()
40 })
41 btnView.setOnClickListener {
42 val sharedIdValue = sharedPreferences.getInt("id_key",0)
43 val sharedNameValue =
44 sharedPreferences.getString("name_key","defaultname")
45 if(sharedIdValue.equals(0) && sharedNameValue.equals("defaultname")){
46 outputName.setText("default name: ${sharedNameValue}").toString()
48 outputId.setText("default id: ${sharedIdValue.toString()}")
49 }else{
50 outputName.setText(sharedNameValue).toString()
51 outputId.setText(sharedIdValue.toString())
52 }
53
54 }
55 btnClear.setOnClickListener(View.OnClickListener {
56 val editor = sharedPreferences.edit()
57 editor.clear()
58 editor.apply()
59 outputName.setText("").toString()
60 outputId.setText("".toString())
61 })
62 }
63 }
Unit-4 Data Base Connectivity and Content Provider

33. SQLite Example


MainActivity.kt
----------------
1 package com.example.sqlitedemojava;
2
3 import androidx.appcompat.app.AppCompatActivity;
4
5 import android.os.Bundle;
6 import android.util.Log;
7
8 import java.util.List;
9
10 public class MainActivity extends AppCompatActivity {
11
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_main);
16
17 DatabaseHandler db = new DatabaseHandler(this);
18
19 // Inserting Contacts
20 Log.d("Insert: ", "Inserting ..");
21 db.addContact(new Contact("Ravi", "9100000000"));
22 db.addContact(new Contact("Srinivas", "9199999999"));
23 db.addContact(new Contact("Tommy", "9522222222"));
24 db.addContact(new Contact("Karthik", "9533333333"));
25
26 // Reading all contacts
27 Log.d("Reading: ", "Reading all contacts..");
28 List<Contact> contacts = db.getAllContacts();
29
30 for (Contact cn : contacts) {
31 String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone:
" +
32 cn.getPhoneNumber();

Page 39 of 48
CS-31 Mobile Application Development in Android using Kotlin
33 // Writing Contacts to log
34 Log.d("Name: ", log);
35 }
36
37 }
38 }
---------------------------------------------------------------------------
DatabaseHandler.java
---------------------
1 package com.example.sqlitedemojava;
2
3 import android.content.ContentValues;
4 import android.content.Context;
5 import android.database.Cursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.database.sqlite.SQLiteOpenHelper;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 public class DatabaseHandler extends SQLiteOpenHelper {
12 private static final int DATABASE_VERSION = 1;
13 private static final String DATABASE_NAME = "contactsManager";
14 private static final String TABLE_CONTACTS = "contacts";
15 private static final String KEY_ID = "id";
16 private static final String KEY_NAME = "name";
17 private static final String KEY_PH_NO = "phone_number";
18
19 public DatabaseHandler(Context context) {
20 super(context, DATABASE_NAME, null, DATABASE_VERSION);
21 //3rd argument to be passed is CursorFactory instance
22 }
23 // Creating Tables
24 @Override
25 public void onCreate(SQLiteDatabase db) {
26 String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
27 + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
28 + KEY_PH_NO + " TEXT" + ")";
29 db.execSQL(CREATE_CONTACTS_TABLE);
30 }
31 // Upgrading database
32 @Override
33 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
34 // Drop older table if existed
35 db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
36
37 // Create tables again
38 onCreate(db);
39 }
40 // code to add the new contact
41 void addContact(Contact contact) {
42 SQLiteDatabase db = this.getWritableDatabase();
43
44 ContentValues values = new ContentValues();
45 values.put(KEY_NAME, contact.getName()); // Contact Name
46 values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
47 // Inserting Row
48 db.insert(TABLE_CONTACTS, null, values);
49 //2nd argument is String containing nullColumnHack
50 db.close(); // Closing database connection
51 }
52 // code to get the single contact
53 Contact getContact(int id) {
54 SQLiteDatabase db = this.getReadableDatabase();
55
Unit-4 Data Base Connectivity and Content Provider
56 Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
57 KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
58 new String[] { String.valueOf(id) }, null, null, null, null);
59 if (cursor != null)
60 cursor.moveToFirst();
61
62 Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
63 cursor.getString(1), cursor.getString(2));
64 // return contact
65 return contact;
66 }
67 // code to get all contacts in a list view
68 public List<Contact> getAllContacts() {
69 List<Contact> contactList = new ArrayList<Contact>();
70 // Select All Query
71 String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
72
73 SQLiteDatabase db = this.getWritableDatabase();
74 Cursor cursor = db.rawQuery(selectQuery, null);
75
76 // looping through all rows and adding to list
77 if (cursor.moveToFirst()) {
78 do {
79 Contact contact = new Contact();
80 contact.setID(Integer.parseInt(cursor.getString(0)));
81 contact.setName(cursor.getString(1));
82 contact.setPhoneNumber(cursor.getString(2));
83 // Adding contact to list
84 contactList.add(contact);
85 } while (cursor.moveToNext());
86 }
87 // return contact list
88 return contactList;
89 }
90 // code to update the single contact
91 public int updateContact(Contact contact) {
92 SQLiteDatabase db = this.getWritableDatabase();
93
94 ContentValues values = new ContentValues();
95 values.put(KEY_NAME, contact.getName());
96 values.put(KEY_PH_NO, contact.getPhoneNumber());
97
98 // updating row
99 return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
100 new String[] { String.valueOf(contact.getID()) });
101 }
102 // Deleting single contact
103 public void deleteContact(Contact contact) {
104 SQLiteDatabase db = this.getWritableDatabase();
105 db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
106 new String[] { String.valueOf(contact.getID()) });
107 db.close();
108 }
109 // Getting contacts Count
110 public int getContactsCount() {
112 String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
113 SQLiteDatabase db = this.getReadableDatabase();
114 Cursor cursor = db.rawQuery(countQuery, null);
115 cursor.close();
116 // return count
117 return cursor.getCount();
118 }
119 }

Page 41 of 48
CS-31 Mobile Application Development in Android using Kotlin
----------------------------------------------------------------------------
Contact.java
------------
1 package com.example.sqlitedemojava;
2
3 public class Contact {
4 int _id;
5 String _name;
6 String _phone_number;
7 public Contact(){ }
8 public Contact(int id, String name, String _phone_number){
9 this._id = id;
10 this._name = name;
11 this._phone_number = _phone_number;
12 }
13 public Contact(String name, String _phone_number){
14 this._name = name;
15 this._phone_number = _phone_number;
16 }
17 public int getID(){
18 return this._id;
19 }
20 public void setID(int id){
21 this._id = id;
22 }
23 public String getName(){
24 return this._name;
25 }
26 public void setName(String name){
27 this._name = name;
28 }
29 public String getPhoneNumber(){
30 return this._phone_number;
31 }
32 public void setPhoneNumber(String phone_number){
33 this._phone_number = phone_number;
34 }
35 }
Unit-5 Common Android API

Unit – 5

Location Based Services (LBS),


Common Android API,
Notifications, Services,
Deployment of applications

Page 43 of 48
CS-31 Mobile Application Development in Android using Kotlin
34. Android device vibrate programmatically
activity_main.xml
------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <androidx.constraintlayout.widget.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context=".MainActivity">
9
10 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
11 xmlns:tools="http://schemas.android.com/tools"
12 android:layout_width="match_parent"
13 android:layout_height="match_parent"
14 tools:context=".MainActivity">
15 <TextView
16 android:layout_width="wrap_content"
17 android:layout_height="wrap_content"
18 android:layout_centerHorizontal="true"
19 android:layout_marginTop="70dp"
20 android:background="#008080"
21 android:padding="5dp"
22 android:text="Vibrate Device"
23 android:textColor="#fff"
24 android:textSize="24sp"
25 android:textStyle="bold" />
26 <TextView
27 android:id="@+id/textView"
28 android:layout_width="wrap_content"
29 android:layout_height="wrap_content"
30 android:layout_centerInParent="true"
31 android:textColor="@android:color/holo_blue_dark"
32 android:textSize="24sp"
33 android:textStyle="bold" />
34 </RelativeLayout>
35
36 </androidx.constraintlayout.widget.ConstraintLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.vibratedevicekotlin
2
3 import android.content.Context
4 import android.os.Build
5 import androidx.appcompat.app.AppCompatActivity
6 import android.os.Bundle
7 import android.os.VibrationEffect
8 import android.os.Vibrator
9
10 @Suppress("DEPRECATION")
11 class MainActivity : AppCompatActivity() {
12 override fun onCreate(savedInstanceState: Bundle?) {
13 super.onCreate(savedInstanceState)
14 setContentView(R.layout.activity_main)
15
16 title = "KotlinApp"
17 val v = (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator)
18 // Vibrate for 500 milliseconds
19 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
20
21 v.vibrate(VibrationEffect.createOneShot(500,VibrationEffect.DEFAULT_AMPLITUDE))
Unit-5 Common Android API
22 }
23 else {
24 v.vibrate(500)
25 }
26 }
27 }
---------------------------------------------------------------------------
AndroidManifest.xml
---------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:tools="http://schemas.android.com/tools">
4
5 <uses-permission android:name="android.permission.VIBRATE" />
6 <application
7 android:allowBackup="true"
8 android:dataExtractionRules="@xml/data_extraction_rules"
9 android:fullBackupContent="@xml/backup_rules"
10 android:icon="@mipmap/ic_launcher"
11 android:label="@string/app_name"
12 android:roundIcon="@mipmap/ic_launcher_round"
13 android:supportsRtl="true"
14 android:theme="@style/Theme.VibrateDeviceKotlin"
15 tools:targetApi="31">
16 <activity
17 android:name=".MainActivity"
18 android:exported="true">
19 <intent-filter>
20 <action android:name="android.intent.action.MAIN" />
21 <category android:name="android.intent.category.LAUNCHER" />
22 </intent-filter>
23 <meta-data
24 android:name="android.app.lib_name"
25 android:value="" />
26 </activity>
27 </application>
28 </manifest>

Page 45 of 48
CS-31 Mobile Application Development in Android using Kotlin
35. Android telephony api
activity_main.xml
------------------
1 <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:paddingBottom="@dimen/activity_vertical_margin"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin"
9 tools:context=".MainActivity" >
10
11 <TextView
12 android:id="@+id/textView1"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:layout_alignParentLeft="true"
16 android:layout_alignParentTop="true"
17 android:layout_marginLeft="38dp"
18 android:layout_marginTop="30dp"
19 android:text="Phone Details:" />
20
21 </RelativeLayout>
----------------------------------------------------------------
MainActivity.kt
----------------
1 package com.example.telephonyapi
2
3 import android.os.Bundle;
4 import android.app.Activity;
5 import android.content.Context;
6 import android.telephony.TelephonyManager;
7 import android.view.Menu;
8 import android.widget.TextView;
9
10 public class MainActivity extends Activity {
11 TextView textView1;
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_main);
16
17 textView1=(TextView)findViewById(R.id.textView1);
18
19 //Get the instance of TelephonyManager
20 TelephonyManager
tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
21
22 //Calling the methods of TelephonyManager the returns the information
23 String IMEINumber=tm.getDeviceId();
24 String subscriberID=tm.getDeviceId();
25 String SIMSerialNumber=tm.getSimSerialNumber();
26 String networkCountryISO=tm.getNetworkCountryIso();
27 String SIMCountryISO=tm.getSimCountryIso();
28 String softwareVersion=tm.getDeviceSoftwareVersion();
29 String voiceMailNumber=tm.getVoiceMailNumber();
30
31 //Get the phone type
32 String strphoneType="";
33
34 int phoneType=tm.getPhoneType();
35
Unit-5 Common Android API
36 switch (phoneType)
37 {
38 case (TelephonyManager.PHONE_TYPE_CDMA):
39 strphoneType="CDMA";
40 break;
41 case (TelephonyManager.PHONE_TYPE_GSM):
42 strphoneType="GSM";
43 break;
44 case (TelephonyManager.PHONE_TYPE_NONE):
45 strphoneType="NONE";
46 break;
47 }
48
49 //getting information if phone is in roaming
50 boolean isRoaming=tm.isNetworkRoaming();
51
52 String info="Phone Details:\n";
53 info+="\n IMEI Number:"+IMEINumber;
54 info+="\n SubscriberID:"+subscriberID;
55 info+="\n Sim Serial Number:"+SIMSerialNumber;
56 info+="\n Network Country ISO:"+networkCountryISO;
57 info+="\n SIM Country ISO:"+SIMCountryISO;
58 info+="\n Software Version:"+softwareVersion;
59 info+="\n Voice Mail Number:"+voiceMailNumber;
60 info+="\n Phone Network Type:"+strphoneType;
61 info+="\n In Roaming? :"+isRoaming;
62
63 textView1.setText(info);//displaying the information in the textView
64 }
65 }
---------------------------------------------------------------------------
AndroidManifest.xml
---------------------
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3 package="com.javatpoint.telephonymanager"
4 android:versionCode="1"
5 android:versionName="1.0" >
6
7 <uses-sdk
8 android:minSdkVersion="8"
9 android:targetSdkVersion="17" />
10
11 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
12
13 <application
14 android:allowBackup="true"
15 android:icon="@drawable/ic_launcher"
16 android:label="@string/app_name"
17 android:theme="@style/AppTheme" >
18 <activity
19 android:name="com.javatpoint.telephonymanager.MainActivity"
20 android:label="@string/app_name" >
21 <intent-filter>
22 <action android:name="android.intent.action.MAIN" />
23
24 <category android:name="android.intent.category.LAUNCHER" />
25 </intent-filter>
26 </activity>
27 </application>
28 </manifest>

Page 47 of 48
CS-31 Mobile Application Development in Android using Kotlin

You might also like