Android Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

PRACTICAL JOURNAL OF

CSIT-606 Android Programming

BE: III Year

Department of Computer Science and Information Technology

Name : Garv Bhatt

Branch : CI

Section :1

Roll No. : 0827CI201067

Session : JAN-JUNE 2023

Department of Computer Science and Information Technology

AITR, Indore.

Android Lab Manual Department of Computer Science and Information Technology


ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Department of Computer Science Engineering

Certificate

This is to certify that the experimental work entered in this


journal as per the BE II year syllabus prescribed by the
RGPV was done by Ms. Garv Bhatt BE III year VI semester
CI in the Android Programming Laboratory of this institute
during the academic year 2022- 2023.

Signature of Faculty

Android Lab Manual Department of Computer Science and Information Technology


Department of Computer Science and Information Technology
Acropolis Institute of Technology and Research, Indore
.
CSIT Vision
To develop competent professionals to become a valuable source for industry, nation
and humanity by adapting industry inspired practices.

CSIT Mission
1. To strengthen industry collaboration for maximizing career opportunities ,
professional and entrepreneurship skills .
2. To improve employment marketability, positive attitude , communication skills
and learning agility.
3. To Facilitate value-based research and  innovation for broadening knowledge,
skills and intellectual abilities

Android Lab Manual Department of Computer Science and Information Technology


LAB INDEX

1. Introduction to android operating system and study of basic widgets.

2. Installation of Java JDK and Android

3. Study of UI in Android

4. Study of android lifecycle and demonstration of it.

5. Study of Android Layouts

6. Study of Intents in android

7. Study of android database (SQlite)

8. Create a basic application of Hello World on Constraint Layout

9. Create an application to add two numbers on Linear Layout

10. Create an application for calculator in Relative layout

11. Create an application for the registration page in Table Layout

Android Lab Manual Department of Computer Science and Information Technology


Practical 1

Aim: Introduction to android

Objective: Student should get the knowledge of android operating system background.

Outcome: Student will be aware of the android operating system.

Android Architecture

Android operating system is a stack of software components which is roughly divided into five
sections and four main layers as shown below in the architecture diagram.

Linux kernel At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches.
This provides basic system functionality like process management, memory management, device
management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is
really good at such as networking and vast array of device drivers, which take the pain out of
interfacing to peripheral hardware.

Libraries On top of Linux kernel there is a set of libraries including open -source Web browser
engine WebKit, well known library libc, SQLite database which is a useful repository for storage and
sharing of application data, libraries to play and record audio and video, SSL libraries responsible for
Internet security etc.
Android Runtime This is the third section of the architecture and available on the second layer
from the bottom. This section provides a key component called Dalvik Virtual Machine which is a
kind of Java Virtual Machine specially designed and optimized for Android.

Android Lab Manual Department of Computer Science and Information Technology


The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in
its own process, with its own instance of the Dalvik virtual machine.

The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.

Application Framework The Application Framework layer provides many higher-level services to
applications in the form of Java classes. Application developers are allowed to make use of these
services in their applications.

Applications You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are Contacts Books,
Browser, Games etc.

Android UI An Android application user interface is everything that the user can see and interact
with. You have learned about the various layouts that you can use to position your views in an
activity. This chapter will give you detail on various views.

A View is an object that draws something on the screen that the user can interact with and a
ViewGroupis an object that holds other View (and ViewGroup) objects in order to define the layout
of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML.

Android UI Controls

There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.
UI Control & Description
TextView This control is used to display text to the user.

EditText EditText is a predefined subclass of TextView that includes rich editing


capabilities.

AutoCompleteTextVie The AutoCompleteTextView is a view that is similar to EditText, except that it


w shows a list of completion suggestions automatically while the user is typing.
Button A push-button that can be pressed, or clicked, by the user to perform an action.
ImageButton AbsoluteLayout enables you to specify the exact location of its children.
CheckBox An on/off switch that can be toggled by the user. You should use checkboxes
when presenting users with a group of selectable options that are not mutually
exclusive.
ToggleButton An on/off button with a light indicator.

RadioButton The RadioButton has two states: either checked or unchecked. RadioGroup

Android Lab Manual Department of Computer Science and Information Technology


RadioGroup A RadioGroup is used to group together one or more RadioButtons.
ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such
as when you are performing a task in the background.
Spinner A drop-down list that allows users to select one value from a set.

TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour
mode or AM/PM mode.
DatePicker The DatePicker view enables users to select a date of the day.

Create UI Controls

As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:

android:id="@+id/text_id"

To create a UI Control/View/Widget you will have to define a view/widget in the layout file and
assign it a unique ID

Then finally create an instance of the Control object and capture it from the layout, use the
following:

TextView myText = (TextView) findViewById(R.id.text_id);

Android Event Handling

Events are a useful way to collect data about a user's interaction with interactive components of your
app, like button presses or screen touch etc. The Android framework maintains an event queue into
which events are placed as they occur and then each event is removed from the queue on a first-in,
first-out (FIFO) basis. You can capture these events in your program and take appropriate action as
per requirements.

There are following three concepts related to Android Event Management:

• Event Listeners: The View class is mainly involved in building up a Android GUI, same View
class provides a number of Event Listeners. The Event Listener is the object that receives
notification when an event happens.

• Event Listeners Registration: Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the Event Listener fires the
event.

• Event Handlers: When an event happens and we have registered and event listener fo the event,
the event listener calls the Event Handlers, which is the method that actually handles the event.

Android Lab Manual Department of Computer Science and Information Technology


Event Listeners & Event Handlers

Event Handler Event Listener & Description


onClick() OnClickListener()
This is called when the user either clicks or touches or focuses upon any
widget like button,text, image etc. You will use onClick() event handler to
handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any
widget like button, text, image etc. for one or more seconds. You will
use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget looses its focus ie.user goes away from the
view item. You will use onFocusChange() event handler to handle such
event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
hardware key on the device. You will use onKey() event handler to handle
such event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any
ovement gesture on the screen. You will use onTouch() event handler to
handle such event.
onMenuItemClick( OnMenuItemClickListener()
) This is called when the user selects a menu item.You will use
onMenuItemClick() event handler to handle such event.

There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc.

Android Lab Manual Department of Computer Science and Information Technology


Practical 2

Installation of Java JDK and Android

How to Set Up Android Studio on Windows 10 and 11

Android Studio is fantastic, but it can be difficult to set up properly. Follow these steps and you'll
be good to go in no time.
Android Studio is one of the best programs for Android app development. It offers a plethora of
features and integrated tools for creating professional Android apps.
The program includes a feature-rich Android emulator, testing tools, and a consistent development
environment. In addition, it also features an intelligent code editor that provides you with advanced
code suggestions.
Due to many configuration steps, Android Studio may be challenging to set up if you're a novice
developer. Here, we show how to install Android Studio on Windows and create a sample
application.

How to Download and Install the Java JDK

Before installing Android Studio, you first need to install the Java JDK and set up the Java
environment to start working on it.
The Java Development Kit (JDK) is a required development package for creating Java-based
applications. Additionally, it also includes tools for developers for testing Java-coded applications.
Follow these steps to get the latest version of Java JDK for Windows and set it up:

1. Go to the official Oracle Java Downloads page.


2. Choose the most recent version of Java JDK and download the x64 MSI Installer under
the Windows tab.
3. Open the file you've just downloaded from the Downloads folder.
4. Follow the on-screen instructions to install the latest Java JDK.
Now that you've successfully installed JDK, you need to set up a Java environment so that Android
Studio can easily find the location of Java on your desktop.

Setting Up the Java Environment

Here are the steps you've to perform for setting up the Java environment:
1. Open Windows search and type "Edit environment variables."
2. Hit the Enter key to open the Environment Variables window.
3. Now, under the System variables section, click Path > Edit > New
4. Copy the path of the folder where the JDK binaries are installed. For example, in our case,
the path is C:\Program Files\Java\jdk-18.0.1.1\bin
5. Switch to the Environment variables window and paste the path you've copied and save
the changes.
6. Next, under the User Variables section, click New.
7. Add PATH_HOME in the variable name box and C:\Program Files\Java\jdk-18.0.1.1 in
the variable value box.
8. Finally, save the changes by clicking OK.

Android Lab Manual Department of Computer Science and Information Technology


How to Install Android Studio on Windows

Follow these steps to download and install Android Studio for Windows:
1. Visit the Android Developers website and click on Download Android Studio.
2. Now, open the downloaded file to install Android Studio.
3. Click Next to continue installing Android Studio.

4. Further, click Install and wait while Android Studio is being installed on your PC.
5. Once done, click Finish to close the installer and start Android Studio.
6. Android Studio will now ask you to import settings. Click OK to continue to set up
Android Studio.

You should use SSD storage when working with Android Studio to get better performance and
faster processing.

If the installer crashes or closes with a random error code, the chances are that your PC doesn't
meet the minimum system requirements. For this, you must check the below-mentioned
requirements once.

The System Requirements for Android Studio on Windows


Your PC must meet the following requirements to run Android Studio efficiently:

 64-bit Microsoft Windows OS 8/10/11.


 1280 x 800 minimum screen resolution.
 x86_64 CPU architecture; 2nd generation Intel Core or newer; or AMD CPU with
Hypervisor support.
 8GB of RAM or more.
 12GB of available disc space is required (IDE + Android SDK + Android Emulator).

How to Set Up Android Studio on Windows

While you've installed Android Studio on your Windows PC, to create a new project you'll have
to configure the Setup Wizard. The Setup Wizard will help you create a development
environment for your future projects.
Follow these steps to set up Android Studio:
1. In the Setup Wizard window, select the Standard option to apply the recommended
settings and click Next.
2. Next, select a theme you want and click Next again to verify the settings you've
configured.
3. On the following screen, select Accept and click Finish to apply the changes.
4. Wait till the Setup Wizard downloads some required files. It may take somewhere around
15 to 30 minutes, depending on your network speed.
5. Once the download is completed, click Finish to complete the setup process.
If it gets stuck while downloading, it's because of either high CPU usage or interruption in
downloading. This is why you must close all the programs that may consume the internet or are
still running in the background.

Android Lab Manual Department of Computer Science and Information Technology


How to Create a New Test Project in Android Studio
Now, that you've set up and configured Android Studio, follow these steps to run a test project
from scratch:

1. Open Android Studio and click New Project.


2. Select the Basic Activity option and click Next to proceed further.
3. On the next screen, type in a name for your app, and select the language (for example,
Java).
4. Next, select the Minimum SDK for your app. The Minimum SDK defines the minimum
Android version needed to run your test app.
5. Once done, click Finish to generate a new test project.
6. Finally, click Allow access on the next screen to allow ADB to access your public
network.
7. That's it. Now, you can make changes to your test project and build your Android app.

The first test project takes around 10-15 minutes to load all the files and sync the project using
Gradle (a build automation tool). Once it is done, you can interact with your app's project
structure and view different activities in Android Studio.

After making the changes to your project, you have many different options to run your test
app:

 Device Manager: You can create a new emulator from the device manager and run your
app on it. However, the emulator consumes a large number of resources, so we don't
recommend using this option if you're using a low-end PC.
 Pair Devices Using Wi-Fi: You can also run the test app on your Android smartphone.
The only condition here is that your smartphone and your PC should be connected to the
same Wi-Fi network.
 ADB Connection: Lastly, you can use a USB cable and turn on USB Debugging on your
phone to run your app via an ADB connection.

Android Lab Manual Department of Computer Science and Information Technology


Practical 3

Aim: Study of UI in Android

Objective: Student should be able to design their own UI for android application using XML.

Outcome: Student will demonstrate the basic application using UI in android.

Create Android Application

The first step is to create a simple Android Application using Eclipse IDE. Follow the option

File → New → Project and finally select →Android New Application wizard from the wizard list.
Now name your application as HelloWorld using the wizard window as follows:

Next, follow the instructions provided and keep all other entries as default till the final step.
Once your project is created successfully, you will have following project screen:

Android Lab Manual Department of Computer Science and Information Technology


Anatomy of Android Application

Before you run your app, you should be aware of a few directories and files in the Android
project:

Folder, File & Description

src
This contains the .java source files for your project. By default, it includes an MainActivity.java
source file having an activity class that runs when your app is launched using the app icon.
gen
This contains the .R file, a compiler-generated file that references all the resources found in
your project. You should not modify this file.
bin
This folder contains the Android package files .apk built by the ADT during the build process
and everything else needed to run an Android application.
res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.

res/layout
This is a directory for files that define your app's user interface.

res/values
This is a directory for other various XML files that contain a collection of resources, such as
strings and colors definitions.

AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines
each of its components.

Android Lab Manual Department of Computer Science and Information Technology


Android Lab Manual Department of Computer Science and Information Technology
Following section will give a brief overview few of the important application files.

The Main Activity File

The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs
your application. Following is the default code generated by the application wizard for
Hello World! Application:

package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.activity_main, menu); return true;
}
}

Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
TheonCreate() method is one of many methods that are fired when an activity is loaded.

The Manifest File

Whatever component you develop as a part of your application, you must declare all its
components in a manifest file called AndroidManifest.xml which ressides

at the root of the application project directory. This file works as an interface between Android
OS and your application, so if you do not declare your component in this file, then it will not be
considered by the OS. For example, a default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

Android Lab Manual Department of Computer Science and Information Technology


<activity
android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter>
<action android:name="android.intent.action.MAIN" /> <category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Here <application>...</application> tags enclosed the components related to the application.


Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The
application uses the image named ic_launcher.png located in the drawable folders

The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.

The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is
namedandroid.intent.category.LAUNCHER to indicate that the application can be launched from
the device's launcher icon.

The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
theapp_name string defined in the strings.xml fi le, which is "HelloWorld". Similar way, other
strings get populated in the application.

Following is the list of tags which you will use in your manifest file to specify different
Android application components:

<activity>elements for activities


<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers

The Strings File

The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file:

<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string> <string
name="menu_settings">Settings</string> <string
name="title_activity_main">MainActivity</string>
</resources>

Android Lab Manual Department of Computer Science and Information Technology


The R File
The gen/com.example.helloworld/R.java file is the glue between the activity Java files
likeMainActivity.java and the resources like strings.xml. It is an automatically generated file and
you should not modify the content of the R.java file. Following is a sample of R.java file:

/* AUTO-GENERATED FILE. DO NOT MODIFY


package com.example.helloworld;
public final class R {
public static final class attr {
}
public static final class dimen {

public static final int padding_large=0x7f040002; public static


final int padding_medium=0x7f040001; public static final int
padding_small=0x7f040000;
}
public static final class drawable {
public static final int ic_action_search=0x7f020000; public static
final int ic_launcher=0x7f020001;
}
public static final class id {
public static final int menu_settings=0x7f080000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f070000;
}
public static final class string {
public static final int app_name=0x7f050000; public static final int
hello_world=0x7f050001; public static final int
menu_settings=0x7f050002; public static final int
title_activity_main=0x7f050003;
}
public static final class style {
public static final int AppTheme=0x7f060000;
}
}

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is referenced by your
application when building its interface. You will modify this file very frequently to change the
layout of your application. For your "Hello World!" application, this file will have following
content related to default layout:

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

Android Lab Manual Department of Computer Science and Information Technology


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>

The TextView is an Android control used to build the GUI and it have various attribuites like
android:layout_width,android:layout_height etc which are being used to set its width and height
etc. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the strings.xml fi le, which is "Hello
World!".

Running the Application

Let's try to run our Hello World! application we just created. I assume you had created your
AVD while doing environment setup. To run the app from Eclipse, open one of your project's
activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display following
Emulator window:

Android Lab Manual Department of Computer Science and Information Technology


Practical 4

Aim: Develop an application demonstrating Activity Life Cycle

Objective: Student should get the knowledge of developing an application android activity
lifecycle.

Outcome: Student will create application for Activity lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The


android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java. By the help of
activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle
method of Activity describes how activity will behave at different states.

Android Activity Lifecycle methods


Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

Android Lab Manual Department of Computer Science and Information Technology


Android Lab Manual Department of Computer Science and Information Technology
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/
android"
3.     xmlns:app="http://schemas.android.com/apk/res-auto"
4.     xmlns:tools="http://schemas.android.com/tools"
5.     android:layout_width="match_parent"
6.     android:layout_height="match_parent"
7.     tools:context="example.javatpoint.com.activitylifecycle.MainActivity">
8.     <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>

Android Activity Lifecycle Example


It provides the details about the invocation of life cycle methods of activity. In this example, we
are displaying the content on the logcat.

File: MainActivity.java
1. package example.javatpoint.com.activitylifecycle;
2.   import android.app.Activity;
3. import android.os.Bundle;
4. import android.util.Log;
5.  public class MainActivity extends Activity {
6.       @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("lifecycle","onCreate invoked");  }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("lifecycle","onStart invoked");     }
     @Override
    protected void onResume() {
        super.onResume();
        Log.d("lifecycle","onResume invoked");  }
          @Override
    protected void onPause() {
        super.onPause();
        Log.d("lifecycle","onPause invoked");      }
    @Override

Android Lab Manual Department of Computer Science and Information Technology


    protected void onStop() {
        super.onStop();
        Log.d("lifecycle","onStop invoked");      }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("lifecycle","onRestart invoked");     }
     @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("lifecycle","onDestroy invoked");     } }

Output:

You will not see any output on the emulator or device. You need to open logcat.

Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Android Lab Manual Department of Computer Science and Information Technology


Now see on the emulator. It is on the home. Now click on the center button to launch the app
again. Now click on the lifecycle activity icon.

Now see on the logcat: onRestart, onStart and onResume methods are invoked.

Android Lab Manual Department of Computer Science and Information Technology


If you see the emulator, application is started again.

Now click on the back button. Now you will see onPause methods is invoked.
Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.

*** The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.

Practical 5

Android Lab Manual Department of Computer Science and Information Technology


Aim: Android Layouts
Android Linear Layout
Android LinearLayout is a view group that aligns all children in either vertically or horizontally.

Modify the default content of res/layout/activity_main.xml file to include a few buttons in linear
layout.
No need to change string Constants.Android studio takes care of default strings
Run the application to launch the Android emulator and verify the result of the changes done in
the application.

Example 1
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"/>
   <Button android:id="@+id/btnPauseService"
       android:layout_width="270dp"
       android:layout_height="wrap_content"
       android:text="Pause"/>
   <Button android:id="@+id/btnStopService"
       android:layout_width="270dp"
       android:layout_height="wrap_content"
       android:text="Stop"/>
</LinearLayout>

Android Lab Manual Department of Computer Science and Information Technology


Example 2
<?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" >
   <TextView android:id="@+id/text"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Nisha_Text_Demo" />
   <Button android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Nisha_Button_Demo" />
   <!-- More GUI components go here  -->
</LinearLayout>

Android Lab Manual Department of Computer Science and Information Technology


Android Relative Layout
Android Relative Layout enables you to specify how child views are positioned relative to each
other. The position of each view can be specified as relative to sibling elements or relative to the
parent

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


<RelativeLayout 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/txt_instruction"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Relative view Demo"
       android:gravity="center"/>

   <TextView
       android:id="@+id/txt_1"
       android:layout_marginTop="10dp"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/txt_instruction"
       android:text="Enter User Name"/>

   <EditText
       android:id="@+id/txt_price"

Android Lab Manual Department of Computer Science and Information Technology


       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="5dp"
       android:layout_below="@id/txt_instruction"
       android:layout_alignParentRight="true"
       android:text="Nisha" />

   <TextView
       android:id="@+id/txt_2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
       android:layout_below="@+id/txt_1"
       android:text="Enter Password"/>

   <EditText
       android:id="@+id/txt_cash_down_payment"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="-10dp"
       android:layout_below="@id/txt_price"
       android:layout_alignParentRight="true"
       android:text="Nisha123" />

   <TextView
       android:id="@+id/txt_3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
       android:layout_below="@+id/txt_2"
       android:text="Enter Semester"/>
  
   <RadioGroup
       android:id="@+id/select_year"
       android:orientation="vertical"
       android:layout_centerInParent="true"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/txt_cash_down_payment">

       <RadioButton
           android:id="@+id/year2"
           android:text="I sem"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"/>
       <RadioButton
           android:id="@+id/year3"
           android:text="II sem"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"/>
       <RadioButton
           android:id="@+id/year4"

Android Lab Manual Department of Computer Science and Information Technology


           android:text="III sem"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"/>

   </RadioGroup>

   <TextView
       android:id="@+id/txt_3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/select_year"
       android:layout_centerInParent="true"
       android:text="Press below button to confirm submission"/>

   <Button
       android:id="@+id/button_loanReport"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@id/txt_3"
       android:layout_centerInParent="true"
       android:text="Submit"
       />
</RelativeLayout>

Android Lab Manual Department of Computer Science and Information Technology


Android Table Layout
Android TableLayout is going to arrange groups of views into rows and columns. You will use
the <TableRow> element to build a row in the table. Each row has zero or more cells; each cell
can hold one View object.

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
    <TableRow
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
       <TextView
           android:text="Time"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_column="1" />
       <TextClock
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/textClock"
           android:layout_column="2" />
   </TableRow>
   <TableRow>
       <TextView
           android:text="First Name"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_column="1" />
       <EditText
           android:width="200px"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />
   </TableRow>
   <TableRow>
       <TextView
           android:text="Last Name"

Android Lab Manual Department of Computer Science and Information Technology


           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_column="1" />
       <EditText
           android:width="100px"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />
   </TableRow>
   <TableRow
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
       <RatingBar
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:id="@+id/ratingBar"
           android:layout_column="2" />
   </TableRow>
   <TableRow
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"/>
   <TableRow
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
       <Button
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Submit"
           android:id="@+id/button"
           android:layout_column="2" />
   </TableRow>
</TableLayout>

Android Lab Manual Department of Computer Science and Information Technology


Practical 6

Aim: Study of Intents in android

Objective: Student should know what is intent in android and whatare the types of it.
Outcome: Student will develop a good application using the intents and its properties efficiently

An intent is a messaging object used to request any action from another app component. Intents
facilitate communication between different components in several ways. The intent is used to
launch an activity, start the services, broadcast receivers, display a web page, dial a phone call,
send messages from one activity to another activity, and so on.

Type Of Intent
Explicit Intent: Explicit intents are communicated between two activities inside the same
application. We can use explicit intents when we need to move from one activity to another
activity.
Example:- when a user wants to start a service to download a file or when a new activity gets
started in response to a user action.

//Explicit Intent
Intent send = new Intent(FirstActivtiy.this,
SecondActivity.class);
//Starts TargetActivity
startActivity(send);

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

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Android Lab Manual Department of Computer Science and Information Technology


android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="This is First Activity" />
<!--open activity2-->
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerHorizontal="true"
android:text="GO TO OTHER ACTIVITY" />
</RelativeLayout>

activity_2.xml

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


<!--activity_2-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.application.myapplication.Activity2">
<!--new activity start and Activity 2-->
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="This is Second Activity " />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerHorizontal="true"
android:text="open activity 2" />
</RelativeLayout>

MainActivity.Java

} package com.example.application.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


private Button button;

@Override

Android Lab Manual Department of Computer Science and Information Technology


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.button);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity2();
}
});
}

public void openActivity2() {


//Explicit Intent
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}

Activity2.Java
package com.example.application.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Activity2 extends AppCompatActivity {


private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Back to the MainActivity
openActivity1();
}
});
}
public void openActivity1() {
//Explicit Intent
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}

Android Lab Manual Department of Computer Science and Information Technology


Output:-

Implicit Intent: Implicit intent is communicated between two activities of an application. One

thing to note here is we should not name a specific component. In place of that we can declare a

general action to perform which allows a component from another app to handle it.

Example:- To show the user a location on a map, we can use an implicit intent.
//Implicit intent
Intent intent = new Intent();

intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(Contract.Contacts.CONTENT_URL);
startActivity(intent);

activity_main.xml

< ? xml versiоn = "1.0"


enсоding = "utf-8" ? >
<
!--асtivity_mаin-- >
<
RelаtiveLаyоut xmlns : аndrоid = "httр://sсhemаs.аndrоid.соm/арk/res/аndrоid" < !--аndrоid-- >
<
!--defаult lаyоut struсture-- >
xmlns: tооls = "httр://sсhemаs.аndrоid.соm/tооls" < !--tооls-- >
xmlns: арр = "httр://sсhemаs.аndrоid.соm/арk/res-аutо" < !--арр-- >
tооls: соntext = "соm.exаmрle.imрliсitintent.MаinАсtivity"

Android Lab Manual Department of Computer Science and Information Technology


аndrоid: lаyоut_width = "mаtсh_раrent" < !--fоr width-- >
аndrоid: lаyоut_height = "mаtсh_раrent" < !--fоr height-- > >
<
!--inрut field fоr writing website nаme-- >
<
EditText <
!--fоr inрut field-- >
аndrоid: id = "@+id/editText" < !--edittext id nаme-- >
аndrоid: lаyоut_width = "wrар_соntent" < !--fоr width-- >
аndrоid: lаyоut_height = "wrар_соntent" < !--fоr height-- > аndrоid: lаyоut_mаrginEnd = "7dр"
< !--mаrgin аt the end-- >
аndrоid: lаyоut_mаrginStаrt = "7dр" < !--mаrgin аt the stаrt-- >
аndrоid: lаyоut_mаrginTор = "70dр" < !--mаrgin аt the tор-- >
аndrоid: ems = "9" <
!--fоr аlignment-- >
аndrоid: lаyоut_аlignРаrentTор = "true"
аndrоid: lаyоut_сenterHоrizоntаl = "true" /
>
<
!--Орen webраge-- >
< Buttоn аndrоid: id = "@+id/buttоn" < !--buttоn id nаme-- >
аndrоid: lаyоut_width = "wrар_соntent" < !--fоr width-- >
аndrоid: lаyоut_height = "wrар_соntent" < !--fоr height-- >

<!--buttоn belоw editText-- >


аndrоid: lаyоut_belоw = "id/editText"
аndrоid: lаyоut_сenterHоrizоntаl = "true"
аndrоid: lаyоut_mаrginTор = "172dр"
аndrоid: lаyоut_mаrginRight = "8dр"
аndrоid: lаyоut_mаrginLeft = "156dр" <
!--disрlаy text-- >
аndrоid: text = "Visit" /
>
<
/RelаtiveLаyоut>

MainActivity.java
package com.example.implicitintent; //package name

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

Button button; //button


EditText editText; //inputtext

Android Lab Manual Department of Computer Science and Information Technology


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = findViewById(R.id.button);
editText = findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() { //add the listener on button

@Override
public void onClick(View view) {
//string type variable
String url = editText.getText()
.toString(); //for storing edtitextvalue

//Intent object and open the webpage


Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

startActivity(intent); //call a webpage


}
});
}
}
Output:-

Android Lab Manual Department of Computer Science and Information Technology


Assignment 7

Aim: To study the database in android (SQLite)

Objective: Student should know the database development in android

Outcome: Student will demonstrate the database development using SQLite for basic queries.

SQLite and Android

What is SQLite?

SQLite is an Open Source database. SQLite supports standard relational database features like
SQL syntax, transactions and prepared statements. The database requires limited memory at
runtime (approx. 250 KByte) which makes it a good candidate from being embedded into other
runtimes.

SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in
Java) and REAL (similar to double in Java).

All other types must be converted into one of these fields before getting saved in the database.
SQLite itself does not validate if the types written to the columns are actually of the defined type,
e.g. you can write an integer into a string column and vice versa.

SQLite in Android

SQLite is embedded into every Android device. Using an SQLite database in Android does not
require a setup procedure or administration of the database.

You only have to define the SQL statements for creating and updating the database. Afterwards
the database is automatically managed for you by the Android platform.

Access to a SQLite database involves accessing the file system. This can be slow.

Therefore it is recommended to perform database operations asynchronously.

I f your application creates a database, this database is by default saved in the directory
DATA/data/APP_NAME/databases/FILENAME.

The parts of the above directory are constructed based on the following rules. DATA is the path
which theEnvironment.getDataDirectory() method returns. APP_NAME is your application
name. FILENAME is the name you specify in your application code for the database.

SQLite architecture

Packages

Android Lab Manual Department of Computer Science and Information Technology


The android.database package contains all necessary classes for working with databases. The
android.database.sqlitepackage contains the SQLite specific classes.

Creating and updating database with SQLiteOpenHelper

To create and upgrade a database in your Android application you create a subclass of the
SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of
SQLiteOpenHelper, specifying the database name and the current database version.

In this class you need to override the following methods to create and update your database.

onCreate() - is called by the framework, if the database is accessed but not yet created.

onUpgrade() - called, if the database version is increased in your application code. This method
allows you to update an existing database schema or to drop the existing database and recreate it
via the onCreate() method.

Both methods receive an SQLiteDatabase object as parameter which is the Java representation of
the database.

The SQLiteOpenHelper class providest the getReadableDatabase() and getWriteableDatabase()


methods to get access to anSQLiteDatabase object; either in read or write mode.

The database tables should use the identifier _id for the primary key of the table.

Several Android functions rely on this standard.

Note:
It is good practice to create a separate class per table. This class defines static onCreate()
andonUpgrade() methods. These methods are called in the corresponding methods of
SQLiteOpenHelper. This way your implementation of SQLiteOpenHelper stays readable, even if
you have several tables.

SQLiteDatabase

SQLiteDatabase is the base class for working with a SQLite database in Android and provides
methods to open, query, update and close the database.

More specifically SQLiteDatabase provides the insert(), update() and delete() methods.

In addition it provides the execSQL() method, which allows to execute an SQL statement
directly.

The object ContentValues allows to define key/values. The key represents the table column
identifier and the value represents the content for the table record in this column. ContentValues
can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder
class .

Android Lab Manual Department of Computer Science and Information Technology


rawQuery() directly accepts an SQL select statement as input.

query() provides a structured interface for specifying the SQL query.

SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

rawQuery() Example

The following gives an example of a rawQuery() call.

Cursor cursor = getReadableDatabase().

rawQuery("select * from todo where _id = ?", new String[] { id });

query() Example
The following gives an example of a query() call.

return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,


KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, null, null, null, null,
null);

The method query() has the following parameters.

Table 1. Parameters of the query() method

Parameter Comment

String dbName The table name to compile the query against


String[] columnNames A list of which table columns to return.
Passing "null" will return all columns.

String whereClause Where-clause, i.e. filter for the selection of


data, null will select all data.
You may include ?s in the "whereClause"".
These placeholders will get replaced by the
values from the selectionArgs array
String[] selectionArgs

String[] having A filter declaring how to group rows, null


will cause the rows to not be grouped.

String[] groupBy Filter for the groups, null means no filter

String[] orderBy Table columns which will be used to order


the data, null means no ordering.

Android Lab Manual Department of Computer Science and Information Technology


If a condition is not required you can pass null, e.g. for the group by clause.

The "whereClause" is specified without the word "where", for example a "where" statement
might look like: "_id=19 and summary=?".

If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs
parameter to the query.

Cursor

A query returns a Cursor object. A Cursor represents the result of a query and basically points
to one row of the query result. This way Android can buffer the query results efficiently; as it
does not have to load all data into memory.

To get the number of elements of the resulting query use the getCount() method.

To move between individual data rows, you can use the moveToFirst() and moveToNext()
methods. The isAfterLast()method allows to check if the end of the query result has been
reached.

Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to


access the column data for the current position of the result. The "columnIndex" is the number
of the column you are accessing.

Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the
column index for a column name of the table.

A Cursor needs to be closed with the close() method call.

ListViews, ListActivities and SimpleCursorAdapter

ListViews are Views which allow to display a list of elements. ListActivities are specialized
activities which make the usage of ListViews easier. To work with databases and ListViews you
can use the SimpleCursorAdapter. The SimpleCursorAdapter allows to set a layout for each row
of the ListViews.

You also define an array which contains the column names and another array which contains
the IDs of Views which should be filled with the data.

The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed
to it. To obtain the Cursor you should use the Loader class.

Android Lab Manual Department of Computer Science and Information Technology


1. Create a basic application of Hello World on Constraint Layout.

<?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!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Garv Bhatt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.577" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:

Android Lab Manual Department of Computer Science and Information Technology


2. Create an application to add two numbers on Linear Layout.

Android Lab Manual Department of Computer Science and Information Technology


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">

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Garv Bhatt"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.528"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.577" />

<!-- on below line we are creating edit text for number 1 -->

<EditText

android:id="@+id/idEdtNumber1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20dp"

android:hint="Enter First Number"

Android Lab Manual Department of Computer Science and Information Technology


android:inputType="number"

android:textColor="@android:color/black" />

<!-- on below line we are creating edit text for number 2 -->

<EditText

android:id="@+id/idEdtNumber2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20dp"

android:hint="Enter Second Number"

android:inputType="number"

android:textColor="@android:color/black" />

<!-- on below line we are creating button for adding two numbers-->

<Button

android:id="@+id/idBtnAdd"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20dp"

android:padding="4dp"

android:text="Add"

android:textAllCaps="false"

app:background="@color/black"

app:backgroundTint="@color/black" />

<!-- on below line we are creating text view for displaying the sum -->

<TextView

android:id="@+id/idTVSum"

android:layout_width="match_parent"

Android Lab Manual Department of Computer Science and Information Technology


android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_margin="20dp"

android:padding="4dp"

android:text="Sum"

android:textAlignment="center"

android:textColor="@android:color/black"

android:textSize="20sp"

android:textStyle="bold" />

</LinearLayout>

MainActivity.java

package com.example.Garv_layout;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

// on below line creating a variables for edit text, button and text
views.

Android Lab Manual Department of Computer Science and Information Technology


private EditText numberOneEdt, numberTwoEdt;

private Button addBtn;

private TextView sumTV;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// on below line initializing variables.

numberOneEdt = findViewById(R.id.idEdtNumber1);

numberTwoEdt = findViewById(R.id.idEdtNumber2);

addBtn = findViewById(R.id.idBtnAdd);

sumTV = findViewById(R.id.idTVSum);

// adding click listener for button on below line.

addBtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

// on below line checking if edit text is empty or not.

if (!numberOneEdt.getText().toString().isEmpty() && !
numberTwoEdt.getText().toString().isEmpty()) {

// on below line getting num1 and num2 from our edit text

int num1 =
Integer.parseInt(numberOneEdt.getText().toString());

int num2 =
Integer.parseInt(numberTwoEdt.getText().toString());

// on the below line getting sum to it.

int sum = num1 + num2;

// on the below line setting sum to it for text view.

sumTV.setText(String.valueOf(sum));

Android Lab Manual Department of Computer Science and Information Technology


} else {

// on below line displaying toast message if the edit text


is empty

Toast.makeText(MainActivity.this, "Please enter both


numbers..", Toast.LENGTH_SHORT).show();

});

Output:

Android Lab Manual Department of Computer Science and Information Technology


3. Create an application for calculator in Relative layout.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

Android Lab Manual Department of Computer Science and Information Technology


android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="abhiandroid.com.calculater.MainActivity"

android:orientation="vertical"

android:gravity="top"

android:textAlignment="center"

android:background="@android:color/holo_blue_bright"

android:weightSum="1">

<TextView

android:text="@string/enter_two_numbers"

android:layout_width="match_parent"

android:id="@+id/textView"

android:layout_height="30dp"

android:gravity="center_horizontal"

android:textColorLink="?android:attr/editTextColor"

tools:textStyle="bold|italic"

android:visibility="visible"

android:textSize="24sp"

android:layout_weight="0.07" />

android:textStyle="bold|italic"

android:fontFamily="serif"

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

Android Lab Manual Department of Computer Science and Information Technology


android:id="@+id/editOp1"

android:textSize="18sp"

android:gravity="center_horizontal"

android:layout_marginBottom="5dp"

android:visibility="visible" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/editOp2"

android:textSize="18sp"

android:gravity="center_horizontal"

android:elevation="1dp" />

<LinearLayout

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<Button

android:text="+"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnadd"

android:layout_weight="0.03" />

<Button

Android Lab Manual Department of Computer Science and Information Technology


android:text="-"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnsub"

android:layout_weight="0.03" />

<Button

android:text="*"

android:layout_width="78dp"

android:layout_height="wrap_content"

android:id="@+id/btnmul"

android:layout_weight="0.03"/>

<Button

android:text="/"

android:layout_height="wrap_content"

android:id="@+id/btndiv"

android:layout_width="78dp"

android:layout_weight="0.03" />

<Button

android:text="Clear"

android:layout_width="80dp"

android:layout_height="wrap_content"

android:id="@+id/btnclr"

android:layout_weight="0.03" />

</LinearLayout>

<TextView

Android Lab Manual Department of Computer Science and Information Technology


android:text="@string/result"

android:layout_width="332dp"

android:id="@+id/textView1"

android:layout_marginTop="10dp"

android:layout_height="50dp"

android:gravity="center_horizontal"

android:textColorLink="?android:attr/editTextColor"

tools:textStyle="bold|italic"

android:textStyle="bold|italic"

android:fontFamily="serif"

android:visibility="visible"

android:textSize="30sp" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number"

android:ems="10"

android:id="@+id/result"

android:textSize="18sp"

android:text="0.00"

android:gravity="center_horizontal" />

</LinearLayout>

Main_Activity.java

package com.example.calculatora1;

import androidx.appcompat.app.AppCompatActivity;

Android Lab Manual Department of Computer Science and Information Technology


import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText opr1;

private EditText opr2;

private Button btnadd;

private Button btnsub;

private Button btnmul;

private Button btndiv;

private Button btnclr;

private TextView txtresult;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

opr1 = (EditText) findViewById(R.id.editOp1);

opr2 = (EditText) findViewById(R.id.editOp2);

btnadd = (Button) findViewById(R.id.btnadd);

btnsub = (Button) findViewById(R.id.btnsub);

btnmul = (Button) findViewById(R.id.btnmul);

btndiv = (Button) findViewById(R.id.btndiv);

Android Lab Manual Department of Computer Science and Information Technology


btnclr = (Button) findViewById(R.id.btnclr);

txtresult= (TextView) findViewById(R.id.result);

// Addition

btnadd.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if((opr1.getText().length()>0) && (opr2.getText().length()>0))

double oper1 =
Double.parseDouble(opr1.getText().toString());

double oper2 =
Double.parseDouble(opr2.getText().toString());

double result = oper1 + oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast= Toast.makeText(MainActivity.this,"Enter The


Required Numbers",Toast.LENGTH_LONG);

toast.show();

});

//Subtraction

btnsub.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if((opr1.getText().length()>0) && (opr2.getText().length()>0))

double oper1 =
Double.parseDouble(opr1.getText().toString());

Android Lab Manual Department of Computer Science and Information Technology


double oper2 =
Double.parseDouble(opr2.getText().toString());

double result = oper1 - oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast= Toast.makeText(MainActivity.this,"Enter The


Required Numbers",Toast.LENGTH_LONG);

toast.show();

});

// Multiplication

btnmul.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if((opr1.getText().length()>0) && (opr2.getText().length()>0))

double oper1 =
Double.parseDouble(opr1.getText().toString());

double oper2 =
Double.parseDouble(opr2.getText().toString());

double result = oper1 * oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast= Toast.makeText(MainActivity.this,"Enter The


Required Numbers",Toast.LENGTH_LONG);

toast.show();

Android Lab Manual Department of Computer Science and Information Technology


}

});

// Division

btndiv.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if((opr1.getText().length()>0) && (opr2.getText().length()>0))

double oper1 =
Double.parseDouble(opr1.getText().toString());

double oper2 =
Double.parseDouble(opr2.getText().toString());

double result = oper1 / oper2;

txtresult.setText(Double.toString(result));

else{

Toast toast= Toast.makeText(MainActivity.this,"Enter The


Required Numbers",Toast.LENGTH_LONG);

toast.show();

});

// Reset Feilds

btnclr.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

opr1.setText("");

opr2.setText("");

txtresult.setText("0.00");

opr1.requestFocus();

Android Lab Manual Department of Computer Science and Information Technology


}

});

Output:

4. Create an application for the registration page in Table Layout

Activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:stretchColumns="1">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Garv Bhatt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.577" />

<TableRow android:padding="5dip">

Android Lab Manual Department of Computer Science and Information Technology


<TextView
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_span="2"
android:gravity="center_horizontal"
android:text="@string/loginForm"
android:textColor="#0ff"
android:textSize="25sp"
android:textStyle="bold" />
</TableRow>

<TableRow>

<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:text="@string/userName"
android:textColor="#fff"
android:textSize="16sp" />

<EditText
android:id="@+id/userName"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:background="#fff"
android:hint="@string/userName"
android:padding="5dp"
android:textColor="#000" />
</TableRow>

<TableRow>

<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="@string/password"
android:textColor="#fff"
android:textSize="16sp" />

<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:background="#fff"
android:hint="@string/password"
android:padding="5dp"
android:textColor="#000" />
</TableRow>

<TableRow android:layout_marginTop="20dp">

Android Lab Manual Department of Computer Science and Information Technology


<Button
android:id="@+id/loginBtn"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:background="#0ff"
android:text="@string/login"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>

Main_Activity.java
package com.example.loginregister;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate a button
Button loginButton = (Button) findViewById(R.id.loginBtn);
// perform click event on the button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello world..!!!",
Toast.LENGTH_LONG).show(); // display a toast message
}
});
}

strings.xml

<resources>
<string name="app_name">TableLayoutExample</string>

Android Lab Manual Department of Computer Science and Information Technology


<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="loginForm">Login Form</string>
<string name="userName">UserName</string>
<string name="password">Password</string>
<string name="login">LogIn</string>
</resources>

Android Lab Manual Department of Computer Science and Information Technology


Android Lab Manual Department of Computer Science and Information Technology
Android Lab Manual Department of Computer Science and Information Technology

You might also like