0% found this document useful (0 votes)
101 views57 pages

AY 23-24 TYIT AMP Practical Manual

The document discusses the key components of Android including activities, services, broadcast receivers, content providers and other components. It also describes how to set up the Android development environment, debug apps using logs and breakpoints, and build a simple 'Hello World' Android app.

Uploaded by

newvinayakprints
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views57 pages

AY 23-24 TYIT AMP Practical Manual

The document discusses the key components of Android including activities, services, broadcast receivers, content providers and other components. It also describes how to set up the Android development environment, debug apps using logs and breakpoints, and build a simple 'Hello World' Android app.

Uploaded by

newvinayakprints
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.

)|2023-24

PRACTICAL NO 1

AIM: Introduction to Android, Introduction to Android Studio IDE, Application


Fundamentals
 Creating a Project
 Android Components
 Activities
 Services
 Content Providers
 Broadcast Receivers
 Creating Android virtual device
 USB debugging mode
 Simple “Hello World” program

Android Components:
Sr.No Components & Description
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
BroadcastReceivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.

Activities
 An activity represents a single screen with a user interface; in-short Activity performs actions on
the screen.
 For example, an email application might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading emails.
 If an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.
 An activity is implemented as a subclass of Activity class as follows −
publicclassMainActivityextendsActivity{
}

Services
 A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different application,
or it might fetch data over the network without blocking user interaction with an activity.
 A service is implemented as a subclass of Service class as follows −
publicclassMyServiceextendsService{
}

1
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Broadcast Receivers
 Broadcast Receivers simply respond to broadcast messages from other applications or from the
system.
 For example, applications can also initiate broadcasts to let other applications know that some
data has been downloaded to the device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate appropriate action.
 A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message
is broadcaster as an Intent object.
publicclassMyReceiverextendsBroadcastReceiver{
publicvoid onReceive(context,intent){}
}

Content Providers
 A content provider component supplies data from one application to others on request.
 Such requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
 A content provider is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.
publicclassMyContentProviderextendsContentProvider{
publicvoid onCreate(){}
}

Additional Components
 There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are –
Sr.No Components & Description
Fragments
1
Represents a portion of user interface in an Activity.
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
Manifest
6
Configuration file for the application.

USB Debugging Mode:


 USB Debugging allows an Android device to communicate with a PCrunning the Android SDK
to use advanced operations.
 When you develop Android apps, you have to install the Android Software Developer Kit (SDK)
on your PC.
 Debugging allows you to go through each line of code, evaluating your app’s variables, methods
and how well your code is working. It’s easier to find small mistake in large pieces of code. In
this article we will go through basic tips and tricks on debugging an Android app.

Start debug mode


 When you want to start the debugging mode, first make sure your device is setup for debugging
and connected to USB, and open your project in Android Studio (AS) and just click the Debug
icon .
 Then select your device in the Choose Device window, and Android Studio will launch your
application in the debug mode.

2
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
 Android Studio will also automatically open the Debug tool. You can turn it on manually by
clicking Debug! at the bottom of Android Studio.
 Another way to start debugging without having to restart your app is by clicking on “Attach

debugger to Android process” .

Debug using Logs


 The easiest way to debug your code is to use Log. This is a utility that allows you to send log
outputs, which you can then view in Logcat in Android Studio.
 Simply use android.util.Log in combination with one of the following methods: Log.v(),
Log.d(), Log.i(), Log.w(), Log.e() or Log.wtf(). All of them use 2 string parameters: TAG and
your message.
 You can also pass Throwable as a third parameter, which will log your TAG, message and
exception log.
 By using different methods — levels of verbosity (VERBOSE, DEBUG, INFO, WARNING,
ERROR) — you can later filter the logs out or even set up AS and customize the Logcat text
colors and text background for each level.

Logcat
 At STRV we use the Logcat utility, which handles if-statement among other things. Check it
out here.
 In build.gradle we have build config property LOGS, which can be set to true in the debug build
type and to false in the release type. Logcat always check the LOGS property before logging
any message. Then you don’t have to worry about wrapping it in any if-statement.
Simply call the method:
Logcat.d(“Your message here”);
You can also set other parameters in this class. The message can include “Code location”.
This means that it displays the name of the method, the line of code and also the thread where
Logcat is called. Another cool thing about Logcat is that you can log formatted messages. So
instead of:
Logcat.d(“Message with index: ” + someInteger)
we use:
Logcat.d(“Message with index: %d”, someInteger)
Breakpoints
 When you are at the point where you can’t fix a bug just by looking at your code, it’s time to
use breakpoints. Breakpoints allow you to pause the execution of your app at a particular line of
code.
 Setting up breakpoints
Just go to the file that you want to debug, find a line of code where you want to start and
click on the sidebar to the left of this line. You will see a red dot there. Then run your app
in the debug mode or attach a debugger (see above).

Creating Android virtual device


Step 1: Go to Android Virtual Device Manager and Click on Create Virtual Device.

3
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Step 2:Virtual Device Configuration window will appear
In Phone Tab Select Name of Device and Click on Next.

Step 3: Select System Image and Click on API 28

Step 4:Give AVD Name and click on Finish

4
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
HELLO WORLD PROGRAM:
Step 1: Create new Android Project and give Application name as hello

Step2: Check Phone and Tablet and select API Android 4.0.3[IceCreamSandwitch]
Click on Next.

Step 3: Select Empty Activity.

5
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Step 4: Click on finish

Now Write code in following files as follows:


Source Code:

MainActivity.kt
package com.example.user1.hello

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

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

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

6
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

OUTPUT:

7
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 2

AIM: Programming Resources


 Color
 Theme
 String
 Drawable
 Dimension
 Image

Android Resource: Color


1. Defining new color properties in colors.xml
2. Create a new project and go to:
ProjectName>App>src>main>res>values>colors.xml

colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
//Add new colors here
<color name="ColorRed">#FF0000</color>
<color name="ColorBlue">#0000FF</color>
</resources>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Practical No. 2!"
android:id="@+id/textview"
android:background="@color/ColorRed"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alpha"
8
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:id="@+id/textview1"
android:background="@color/ColorBlue"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="India"
android:id="@+id/textview2"
android:background="#00FF00"/>

</LinearLayout>

MainActivity.kt
package com.example.user1.ampract2
import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {


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

OUTPUT:

9
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Theme
1. Defining new theme properties in styles.xml
2. Create a new project and go to: ProjectName>App>src>main>res>values>styles.xml

styles.xml
<resources> <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> //Add new color to the background
<item name="android:background">#00F0EF</item>
<item name="android:textColor">#000000</item>
</style></resources>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="TYIT" android:id="@+id/textview"
android:background="@color/ColorRed"/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="AMP" android:id="@+id/textview1"
android:background="@color/ColorBlue"/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="Welcome" android:id="@+id/textview2" android:background="#00FF00"/>
</LinearLayout>

OUTPUT:

10
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Strings
1. Defining paragraph and header property in strings.xml
2. Create a new project and go to: ProjectName>App>src>main>res>values>strings.xml

strings.xml
<resources>
<string name="app_name">ampract2</string>
<string name="ParaHead">Programming Resources</string>
<string name="Description">The Android multimedia framework includes support for playing
variety of common media types.</string>
</resources>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="@string/ParaHead" android:id="@+id/textview"
android:background="@color/ColorRed"/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="@string/Description" android:id="@+id/textview1"
android:background="@color/ColorBlue"/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="Welcome" android:id="@+id/textview2" android:background="#00FF00"/>
</LinearLayout>

OUTPUT:

11
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Dimension, Image
1. Adding Images to Application created
2. For adding a new image files, do the following:
ProjectName>App>src>main>res>drawable>Right-click and paste the images that are copied
3. For adding new dimension file, do the following:
ProjectName-->App-->src-->main-->res-->values-->Right-click and new-->values resource
file
4. Select Dimension and click on OK

Give file name as dimens and click OK

12
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
5. Add a new dimens.xml file and write the following code in dimens.xml

dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimenname="textview_height">35dp</dimen>
<dimenname="textview_width">150dp</dimen>
<dimenname="font_size">26sp</dimen>
</resources>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Modified"
android:textSize="@dimen/font_size"/>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img1"
android:src="@drawable/maple"/>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img2"

13
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:src="@drawable/penguin"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img3"
android:src="@drawable/twitter"/>

</LinearLayout>

OUTPUT:

14
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 3

AIM: Programming Activities and Fragments


 Activity Life Cycle
 Activity methods
 Multiple Activities

Activity Lifecycle

15
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

The lifecycle methods of Android Activity


1. The various methods to be created are onStart(), onRestart(), onStop(), onResume(),onDestroy()
and onPause()
2. Create a new project and go to, MainActivity.kt
3. For seeing the output go to,
Logcat>Search for “Lifecycle” keyword

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.kt

package com.example.user1.ampract3
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log;

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
print("onCreate")
}

16
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
override fun onStart() {
super.onStart()
print("onStart")
}

override fun onResume() {


super.onResume()
print("onResume")
}

override fun onPause() {


super.onPause()
print("onPause")
}

override fun onStop() {


super.onStop()
print("onStop")
}

override fun onRestart() {


super.onRestart()
print("onRestart")
}

override fun onDestroy() {


super.onDestroy()
print("onDestroy")
}

fun print(msg: String){


Log.d("Activity State ",msg)
}
}

OUTPUT:

17
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

18
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 4

AIM: Program related to different layouts


 Coordinate Layout
 Linear Layout
 Relative Layout
 Frame Layout
 ListView
 Grid View

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
Sr.No Layout & Description
Linear Layout
1 LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
Relative Layout
2
RelativeLayout is a view group that displays child views in relative positions.
Table Layout
3
TableLayout is a view that groups views into rows and columns.
Absolute Layout
4
AbsoluteLayout enables you to specify the exact location of its children.
Frame Layout
5
The FrameLayout is a placeholder on screen that you can use to display a single view.
List View
6
ListView is a view group that displays a list of scrollable items.
Grid View
7
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
Sr.No Attribute & Description
android:id
1
This is the ID which uniquely identifies the view.
android:layout_width
2
This is the width of the layout.
android:layout_height
3
This is the height of the layout
android:layout_marginTop
4
This is the extra space on the top side of the layout.
android:layout_marginBottom
5
This is the extra space on the bottom side of the layout.
19
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:layout_marginLeft
6
This is the extra space on the left side of the layout.
android:layout_marginRight
7
This is the extra space on the right side of the layout.
android:layout_gravity
8
This specifies how child Views are positioned.
android:layout_weight
9
This specifies how much of the extra space in the layout should be allocated to the View.
android:layout_x
10
This specifies the x-coordinate of the layout.
android:layout_y
11
This specifies the y-coordinate of the layout.
android:layout_width
12
This is the width of the layout.
android:layout_width
13
This is the width of the layout.
android:paddingLeft
14
This is the left padding filled for the layout.
android:paddingRight
15
This is the right padding filled for the layout.
android:paddingTop
16
This is the top padding filled for the layout.
android:paddingBottom
17
This is the bottom padding filled for the layout.

1. Linear Layout

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

<Button android:id="@+id/btnStartService" android:layout_width="270dp"


android:layout_height="wrap_content" android:text="start_service"/>
<Button android:id="@+id/btnPauseService" android:layout_width="270dp"
android:layout_height="wrap_content" android:text="pause_service"/>
<Button android:id="@+id/btnStopServce" android:layout_width="270dp"
android:layout_height="wrap_content" android:text="stop_service"/>
</LinearLayout>

MainActivity.kt

package com.example.user1.frame_layout

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

20
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
OUTPUT:

2. Relative Layout

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="16dp" android:paddingRight="16dp" >

<EditText android:id="@+id/name" android:layout_width="fill_parent"


android:layout_height="wrap_content" />

<LinearLayout android:orientation="vertical" android:layout_width="fill_parent"


android:layout_height="fill_parent" android:layout_alignParentLeft="true"
android:layout_below="@+id/name">

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="New Button" android:id="@+id/button" />

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="New Button" android:id="@+id/button2" />
</LinearLayout>
</RelativeLayout>

MainActivity.kt

package com.example.user1.frame_layout

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

21
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

OUTPUT:

3. Frame Layout

MainActivity.kt
package com.example.user1.frame_layout

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

22
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/one"
android:scaleType="centerCrop"/>

<TextView android:textSize="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:gravity="center"
android:textColor="@color/colorAccent"
android:layout_marginTop="220dp" />

</FrameLayout>

OUTPUT:

23
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

4. ListView

MainActivity.kt
package com.example.user1.listview
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView

class MainActivity : AppCompatActivity() {

var array = arrayOf("Melbourne", "Vienna", "Vancouver", "Toronto", "Calgary",


"Adelaide", "Perth", "Auckland", "Helsinki", "Hamburg", "Munich", "New York",
"Sydney", "Paris", "Cape Town", "Barcelona", "London", "Bangkok")

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val adapter = ArrayAdapter(this, R.layout.listview_item, array)

val listView:ListView = findViewById(R.id.listview_1)


listView.setAdapter(adapter)
}
}

listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Each List Item is displayed as TextView defined below -->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="10dip" android:textSize="16dip"

24
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:textStyle="bold" >
</TextView>

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

<ListView android:id="@+id/listview_1" android:layout_width="match_parent"


android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>

OUTPUT:

25
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Grid View:
activity_main.xml
<?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"
tools:context=".MainActivity" android:rowCount="3" android:columnCount="3"
android:padding="20dp">

<Button android:layout_width="110dp" android:layout_height="100dp" android:text="1"/>


<Button android:layout_width="110dp" android:layout_height="100dp" android:text="2"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="3"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="4"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="5"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="6"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="7"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="8"/>
<Button android:layout_width="110dp" android:layout_height="100dp" android:text="9"/>
</GridLayout>

MainActivity.kt

package com.example.user1.gridview

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

OUTPUT:

26
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

27
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 5

AIM: Programming UI elements


 UI Components
 AppBar

Android Different Types of UI Controls


We have a different type of UI controls available in android to implement user interface for our
android applications.

Following are the commonly used UI or input controls in android applications.


Android TextView
 In android, TextView is a user interface control which is used to display the text to the user.

Android EditText
 In android, EditText is a user interface control which is used to allow the user to enter or modify
the text.

Android AutoCompleteTextView
 In android, AutoCompleteTextView is an editable text view which is used to show the list of
suggestions based on the user typing text. The list of suggestions will be shown as a dropdown
menu from which the user can choose an item to replace the content of textbox.

Android Button
 In android, Button is a user interface control which is used to perform an action when the user click
or tap on it.

Android Image Button


 In android, Image Button is a user interface control which is used to display a button with image
to perform an action when user click or tap on it.
 Generally, the Image button in android looks similar as regular Button and perform the actions same
as regular button but only difference is for image button we will add an image instead of text.

Android Toggle Button


 In android, Toggle Button is a user interface control which is used to display ON (Checked) or
OFF (Unchecked) states as a button with a light indicator.

Android CheckBox
 In android, Checkbox is a two states button that can be either checked or unchecked.

Android Radio Button


 In android, Radio Button is a two states button that can be either checked or unchecked and it
cannot be unchecked once it is checked.

Android Radio Group

28
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
 In android, Radio Group is used to group one or more radio buttons into separate groups based on
our requirements.
 In case if we group radio buttons using radio group, at a time only one item can be selected from
the group of radio buttons.

Android ProgressBar
 In android, ProgressBar is a user interface control which is used to indicate the progress of an
operation.

Android Spinner
 In android, Spinner is a drop-down list which allows a user to select one value from the list.

Android TimePicker
 In android, TimePicker is a widget for selecting the time of day, either in 24-hour or AM/PM mode.

Android DatePicker
 In android, DatePicker is a widget for selecting a date.

Android Toolbar or App bar: is a part of the application, where its provide UI experience on top of
the app for easy navigation and quick access to other items. A Toolbar is a generalization of Android
action bar.

Toolbar (App bar) is supporting a more focused feature set than ActionBar. From start to end, a
toolbar may contain a combination of the following optional elements:
 Navigation button: Up arrow or navigation menu toggle icon in starting of Toolbar. You override
default home function and perform any action goto parent activity or open/close navigation menu
toggle,
 Branded logo image: Its use for when you want to show logo in-app top bar. This may extend to
the height of the bar and can be wider.
 Title and subtitle: If an app uses a logo image it should strongly recommend neglecting a title and
subtitle. It shows the name of the brand or Activity or user landing page information.
 An action menu: The menu of actions will pin to the end of the Toolbar offering a few main
operations to the user like setting, print, save, profile etc. Or maybe some time you needed the same
menu for every activity, then you can use the same toolbar in multiple places.

Program for AppBar


Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/ap
k/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!" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

29
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<include layout="@layout/toolbar_layout"/>

</android.support.constraint.ConstraintLayout>

MainActivity.kt
package com.example.user1.appbar

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar;

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolBar))

}
}

Go to app->layout->New->XML file

Create xml layout file named as toolbar_layout

toolbar_layout.xml

30
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<app:android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:id="@+id/toolBar">

</app:android.support.v7.widget.Toolbar>
</LinearLayout>

OUTPUT:

Adding menus to toolbar

31
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
For adding Menus to appbar, go to,
1. ProjectName> App >Src> Main > Res > New > Resource File > Give a filename
(app_bar_menu.xml) and select menu in resource type.
2. Now go to app_bar_menu.xml and add two menu items, and make the following changes to the
code file,

app_bar_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/action_search" android:title="Setting"


android:icon="@drawable/ic_launcher_background" app:showAsAction="ifRoom"/>

<item android:id="@+id/action_about" android:title="About"


app:showAsAction="never"/>
</menu>

3. Now go to MainActivity.ktand add a new method onCreateOptionsMenu(), and make the


following changes to the code file,
MainActivity.kt

32
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
package com.example.user1.appbar

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolBar))

}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.app_bar_menu,menu)
return super.onCreateOptionsMenu(menu)
}
// actions on click menu items
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_search-> {
// User chose the "Print" item
Toast.makeText(this,"Search action",Toast.LENGTH_LONG).show()
true
}
R.id.action_about-> {
// User chose the "Print" item
Toast.makeText(this,"About action",Toast.LENGTH_LONG).show()
true
}
android.R.id.home->{
Toast.makeText(this,"Home action",Toast.LENGTH_LONG).show()
true
}

else ->
{
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}

OUTPUT:
33
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

34
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 6

AIM: Programming menus


 Android Menu is provide a user interface in Android application. The concept of Android menu
has came for give a user experience to user. Like if your have same option (action button ) in
multiple activity , then you have to add menu in the App bar for good user interface experience.

Types of Android Menus:


 Options menu : is the collection of menu items for an activity. Where app activity place actions
that have a global impact on the app, such as “Profile,” “Login/Logout”, “Notification” and
“Settings.”

 Context menu and contextual action mode : A context menu is appears when the user performs
a long-click on an element. That provides actions that affect the selected content or context frame.
Like in Gmail app you have to long press any email then Context menu appear with option Delete
,Archived etc. Context menu allows the user to select multiple items.

 Popup menu : A popup menu displays a list of items in a vertical list that’s anchored to the view
that invoked the menu

Android Menu Elements


 <menu> : It’s a container of menu Items. A <menu> element is the root node for the file and it hold
one or more <item> and <group> elements.
 <item> :MenuItem is represents a single item in a menu. This element may contain a
nested <menu>element in order to create a submenu.

35
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
 <group> This is an optional, invisible container for <item> elements. It allows you to categorize
menu items so they share properties such as active state and visibility.

Android Menu Attributes


android:id: A resource ID that’s unique to the item, Wheres the application to recognize the item
when the user selects it.
android:icon: A reference to a drawable to use as the item’s icon
.android:title: A reference to a string to use as the item’s title.
android:showAsAction:Specifies when and how this item should appear as an action item in the
app bar.

Creating Menus
1. Create a new project and go to,

Project > App >src>res(Right-click on res and select) > New > Android Resource File >
Filename(mymenu) and Resource Type Menu

36
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
2. Now go to, mymenu.xml file and make the following changes to code file,
mymenu.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">
android:layout_width="wrap_content" android:layout_height="wrap_content"
<item android:id="@+id/newb" android:title="Bookmarks" />

<item android:title="Search" android:id="@+id/search" />

<item android:id="@+id/save" android:title="Save"/>

<item android:id="@+id/Share" android:title="Share" />

<item android:id="@+id/delete" android:title="Delete" />

<item android:id="@+id/Exit" android:title="Exit" />

</menu>

3. Now go to MainActivity.ktfile and make the following changes to code,

MainActivity.kt

package com.example.user1.menu
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {


menuInflater.inflate(R.menu.mymenu,menu)
return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {


R.id.newb-> {
// User chose the "Print" item

Toast.makeText(this,"New selected",Toast.LENGTH_LONG).show()
true
}

R.id.Share-> {

// User chose the "Print" item


Toast.makeText(this,"Share selected",Toast.LENGTH_LONG).show()
true

37
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
}

R.id.delete-> {
// User chose the "Print" item
Toast.makeText(this,"Delete selected",Toast.LENGTH_LONG).show()
true
}

R.id.save-> {
// User chose the "Print" item
Toast.makeText(this,"Save selected",Toast.LENGTH_LONG).show()
true
}
R.id.search-> {
// User chose the "Print" item
Toast.makeText(this,"Search selected",Toast.LENGTH_LONG).show()
true
}

R.id.Exit-> {

// User chose the "Print" item


Toast.makeText(this,"About action",Toast.LENGTH_LONG).show()
true
}

android.R.id.home->{

Toast.makeText(this,"Home action",Toast.LENGTH_LONG).show()
true
}

else -> {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/ap
k/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!"
38
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

OUTPUT:

39
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 7

AIM: Program on Broadcast receivers

A broadcast receiver (receiver) is an Android component which allows you to register for system or
application events. All registered receivers for an event are notified by the Android runtime once this
event happens.
For example, applications can register for the ACTION_BOOT_COMPLETED system event which is
fired once the Android system has completed the boot process.

Implementation
 A receiver can be registered via the AndroidManifest.xml file.
 Alternatively to this static registration, you can also register a receiver dynamically via
theContext.registerReceiver() method.
 The implementing class for a receiver extends the BroadcastReceiver class.
 If the event for which the broadcast receiver has registered happens, the onReceive() method of the
receiver is called by the Android system.

Life cycle of a broadcast receiver


After the onReceive() of the receiver class has finished, the Android system is allowed to recycle the
receiver.

Asynchronous processing
 Before API level 11, you could not perform any asynchronous operation in the onReceive()method,
because once the onReceive() method had been finished, the Android system was allowed to recycle
that component. If you have potentially long running operations, you should trigger a service instead.
 Since Android API 11 you can call the goAsync() method. This method returns an object of
thePendingResult type. The Android system considers the receiver as alive until you call
thePendingResult.finish() on this object. With this option you can trigger asynchronous processing
in a receiver. As soon as that thread has completed, its task calls finish() to indicate to the Android
system that this component can be recycled.

Restrictions for defining broadcast receiver


 As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the
corresponding application has never been started by the user or if the user explicitly stopped the
application via the Android menu (in Manage Application ).
 This is an additional security feature as the user can be sure that only the applications he started will
receive broadcast intents.

Send the broadcast to your application for testing


You can use the following command from the adb command line tool. The class name and package
names which are targeted via the command line tool need to be as defined in the manifest. You should
send the intent you generated to your specific component, for example if you send a general
ACTION_BOOT_COMPLETED broadcast, this will trigger a lot of things in an Android system.
# trigger a broadcast and deliver it to a component
adb shell am activity/service/broadcast -a ACTION -c CATEGORY -n NAME
40
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

#for example (this goes into one line)

adb shell am broadcast -a


android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n
package_name/class_name

System broadcasts
Several system events are defined as final static fields in the Intent class. Other Android system classes
also define events, e.g., the TelephonyManager defines events for the change of the phone state.
The following table lists a few important system events.
Table 1. System Events
Event Description
Intent.ACTION_BOOT_COMPLETED Boot completed. Requires
the android.permission.RECEIVE_BOOT_COMPLE
TED permission
Intent.ACTION_POWER_CONNECTED Power got connected to the device.
Intent.ACTION_POWER_DISCONNECTED Power got disconnected to the device.
Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to reduce
activities in your app which consume power.
Intent.ACTION_BATTERY_OKAY Battery status good again.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/and
roid"
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="Flight Mode"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="8dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/flightmode" />

</android.support.constraint.ConstraintLayout>

MainActivity.kt
package com.example.user1.broadcast

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
41
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user1.broadcast">

<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>
</application>

</manifest>

MyReceiver.kt
package com.example.user1.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast : Flight mode changed.",
Toast.LENGTH_LONG).show()
}
}

OUTPUT:
42
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

43
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 8

AIM: Database Programming with SQLite

Create Kotlin file named as UserModel, DBContract,UserDBHelper

UserModel.kt
package com.example.user1.sqlitetutorial

class UserModel(valuserid: String, valname: String, valage: String)


44
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

DBContract.kt
package com.example.user1.sqlitetutorial

import android.provider.BaseColumns

object DBContract {

/* Inner class that defines the table contents */

class UserEntry : BaseColumns {


companion object {
valTABLE_NAME = "users"
valCOLUMN_USER_ID = "userid"
valCOLUMN_NAME = "name"
valCOLUMN_AGE = "age"
}

UserDBHelper.kt
package com.example.user1.sqlitetutorial

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper

class UsersDBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null,


DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(SQL_CREATE_ENTRIES)
}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {


// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES)
onCreate(db)
}

override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {


onUpgrade(db, oldVersion, newVersion)
}

@Throws(SQLiteConstraintException::class)
fun insertUser(user: UserModel): Boolean {
// Gets the data repository in write mode
valdb = writableDatabase

// Create a new map of values, where column names are the keys
valvalues = ContentValues()
values.put(DBContract.UserEntry.COLUMN_USER_ID, user.userid)
values.put(DBContract.UserEntry.COLUMN_NAME, user.name)
45
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
values.put(DBContract.UserEntry.COLUMN_AGE, user.age)
// Insert the new row, returning the primary key value of the new row
valnewRowId = db.insert(DBContract.UserEntry.TABLE_NAME, null, values)
return true
}

@Throws(SQLiteConstraintException::class)
fun deleteUser(userid: String): Boolean {
// Gets the data repository in write mode
valdb = writableDatabase// Define 'where' part of query.
valselection = DBContract.UserEntry.COLUMN_USER_ID+ " LIKE ?"
// Specify arguments in placeholder order.
valselectionArgs = arrayOf(userid)
// Issue SQL statement.
db.delete(DBContract.UserEntry.TABLE_NAME, selection, selectionArgs)
return true
}

fun readUser(userid: String): ArrayList<UserModel> {


valusers = ArrayList<UserModel>()
valdb = writableDatabase
varcursor: Cursor? = null
try {
cursor = db.rawQuery("select * from " + DBContract.UserEntry.TABLE_NAME+ "
WHERE " + DBContract.UserEntry.COLUMN_USER_ID+ "='" + userid + "'", null)
} catch (e: SQLiteException) {
// if table not yet present, create it
db.execSQL(SQL_CREATE_ENTRIES)
return ArrayList()
}

varname: String
varage: String
if (cursor!!.moveToFirst()) {
while (cursor.isAfterLast== false) {
name =
cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
users.add(UserModel(userid, name, age))
cursor.moveToNext()
}
}
return users
}

fun readAllUsers(): ArrayList<UserModel> {


valusers = ArrayList<UserModel>()
valdb = writableDatabase
varcursor: Cursor? = null
try {
cursor = db.rawQuery("select * from " + DBContract.UserEntry.TABLE_NAME, null)
} catch (e: SQLiteException) {
db.execSQL(SQL_CREATE_ENTRIES)
return ArrayList()
}

varuserid: String
varname: String
varage: String
46
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
if (cursor!!.moveToFirst()) {
while (cursor.isAfterLast== false) {
userid = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_USER_ID))
name =
cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
users.add(UserModel(userid, name, age))
cursor.moveToNext()
}
}
return users
}

companion object {
// If you change the database schema, you must increment the database version.
valDATABASE_VERSION = 1
valDATABASE_NAME = "FeedReader.db"
private valSQL_CREATE_ENTRIES =
"CREATE TABLE " + DBContract.UserEntry.TABLE_NAME+ " (" +
DBContract.UserEntry.COLUMN_USER_ID+ " TEXT PRIMARY KEY," +
DBContract.UserEntry.COLUMN_NAME+ " TEXT," +
DBContract.UserEntry.COLUMN_AGE+ " TEXT)"
private valSQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " +
DBContract.UserEntry.TABLE_NAME
}
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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" android:gravity="center"
tools:context=".MainActivity">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"


android:text="SQLite Tutorial - User Management" android:textSize="20dp"
android:padding="10dp" />

<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical">

<EditText android:id="@+id/edittext_userid" android:hint="User ID"


android:gravity="center" android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText android:id="@+id/edittext_name" android:hint="User Name"


android:gravity="center" android:layout_width="match_parent"
android:layout_height="wrap_content" />

<EditText android:id="@+id/edittext_age" android:hint="User Age"


android:gravity="center" android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
47
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:orientation="horizontal">
<Button
android:id="@+id/button_add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="addUser"
android:text="Add" />

<Button
android:id="@+id/button_show_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="showAllUsers"
android:text="Show All" />
</LinearLayout>

<TextView
android:id="@+id/textview_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<LinearLayout
android:id="@+id/ll_entries"
android:padding="15dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</LinearLayout>

</LinearLayout>

MainActivity.kt
package com.example.user1.sqlitetutorial

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {


lateinitvarusersDBHelper: UsersDBHelper

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
usersDBHelper= UsersDBHelper(this)
}

fun addUser(v:View){
varuserid = this.edittext_userid.text.toString()
varname = this.edittext_name.text.toString()
varage = this.edittext_age.text.toString()
varresult = usersDBHelper.insertUser(UserModel(userid = userid,name = name,age = age))

//clear all edittext s


48
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
this.edittext_age.setText("")
this.edittext_name.setText("")
this.edittext_userid.setText("")
this.textview_result.text= "Added user : "+result
this.ll_entries.removeAllViews()
}

fun showAllUsers(v:View){
varusers = usersDBHelper.readAllUsers()
this.ll_entries.removeAllViews()
users.forEach{
vartv_user = TextView(this)
tv_user.textSize= 30F
tv_user.text= it.name.toString() + " - " + it.age.toString()
this.ll_entries.addView(tv_user)
}
this.textview_result.text= "Fetched " + users.size+ " users"
}

}
OUTPUT:

49
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

PRACTICAL NO 9

AIM: Programming Security and Permissions

Extra Packages requied in ManagePermission.kt (Class File)


import android.app.Activity
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog

Extra Packages requied in MainActivity.kt


import android.Manifest
import android.content.Context
import android.os.Build
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

For Multple Permission Access,need to add following line in class MainActivity.kt

private valPermissionsRequestCode = 123

MainActivity.kt
package com.example.user1.permissionappdemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.Manifest
import android.content.Context
import android.os.Build
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

private valPermissionsRequestCode= 123


private lateinitvarmanagePermissions: ManagePermissions

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Initialize a list of required permissions to request runtime


vallist = listOf<String>(
Manifest.permission.CAMERA,
Manifest.permission.READ_CONTACTS,

50
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SEND_SMS,
Manifest.permission.READ_CALENDAR
)
// Initialize a new instance of ManagePermissions class
managePermissions=
ManagePermissions(this,list,PermissionsRequestCode)

// Button to check permissions states


button.setOnClickListener{
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M)
managePermissions.checkPermissions()
}
}

// Receive the permissions request result


override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
PermissionsRequestCode->{
valisPermissionsGranted = managePermissions
.processPermissionsResult(requestCode,permissions,grantResults)
if(isPermissionsGranted){
// Do the task now
toast("Permissions granted.")
}else{
toast("Permissions denied.")
}
return
}
}
}

// Extension function to show toast message


fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

An app must publicize the permissions it requires by including <uses-permission>tags in the app
manifest.

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user1.permissionappdemo">

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
51
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>

<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

Create a New Kotlin Class


app->src->main->java->com.example.admin.permissionappdemo

52
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

Write the following code in the Class File


ManagePermissions.kt
package com.example.user1.permissionappdemo

import android.app.Activity
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog

class ManagePermissions(valactivity: Activity,vallist:


List<String>,valcode:Int) {
// Check permissions at runtime
fun checkPermissions() {
if (isPermissionsGranted() != PackageManager.PERMISSION_GRANTED) {
showAlert()
} else {
activity.toast("Permissions already granted.")
}
}

// Check permissions status


private fun isPermissionsGranted(): Int {
// PERMISSION_GRANTED : Constant Value: 0
// PERMISSION_DENIED : Constant Value: -1

varcounter = 0;
for (permission in list) {
counter += ContextCompat.checkSelfPermission(activity,
permission) }
return counter
}

// Find the first denied permission


private fun deniedPermission(): String {
for (permission in list) {
if (ContextCompat.checkSelfPermission(activity, permission)
== PackageManager.PERMISSION_DENIED) return permission
}

53
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
return ""
}

// Show alert dialog to request permissions


private fun showAlert() {
valbuilder = AlertDialog.Builder(activity)
builder.setTitle("Need permission(s)")
builder.setMessage("Some permissions are required to do the task.")
builder.setPositiveButton("OK", { dialog, which -
>requestPermissions() })
builder.setNeutralButton("Cancel", null)
valdialog = builder.create()
dialog.show()
}
// Request the permissions at run time

private fun requestPermissions() {


valpermission = deniedPermission()
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
permission)) {
// Show an explanation asynchronously
activity.toast("Should show an explanation.")
} else {
ActivityCompat.requestPermissions(activity, list.toTypedArray(),
code)
}
}

// Process permissions result


fun processPermissionsResult(requestCode: Int, permissions:
Array<String>,
grantResults: IntArray): Boolean {
varresult = 0
if (grantResults.isNotEmpty()) {
for (item in grantResults) {
result += item
}
}

if (result == PackageManager.PERMISSION_GRANTED) return true


return false
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://sc
hemas.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!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
54
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Request Permission at Runtime"
android:visibility="visible"
tools:layout_editor_absoluteX="28dp"
tools:layout_editor_absoluteY="0dp" />

</android.support.constraint.ConstraintLayout>

OUTPUT:

55
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

56
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24

57

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy