Advance Mobile Programming
Advance Mobile Programming
Advance Mobile Programming
UNIVERSITY OF MUMBAI
Reference Manual
Subject: Advanced Mobile Programming
Practical
package com.practical.hello
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
4 | Page
Create and manage virtual devices:
To open the AVD Manager, do one of the following:
• Select Tools > AVD Manager.
• Click AVD Manager AVD Manager icon in the toolbar.
5 | Page
6 | Page
Output:
7 | Page
PRACTICAL 2
Programming Resources
Q. Insert the new contents in the following resources and demonstrate their uses in
the android application
Android Resources: (Color, Theme, String, Drawable, Dimension, Image)
Solution:
Color:
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
8 | Page
Theme:
style.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyApplication"
parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor"
tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
String:
9 | Page
string.xml:
<resources>
<string name="app_name">My Application</string>
<string name="numbers">
<item>1</item>
<item>2</item>
<item>3</item>
</string>
</resources>
Drawable:
1. Right click on drawable folder
10 | P a g e
Note: to create drawable resource, right click on drawable folder and select drawableresource file
11 | P a g e
MainActivity.Kt
package com.practical2.drwable
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output:
12 | P a g e
PRACTICAL 3
Programming Activities and fragments
Activity Life Cycle, Activity methods, Multiple Activities, Life Cycle of fragments and
multiple fragments.
Activity Lifecycle:
onCreate(): Called by the OS when the activity is first created. This is where you
initialize any UI elements or data objects. You also have the savedInstanceState of the
activity that contains its previously saved state, and you can use it to recreate that state.\
onStart(): Just before presenting the user with an activity, this method is called. It’s
always followed by onResume(). In here, you generally should start UI animations, audio
based content or anything else that requires the activity’s contents to be on screen.
13 | P a g e
onResume(): As an activity enters the foreground, this method is called. Here you have agood
place to restart animations, update UI elements, restart camera previews, resume audio/video
playback or initialize any components that you release during onPause().
onPause(): This method is called before sliding into the background. Here you should stop any
visuals or audio associated with the activity such as UI animations, music playback or the camera.
This method is followed by onResume() if the activity returns tothe foreground or by onStop() if it
becomes hidden.
onStop(): This method is called right after onPause(), when the activity is no longer visible to the
user, and it’s a good place to save data that you want to commit to the disk.It’s followed by either
onRestart(), if this activity is coming back to the foreground, or onDestroy() if it’s being released
from memory.
onRestart(): Called after stopping an activity, but just before starting it again. It’s alwaysfollowed
by onStart().
onDestroy(): This is the final callback you’ll receive from the OS before the activity is destroyed.
You can trigger an activity’s desctruction by calling finish(), or it can be triggered by the system
when the system needs to recoup memory. If your activity includes any background threads or
other long-running resources, destruction could lead to a memory leak if they’re not released, so
you need to remember to stop these processeshere as well.
14 | P a g e
MainActivity.kt
package com.example.activitylifecycle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity LifeCycle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output:
16 | P a g e
Q. Create an android application with two Fragments and load them on the click
of Button’s. Display two Button’s and a FrameLayout in our Activity and perform
setOnClickListener event on both Button’s. On the click of First Button replace
the First Fragment and on click of Second Button we replace the Second Fragment
with the layout(FrameLayout).
FragmentOne.xml
<TextView
android:text="Fragment One"
android:layout_width="wrap_content"
android:layout_marginTop="230dp"
android:layout_marginLeft="145dp"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textColor="#000000"
android:textStyle="bold"
tools:text="Fragment One"
android:textSize="18sp"
android:visibility="visible"
android:background="@color/purple_200"/>
<ImageView
android:layout_width="197dp"
android:layout_height="328dp"
android:src="@drawable/aa"
android:layout_marginTop="200dp"
android:layout_marginLeft="95dp"
android:id="@+id/imageView2"
android:visibility="visible"/>
</RelativeLayout>
17 | P a g e
FragmentTwo.xml
<TextView
android:text="Fragment Two"
android:layout_width="wrap_content"
android:layout_marginTop="230dp"
android:layout_marginLeft="145dp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textSize="18sp"
android:visibility="visible"
android:textStyle="bold"/>
<ImageView
android:layout_width="209dp"
android:layout_height="296dp"
android:layout_marginTop="200dp"
android:layout_marginLeft="95dp"
android:src="@drawable/bb"
android:id="@+id/imageView"/>
</RelativeLayout>
FragmentOne.kt
18 | P a g e
package com.example.fragments
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
19 | P a g e
FragmentTwo.kt
package com.example.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
20 | P a g e
activity_main.xml
<Button
android:id="@+id/btn_change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Change Fragment"
android:textAllCaps="false"/>
<FrameLayout
android:id="@+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
21 | P a g e
MainActivity.kt
package com.example.fragments
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
fun showFragmentOne() {
val transaction = manager.beginTransaction()
val fragment = FragmentOne()
transaction.replace(R.id.fragment_holder, fragment)
transaction.addToBackStack(null)
transaction.commit()
isFragmentOneLoaded = true
}
fun showFragmentTwo() {
val transaction = manager.beginTransaction()
val fragment = FragmentTwo()
transaction.replace(R.id.fragment_holder, fragment)
transaction.addToBackStack(null)
transaction.commit()
isFragmentOneLoaded = false
}
}
22 | P a g e
PRACTICAL 4
Programs related to different Layouts
Q. Create an android application using linear layout and insert 10 games in the list view and
display the selected game in the text view.
activity_main.xml
<TextView
android:text="List View"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:id="@+id/textView5"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myList"/>
</LinearLayout>
23 | P a g e
MainActivity.kt
package com.example.listview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
myListView.adapter= ArrayAdapter<String>(this,android.R.layout.
simple_list_item_1,subjects)
myListView.setOnItemClickListener { parent, view,
position, id ->
Toast.makeText(this,"Clicked:\n"+subjects[position],
Toast.LENGTH_SHORT).show()
myDispLabel.text = subjects[position]
}
}
}
Q. Create an android application using grid view layout and insert 6 images of different
animals as the items and toast the animal name by clicking the image.
activity_main.xml
24 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<GridLayout 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"
android:columnCount="3"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img1"
android:id="@+id/imageView1"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img2"
android:id="@+id/imageView2"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img3"
android:id="@+id/imageView3"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img4"
android:id="@+id/imageView4"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img5"
android:id="@+id/imageView5"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img6"
android:id="@+id/imageView6"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
</GridLayout>
25 | P a g e
Q. Create the standard calculator application in android
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="DEL" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="C" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="%" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="+" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="/" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
[…] 26 | P a g e
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
activity_main.xml
package com.example.tablelayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
Output
27 | P a g e
PRACTICAL 5
Programing UI Elements
1. Create an android application with customised appbar. Insert search and file
buttons in it and toast the appropriate message on clicking the buttons (add new
color in color.xml and use that color for appbar).
28 | P a g e
menu.xml
activity_main.xml
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">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Menus"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
29 | P a g e
MainActivity.kt
package com.example.appbar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
Output
30 | P a g e
PRACTICAL 6
Programming menus, dialog, dialog fragments
Q. Create an android application for the following menu items, the approriate toast should appear by
clicking on the item : Also create sub-menu
• Settings
• Search
• Compose Email
• FeedBack
Make compose email disabled
menu.xml
31 | P a g e
activity_main.xml
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">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Menus"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
32 | P a g e
MainActivity.kt
package com.example.appbar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
33 | P a g e
Output
Q. Create an android application to display Alert Dialog on pressing the Back button .
activity_main.xml
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">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Press the back button of your phone"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
34 | P a g e
MainActivity.kt
Output
package com.example.alertdialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
// Declare the onBackPressed method when the back button is pressed this
method will call
override fun onBackPressed() {
// Create the object of AlertDialog Builder class
val builder = AlertDialog.Builder(this)
// Set the message show for the Alert time
builder.setMessage("Do you want to exit ?")
// Set Alert Title
builder.setTitle("Alert !")
// Set Cancelable false for when the user clicks on the outside the
Dialog Box then it will remain show
builder.setCancelable(false)
// Set the positive button with yes name Lambda OnClickListener method
is use of DialogInterface interface.
builder.setPositiveButton("Yes") {
// When the user click yes button then app will close
dialog, which ->
finish()
}
35 | P a g e
36 | P a g e
PRACTICAL 7
Programs on Intents, Events Listeners and Adapters
Q. Create an android application to pass the data from current application to another
application using intent.
Create 2 activities
37 | P a g e
38 | P a g e
activity_main.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiple Activities"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.14" />
<Button
android:id="@+id/activity1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="172dp"
android:text="Activity 1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/activity2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Activity 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/activity1" />
</androidx.constraintlayout.widget.ConstraintLayout>
39 | P a g e
MainActivity.kt
package com.example.multipleactivities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
activity_main2.xml
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
40 | P a g e
MainActivity2.kt
package com.example.multipleactivities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
activity_main3.xml
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
41 | P a g e
MainActivity3.kt
package com.example.multipleactivities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
42 | P a g e
Practical 8
Programs on Services, notification and broadcast
receivers
Q. Create an android application which automatically notify the user when
Aeroplane mode is turned on or off using broadcast receiver.
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_name"
android:textSize="80dp"
android:textColor="@color/purple_200"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
43 | P a g e
AndroidManifest.xml
</manifest>
44 | P a g e
MainActivity.kt
package com.example.broadcastreceiver
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.net.ConnectivityManager
import android.widget.Toast
45 | P a g e
Output
activity_main.xml
46 | P a g e
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/playSound"
android:onClick="PlayBackgroundSound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Run background Sound"/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:text="Playing Music in Background"/>
</LinearLayout>
47 | P a g e
BackgrounService.java
package com.example.backgroundservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public void onLowMemory() {
}
}
48 | P a g e
MainActivity.kt
package com.example.backgroundservice
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
AndroidManifest.xml
<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.BroadcastReceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
49 | P a g e
Q. Create an android application to generate notification
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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:id="@+id/btn_notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output
50 | P a g e
PRACTICAL 9
Database Programming with SQLite
Q. Create an android application using sqlite database to manage the students data
by using insert, update and delete operations and display the data in scroll view.
Allow user to insert Name and Age of the student.
User.kt
package com.example.database
class User {
var id : Int = 0
var name : String = ""
var age : Int = 0
constructor(name:String,age:Int){
this.name = name
this.age = age
}
constructor(){
}
51 | P a g e
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"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Name"/>
<EditText
android:id="@+id/etvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Age"/>
<EditText
android:id="@+id/etvAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:inputType="number"
android:padding="10dp" />
<Button
android:id="@+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="10dp"
android:background="@color/purple_200"
android:text="Insert" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">
<Button
android:id="@+id/btn_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/purple_200"
android:layout_margin="4dp"
android:text="Read"/>
<Button
android:id="@+id/btn_update"
android:layout_width="match_parent" 52 | P a g e
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="4dp"
android:background="@color/purple_200"
MainActivity.kt
package com.example.database
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
btn_read.setOnClickListener({
var data = db.readData()
tvResult.text = ""
for (i in 0..(data.size - 1)) {
tvResult.append(
data.get(i).id.toString() + " " + data.get(i).name + " " +
data.get(
i
).age + "\n"
)
}
})
btn_update.setOnClickListener({
db.updateData()
btn_read.performClick()
})
btn_delete.setOnClickListener({
db.deleteData()
btn_read.performClick()
})
}
53 | P a g e
DatabaseHandler.kt
package com.example.database
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
@SuppressLint("Range")
fun readData(): MutableList<User> {
var list: MutableList<User> = ArrayList()
val db = this.readableDatabase
val query = "Select * from " + TABLE_NAME
val result = db.rawQuery(query, null)
if (result.moveToFirst()) {
do {
var user = User()
user.id = result.getString(result.getColumnIndex(COL_ID)).toInt()
user.name = result.getString(result.getColumnIndex(COL_NAME))
user.age = result.getString(result.getColumnIndex(COL_AGE)).toInt()
list.add(user)
} while (result.moveToNext())
}
result.close()
db.close()
return list 54 | P a g e
}
fun deleteData() {
val db = this.writableDatabase
Output
55 | P a g e
PRACTICAL 10
Programming threads, handles and asynchronized
programs
Q. Create an android application to generate any random number with some time
activity_main.xml
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
56 | P a g e
MainActivity.kt
package com.example.thread
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
57 | P a g e
Output
58 | P a g e
PRACTICAL 11
Programming Media API and Telephone API
Q. Create a media API in android to play an audio/video file
activity_main.xml
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/playSound"
android:onClick="PlayBackgroundSound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Run background Sound"/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:text="Playing Music in Background"/>
</LinearLayout>
59 | P a g e
BackgroundService.java
package com.example.backgroundservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public void onLowMemory() {
}
}
60 | P a g e
MainActivity.kt
package com.example.backgroundservice
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
AndroidManifest.xml
<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.BroadcastReceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
61 | P a g e
Output
62 | P a g e
PRACTICAL 12
Programming Security and permissions
Q. Create an android application with two buttons and each will request the permission to
access the device data such as user’s file, camera.
activity_main.xml
<Button
android:id="@+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="140dp"
android:text="Ask permission for Camera"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ask permission for storage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/camera" />
</androidx.constraintlayout.widget.ConstraintLayout>
63 | P a g e
package com.example.permisions
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.Manifest
companion object {
private const val CAMERA_PERMISSION_CODE = 100
private const val STORAGE_PERMISSION_CODE = 101
}
// Defining Buttons
val storage: Button? = findViewById(R.id.storage)
val camera: Button? = findViewById(R.id.camera)
// This function is called when the user accepts or decline the permission.
AndroidManifext.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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.Permisions">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
65 | P a g e
PRACTICAL 13
Programming Network Communications and
Services (JSON)
Handling connectivity errors in Android apps with Kotlin:
Open your build.gradle file and add the following dependencies:
implementation
'com.android.support:design:27.1.1'
implementation
'com.squareup.retrofit2:retrofit:2.3.0'
implementation
'com.squareup.retrofit2:converter-
scalars:2.3.0'
Open your AndroidManifest.xml file and add the permissions like so:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
[…]
</manifest>
When there is a network connection, we will fetch data from an API. Let’s set up an interface to
hold the endpoints we will access. Create a new Kotlin file named ApiService and paste this:
import retrofit2.Call import retrofit2.http.GET
66 | P a g e
For this demo, we are only going to access one endpoint, which is equivalent to our base URL. It’s
for this reason we used a dot instead of the usual /some-url in the @GET annotation.
When these items are fetched, we will display the items in a list. We, therefore, need a
RecyclerView in the layout and a matching adapter. Create a new Kotlin file named
RecyclerAdapter and paste this:
return ViewHolder(view)
}
67 | P a g e
the adapter handles the display of items on a list. It has some overridden methods like:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/no_internet_connection" />
</android.support.constraint.ConstraintLayout>
The layout contains a RecyclerView for our list items and an ImageView to show an error
message.
68 | P a g e
We also need an error message image. Once you have an image, rename the file to
no_internet_connection and save it to your drawable folder:
NameOfProject/app/src/main/res/drawable.
For us to monitor when the connectivity changes, we need broadcast receivers. Broadcast
receivers are components that allow you to register and listen to Android system and application
events. Usually, the Android system sends broadcast events when various system events occur
and your app needs to register to get these events.
Let’s register a listener to be triggered when the internet connection is online or offline.
Open your MainActivity file and paste the following code:
69 | P a g e
Above, we initialized some variables:
After creating the broadcast receiver, we have to register it to get updates and unregister if
there are no more activities. To do this, add the following functions to the code above in the
MainActivity.kt:
70 | P a g e
In the onCreate function, we set up our RecyclerView by calling the setupRecyclerView.
Create a private function in the MainActivity class and set it up like this:
Remember we mentioned the connected and disconnected functions earlier in this post. We
will now add them to the class. Add them to the MainActivity file like so:
The disconnected function is called when there is no network connection. It hides the
RecyclerView and shows the ImageView. The connected function is called when there is an
active internet connection. It shows the RecyclerView, hides the ImageView, and finally calls
the fetchFeeds function.
Next, in the same file, paste the following code:
71 | P a g e
getFeeds()
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable) {
Log.e("MainActivityTag", t.message)
}
})
This function calls the API to get data. When the call is successful, we have
another function that helps us add the title of the posts gotten from the endpoint
to our list and then to our adapter. Create a function named addTitleToList and
set it up like so:
for (i in 0..(children.length()-1)) {
val item =
children.getJSONObject(i).getJSONObject("data").getString("title")
arrayList.add(item)
adapter.setItems(arrayList)
}
}
72 | P a g e