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

NATTRAMPALLI – 635 854

(Approved by AICTE New Delhi and Affiliated to Anna University)

NAME :

REGISTER NUMBER

SUBJECT CODE / NAME : ………………………………………..

YEAR/SEM : …………………………………….......

APRIL 2019
Department of Computer Science Engineering

1
NATTRAMPALLI - 635 854. VELLORE DISTRICT

Department of Computer Science Engineering

BONAFIDE CERTIFICATE

Certified with this is a bonafide record of the practical work done by


_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 6 h Semester Computer
Science Engineering in Mobile Application Development LAB-CS6611 during the period Dec
2018 to APR 2019

Staff In-Charge Head of the Department

Submitted for the Practical examination held on……….....…………….at Bharathidasan


Engineering College, Nattrampalli.

Internal Examiner External Examiner

2
TABLE OF CONTENTS
Ex. Page Staff
Date Name of the Experiment
No No. Signature

Ex.No. CREATION OF SIMPLE UI DESIGN ANDROID APPLICATION

Aim:
To create an application that uses GUI components, Font and Colours using Android Studio.
3
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:

1. Select File\New Project from the menu to create a new project, Studio will present you with your
first project creation screen:

2. Enter Application name as shown above. Feel free to put your own name in the Company
Domain text field. As you type, you’ll notice the Package Name will automatically change to create
a reverse domain style name based on your Application name and Company Domain. Click next at
the bottom of the window to progress to the next part of the project setup.

4
3. Click Next option. The next screen is where you select device types and operating systems to target.
Want an App to focus on just Phone and Tablet? For now though you just want an App that works
on an Android Phone. This option is selected as the default, alongside the default Minimum
SDK.The Minimum SDK drop down menu sets the minimum version of Android needed to run your
app. selecting this value for your own projects is a matter of balancing the SDK capabilities you
want and the devices you want to support.

4. Choose “Blank Activity”

Getting back to the new project window, click Next in the bottom right to pick more options for
your project. This screen lets you choose a default Activity for your app. Think of an Activity as a
window within your App that displays content the user can interact with – not unlike a View Controller in

5
iOS. An activity can take up the entire screen or it could be a simple pop-up. Available activities on this
template range from a blank activity with an Action Bar right up to an Activity with
a MapView embedded. You will be making a lot of activities, so it’s good to get accustomed with them.
Select the Blank Activity option and click Next.

6
5. If you have made it this far then well done, you are at the final screen before you dig into some
actual coding. To speed this part up a little bit you will use the pre-populated default values, but
what is actually done with these values?
 Activity Name. This will give your Activity a name to refer to in code. Once the project setup is
complete Android Studio will create a .java class and use the contents of this text field to give the
class a name. This is the name you will use to refer to your Activity inside your code.
 Layout Name. You’re going to define your Activity in Java, but the layout of everything it will
show to the user is defined in a special sort of Android XML. You will learn how to read and edit
those files shortly.
Click Finish. Android Studio takes this as its cue to go do a bunch of behind-the-scenes operations and
create your project. As it shoots out some descriptions of what it’s doing from time to time, you may
notice it say something like the following:
6. You see your project name, which is familiar. But then there is this Gradle word, and then a mention
of Maven in the URL. The benefit of having a modern IDE like Android Studio is that it handles a
lot for you. But as you’re just beginning to learn how to use the software, it’s good to know, in
general, what it’s doing for you.
Cradle is a new build tool that is easy to use, but it also contains a lot of advanced options if you
investigate it further. It takes your Java code and XML layouts, and then uses the latest Android
build tools to create the app package file, known as an APK file. You can customize your
configurations to have development or production versions of the app that behave differently, or add
dependencies for third-party libraries.

7
of an Android Application

UI Elements:
Layouts: Linear Layout o Horizontal vs Vertical, Relative Layout, Table Layout, Grid Layout, Frame
Layout
Widgets: Text View, Button, Radio Button, Toggle Button, Image View, Image Button, Checkbox,
Progress Bar, Seek Bar, Rating Bar
Web View
• Spinner
Text Fields
• Edit Text o Plain text, Name, Number, Email etc.
Containers
• Scroll View , Vertical vs. Horizontal ,List View ,Grid View ,Search View
 Tab Host
• Background colour or draw able, id, padding, margin, TextColor colour value (Hex, Reba etc.)
draw able colour resource ,text Style ,typeface
7. Changing attributes (text color, background, typeface etc.) in java
TextView <<variable>> = (TextView) findViewById(R.id.<<id>>);
<<variable>>.setTextColor(getResources().getColor(R.color.<<name>>));
The color resource is defined in a “color.xml” resource file inside “values” resource directory.
E.g.:

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


<resources>
<color name="yellow">#FFFF00</color>
</resources>
<<variable>>.setBackgroundColor(getResources().getColor(R.color.<<name>>));
Changing Type Face
1. First we need to import a font face to assets directory.
2. Create an assets directory.
3. In Android Studio, select File>app>New>Java Class>Folder>Assets Folder.
4. Download a font from internet and put it under assets/fonts folder.
5. Create a new directory “font” – not necessary –
6. Modify src/MainActivity.java file to add necessary code.
7. Modify the res/layout/activity main to add respective XML components

8
XML CODING
<?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/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="HELLO WORLD"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change font size"
android:textSize="20sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change color"
android:textSize="20sp" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change font style"
android:textSize="20sp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/nature"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
Main Activity.java:

package com.example.bec.poo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

9
public class MainActivity extends AppCompatActivity {
float font =24;
int i=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t1=(TextView) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
t1.setTextSize(font);
font=font+4;
if(font==40)
font=20;
} });
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
switch(i)
{ case 1:
t1.setTextColor(Color.parseColor("#0000FF"));
break;
case 2:
t1.setTextColor(Color.parseColor("#00FF00"));
break;
case 3:
t1.setTextColor(Color.parseColor("#FF0000"));
break;
case 4:
t1.setTextColor(Color.parseColor("#800000"));
break;
} i++;
if(i==5)
i=1; } });
Button b3 = (Button) findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TextView tF = (TextView) findViewById(R.id.textView1); //find the textView with id theFont
//Now we need to create a new TypeFace from the .ttf file we imported
Typeface typeface = Typeface.createFromAsset(getAssets(),"font/Pacifico.ttf"); //Set the
typeface of the textView tF.setTypeface(typeface);
//the type-face will change at
tF.setTypeface(typeface); }
}); }}

10
11
12
8. First: On the Emulator
 Before we can run the application, we need to setup an Android Virtual Device (AVD), or
emulator, to run it on:
 Android Studio comes free with the ability to set up a software-based Android device on your
computer and run apps on it, browse websites, debug and everything you would expect. This
capability is known as the Android Emulator.
 Select the menu Tools ->Android "Android SDK and AVD Manager".
 Let’s run through creating a new AVD. Click Create Virtual Device… in the bottom left to begin
configuring a new virtual device.
 The first decision you need to make is what type of device you want to emulate.
The Category list to the left shows all the types of device you can emulate. Clicking each option
shows you what type of devices are available to you in that category. For now you just want to
emulate a phone sized device but if you wanted to emulate an Android Wear watch or an Android
TV then you have options to do so here.Select Nexus S in the list of devices available to you from
the phone category and click next.
 Your next decision is to decide what version of Android you want your virtual device to run. You
will already have one or two available to you thanks to the setup wizard, so let’s use one of them.
Select Lollipop and make sure the one selected has the value x86 in the ABI column. We want the
emulator to be running as fast as possible on our x86 computers. :)
 Click Next once this is done to move to the final screen. The last screen is simply a confirmation
of your previous choices with the option to configure some other properties of your device such
as device name, start-up orientation, and RAM size. For now leave these set as their defaults and
click Finish.
 Congratulations! With relative ease you’ve just created a fresh virtual device ready for use to test
out your new app.
 Now, close the AVD Manager to go back to Android Studio’s main view. Now that you’ve
configured everything, there’s but one step left…

13
14
15
8. We're now ready to run our application.
 Select the menu Run -> Run.
• Note: The emulator may take a long time to start up.
• Note: Another way to run your application is to right-click on the project in the Package
Explorer, then select Run As -> Android Application.

16
17
Output :

Result:
Thus the UI android application that uses GUI components, Font and Colours was successfully executed.

18
Ex.No. Layout and Event Listeners
Aim:
To create an application that uses Layout Managers and event listeners using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Layouts
1. Relative Layout
As in name this layout positions elements relative to the adjacent elements.It uses the following
attributes for each element to position them: layout:alignEnd ,layout:alignStart ,layout:toEndOf
,layout:toStartOf ,layout:alignParent , layout:centreInParent
1. We will create a Text View (Large) inside the parent Relative layout by editing the xml code:
Linear Layout
1. Linear layout are two types Horizontal and Vertical.
2. Horizontal/Vertical is set using the orientation attribute.
3. In such layout the elements are arranged in order top-to-bottom or lefttoright.
4. Let’s add a Linear Layout now. (Now you can use the drag and drop layout
editor). Change orientation to Vertical.
5. Now add an Image View to the Linear Layout.
6. Import an image to the draw able directory. (Just as we have imported font face
in previous chapter).
7. Set the src attribute to the draw able we imported. (Click the browse button and
select the file from Draw able directory).

19
Table Layout:
 As we all know table layout uses rows and columns to position elements.

 Add table layout inside the linear layout. Table layout uses Table Row layout to create rows.
 Add a Table Row to the Table Layout. Add two Buttons to the Table Row.

 Change the Id’s of the two Buttons to btnClick and btnLongClick respectively.

 we will use these buttons to implement event listeners

 Change text to Click Me! and Long Click Me! also.

 Select one of the buttons from the component tree. Pay attention to Properties window. You can see
layout: span and layout: column attributes. The table layout uses these attributes to position
elements.
 If the values are unset then uses default values (span=1 and column increments according to order of
placement).

20
Grid Layout

 This is a very useful layout. This layout has order as well as freedom.
 This layout uses orderly grids with rows and columns, span and spaces.
 Add a Grid Layout below the table layout.
 Now drag and drop a Button to the Grid Layout.
 You’ll see a green grid with many blocks.

Example:

2. Select this button and you can see that it uses attributes layout: column, layout: row, layout: row
Span, layout: column Span. These are the attributes to position to items in Grid Layout.
 Change the row Span to.
 Resize the button
 Add one more button and a text field.
 Edit the xml file to position them correctly
Final 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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sampleprogram"
android:id="@+id/txtSample"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"

21
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/txtSample"
android:layout_centerHorizontal="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal"
android:src="@drawable/poo" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tableRow"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ClickMe"
android:id="@+id/btnClick"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LongClickMe"
android:id="@+id/btnLongClick"/>
</TableRow>
</TableLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="@+id/lytGrid">
<Button
android:layout_width="202dp"
android:layout_height="156dp"
android:text="ClickorLongCLick\nMe"
android:id="@+id/btnAll"
android:layout_column="3"
android:layout_row="0"
android:layout_columnSpan="1"
android:layout_rowSpan="2" />
<Button
android:layout_width="143dp"
android:layout_height="match_parent"
android:text="Show\nMy\nName"
android:id="@+id/btnShowName"
android:layout_row="1"
android:layout_column="2"
android:layout_rowSpan="3" />
<EditText
android:layout_width="match_parent"
android:layout_height="62dp"
android:id="@+id/txtName"
22
android:layout_row="3"
android:layout_column="3"
android:hint="EnteryourName"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />
</GridLayout></LinearLayout></LinearLayout>
Setting up Java Code:

package com.example.bec.poo1;

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 {


Button clickBtn, longClickBtn, allBtn, btnShow;
TextView sample;
EditText nameTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickBtn = (Button) findViewById(R.id.btnClick);
longClickBtn = (Button) findViewById(R.id.btnLongClick);
allBtn = (Button) findViewById(R.id.btnAll);
btnShow = (Button) findViewById(R.id.btnShowName);
sample = (TextView) findViewById(R.id.txtSample);
nameTxt = (EditText) findViewById(R.id.txtName);
/*Simple Click onClick Listener*/
clickBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hai III CSE!", Toast.LENGTH_SHORT).show();
}
});
/*Implement Long Click Listener*/
longClickBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Hai BEC !",
Toast.LENGTH_SHORT).show();
return false;
}
});

allBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You Just Clicked Me!",
Toast.LENGTH_SHORT).show();
}
23
});
allBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "You clicked me for so long!",
Toast.LENGTH_SHORT).show();
return false;
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//sample.setText(nameTxt.getText().toString());
Toast.makeText(getApplicationContext(), "K.POOVAZHAKI!",
Toast.LENGTH_SHORT).show();
}
}); }}

Output:

Result: Thus the Layout and Event listener android application was successfully executed.

24
Ex.No. Layout and Event Listeners
Aim:
To create an application that uses Layout Managers and event listeners using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Setting up 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" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/background"
android:weightSum="1">
<Button
android:layout_width="266dp"
android:layout_height="wrap_content"
android:text="Green"
android:id="@+id/btnGreen"
android:layout_weight="0.07" />
<Button
android:layout_width="269dp"
android:layout_height="wrap_content"
android:text="Blue"
android:id="@+id/btnBlue"
android:layout_weight="0.07" /> </LinearLayout>
</LinearLayout>
Setting up Java:
package com.example.bec.poo2;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
25
public class MainActivity extends AppCompatActivity {
LinearLayout background;
Button btnGreen, btnBlue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (LinearLayout) findViewById(R.id.background);
btnGreen = (Button) findViewById(R.id.btnGreen);
btnBlue = (Button) findViewById(R.id.btnBlue);
btnGreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
background.setBackgroundColor(Color.parseColor("#00ff00")); } });
btnBlue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
background.setBackgroundColor(Color.parseColor("#006699")); } });
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}}
Output :

Result: Thus the android Event Listener application was successfully executed.

26
ExNo. CALCULATOR APPLICATION

Aim: To create a native calculator application using Android Studio.


Algorithm:
Using the Android Studio create a project of the type mobile application.
 Create a simple application in the project.
 Click on the Design tab and design the prototype of the application.
 Click on source tab and modify the application logic of the application.
 Save the project.
 Right click on the project and click on deploy and undeploy.
 Then test the android application.

Steps:
• In this Tutorial we are going to start a new project Calculator.

• First of all, to start with we are going to create a simple calculator to do simple arithmetic
operations (i.e., one operator and two operands).
• Start Android Studio .Create a new Project.

• Target Android devices >> Check Phone and Tablet

• Select a Blank Activity >>

• Click Finish keeping the default settings for Activity (Name: Main Activity…..).

Skip to XML Code


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"
android:textSize="20sp" />
<EditText

27
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<Button
android:id="@+id/Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+"
android:textSize="30sp"/>
<Button
android:id="@+id/Sub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="-"
android:textSize="30sp"/>
<Button
android:id="@+id/Mul"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="*"
android:textSize="30sp"/>
<Button
android:id="@+id/Div"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="/"
android:textSize="30sp"/>
</LinearLayout>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Answer is"
android:textSize="30sp"
android:gravity="center"/>
</LinearLayout>
Setting up

28
.v7.app.AppCompatActivity;
import android.os.Bundle;
import

Button Sub;
Button Mul;
Button Div;
TextView Result;
@Override

public void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(

//Defining the Views


EditText Num1;
EditText Num2;
Button Add;
.layout.activity

_main);
//Referring the Views
Num1 = (EditText) findViewById(R.id.editText1);
Num2 = (EditText) findViewById(R.id.editText2);
Add = (Button) findViewById(R.id.Add);
Sub = (

Button) findViewById(R.id.Sub);
Mul = (Button) findViewById(R.id.Mul);

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


Result = (R android. Java

package com.example.bec.poocalci;
import android.support text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
29
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
TextView) findViewById(R.id.textView);
// set a listener
Add.setOnClickListener(this);
Sub.setOnClickListener(this);
Mul.setOnClickListener(this);
Div.setOnClickListener(this);
}
@Override
public void onClick (View v)
{
float num1 = 0;
float num2 = 0;
float result = 0;
String oper = "";
// check if the fields are empty
if (TextUtils.isEmpty(Num1.getText().toString()) || TextUtils.isEmpty(Num2.getText().toString()))
return;
// read EditText and fill variables with numbers
num1 = Float.parseFloat(Num1.getText().toString());
num2 = Float.parseFloat(Num2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId())
{
case R.id.Add:
oper = "+";
result = num1 + num2;
break;
case R.id.Sub:
oper = "-";
result = num1 - num2;
break;
case R.id.Mul:
oper = "*";
result = num1 * num2;
break;
case R.id.Div:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
Result.setText(num1 + " " + oper + " " + num2 + " = " + result); }}

Output:

30
Result: Thus the android Calculator application was successfully executed.

Ex.no. CREATION OF SIMPLE GRAPHICAL APPLICATION

Aim:
To create an application that draws basic graphical primitives on the screen using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:

31
1. View class which is used to draw graphical items on to the android app screen.
2. In this exercise we will draw some graphic primitives using Paint, View, Canvas and a method on
Draw ().
3. Go ahead and start our project.
4. In the Add an Activity section Select No Activity.
5. Open the Project Window.
6. Expand the app and then the java folders.

7. Now we need to extend the View Class to the Sample Canvas class we just created. Go ahead and edit
the Java File.
8. Now we need to create a Paint object.
9. So above the constructor definition add the following code.
10. Now place the cursor below the constructor definition and press [ALT] + [Insert] and select Override
Methods from the popup Menu.
11. To draw a rectangle we use the function:
canvas.drawRect (float left, float top, float right, float bottom, Paint paint) ;
The arguments can be depicted as shown below:
The co-ordinates of: A = (left, top) B = (right, bottom) paint is the paint object we created.
Let’s draw a rectangle now:
canvas.drawRect(100,100,300,300,paint) ;
9. Drawing a circle
canvas.drawCircle (float cx, float cy, float radius, Paint paint) The co-ordinates of A =
(cx,cy).And the length AB = radius.Let’s draw a circle with fill color green center at (200,200) and radius
paint.setColor(Color.GREEN) ; canvas.drawCircle(200,200,75,paint) ;
Setting up Java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android package com.example.bec.poo4;

.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(new myview(this));
}
private class myview extends View
32
{
public myview(Context context)
{
super(context);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint paint=new Paint();
paint.setTextSize(40);
paint.setColor(Color.GREEN);
canvas.drawText("Circle", 55, 30, paint);
paint.setColor(Color.RED);
canvas.drawCircle(100, 150,100, paint);
paint.setColor(Color.GREEN);
canvas.drawText("Rectangle", 255, 30, paint);
paint.setColor(Color.YELLOW);
canvas.drawRect(250, 50,400,350, paint);
paint.setColor(Color.GREEN);
canvas.drawText("SQUARE", 55, 430, paint);
paint.setColor(Color.BLUE);
canvas.drawRect(50, 450,150,550, paint);
paint.setColor(Color.GREEN);
canvas.drawText("LINE", 255, 430, paint);
paint.setColor(Color.RED);
canvas.drawLine(250, 500, 350, 500, paint);
} }}

Content_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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"></LinearLayout>

Output:

33
Result: Thus the android Graphical Primitive Screens application was successfully executed.

Ex.No. CREATION OF SIMPLE DATA HANDLING APPLICATION

Aim:
To create an application that makes use of database using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
34
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
 To use a database to save and access data.
 We will use the SQLite Database and SQLiteOpenHelper classes to implement
database handling.
 Open the activity_main.xml layout and in my android studio 1.5 there is bunch of custom
views with a floating button.
Setting up XML:
"
android:layout_x="150dp"
android:layout_y="50dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/name"
android:layout_x="30dp"
android:layout_y="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout" android:stretchColumns="0"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:text="@string/title" android:layout_x="110dp"
android:layout_y="10dp" android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:text="@string/empid"
android:layout_x="30dp"
android:layout_y="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editEmpid"
android:inputType="number +id/editName"
android:inputType="text"
android:layout_x="150dp"
android:layout_y="100dp"
35
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/salary"
android:layout_x="30dp"
android:layout_y="150dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editsalary"
android:inputType="number"
android:layout_x="150dp"
android:layout_y="150dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnAdd"
android:text="@string/add"
android:layout_x="30dp"
android:layout_y="200dp"
android:layout_width="130dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnDelete"
android:text="@string/delete"
android:layout_x="160dp"
android:layout_y="200dp"
android:layout_width="130dp"
android:layout_height="40dp"/>n
<Button android:id="@+id/btnModify"
android:text="@string/modify"
android:layout_x="30dp"
android:layout_y="250dp"
android:layout_width="130dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnView"
android:text="@string/view"
android:layout_x="160dp"
android:layout_y="250dp"
android:layout_width="130dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnViewAll"
android:text="@string/view_all"
android:layout_x="85dp"
android:layout_y="300dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
</AbsoluteLayout></LinearLayout>

Setting up string.xml
<resources>
<string name="app_name">First5</string>
<string name="hello">Hello World, Employee detail Activity!</string>
<string name="title">Employee Details</string>
<string name="empid">Enter Employee ID: </string>
<string name="name">Enter Name: </string>
<string name="salary">Enter salary: </string>
<string name="add">Add Employee</string>
<string name="delete">Delete Employee</string>
36
<string name="modify">Modify Employee</string>
<string name="view">View Employee</string>
<string name="view_all">View All Employee</string>
</resources>

Setting up java
package com.example.bec.first5;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
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 implements View.OnClickListener {
EditText editEmpid,editName,editsalary;
Button btnAdd,btnDelete,btnModify,btnView,btnViewAll;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editEmpid=(EditText)findViewById(R.id.editEmpid);
editName=(EditText)findViewById(R.id.editName);
editsalary=(EditText)findViewById(R.id.editsalary);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnDelete=(Button)findViewById(R.id.btnDelete);
btnModify=(Button)findViewById(R.id.btnModify);
btnView=(Button)findViewById(R.id.btnView);
btnViewAll=(Button)findViewById(R.id.btnViewAll);
btnAdd.setOnClickListener((View.OnClickListener) this);
btnDelete.setOnClickListener((View.OnClickListener) this);
btnModify.setOnClickListener((View.OnClickListener) this);
btnView.setOnClickListener((View.OnClickListener) this);
btnViewAll.setOnClickListener((View.OnClickListener) this);
db=openOrCreateDatabase("EmployeeDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS employee(empid VARCHAR,name
VARCHAR,salary VARCHAR);");
}
@Override
public void onClick(View view) {
if(view==btnAdd)
{
if(editEmpid.getText().toString().trim().length()==0||
editName.getText().toString().trim().length()==0||
editsalary.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO employee VALUES('"+editEmpid.getText()
+"','"+editName.getText()+ "','"+editsalary.getText()+"');");
showMessage("Success", "Record added");
37
clearText();
}
if(view==btnDelete)
{
if(editEmpid.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Employee id");
return; }
Cursor c=db.rawQuery("SELECT * FROM employee WHERE
empid='"+editEmpid.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM employee WHERE empid='"+editEmpid.getText()+"'");
showMessage("Success", "Record Deleted");
} else
{
showMessage("Error", "Invalid Employee id");
}
clearText();
}
if(view==btnModify)
{
if(editEmpid.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Employee id");
return;
}
Cursor c=db.rawQuery("SELECT * FROM employee WHERE
empid='"+editEmpid.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE employee SET name='"+editName.getText()
+"',salary='"+editsalary.getText()+ "' WHERE empid='"+editEmpid.getText()+"'");
showMessage("Success", "Record Modified");
} else
{
showMessage("Error", "Invalid Rollno");
} clearText();
}
if(view==btnView)
{
if(editEmpid.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Employee id");
return;
}
Cursor c=db.rawQuery("SELECT * FROM employee WHERE
empid='"+editEmpid.getText()+"'", null);
if(c.moveToFirst())
{
editName.setText(c.getString(1)); editsalary.setText(c.getString(2));
} else
{
showMessage("Error", "Invalid Employee id"); clearText();
}
38
}
if(view==btnViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM employee", null); if(c.getCount()==0)
{
showMessage("Error", "No records found"); return;
}
StringBuffer buffer=new StringBuffer(); while(c.moveToNext())
{
buffer.append("Employee id: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("salary: "+c.getString(2)+"\n\n");
}
showMessage("Employee details Details", buffer.toString());
} }
public void showMessage(String title,String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
editEmpid.setText("");
editName.setText("");
editsalary.setText("");
editEmpid.requestFocus(); } }

Output:

Result: Thus the android Database handling application was successfully executed.

Ex.No. CREATION OF SIMPLE RSS FEED PARSING APPLICATION


39
Aim:
To develop an application that parse RSS feeds from XML RSS File in internet using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:
 Create a new project with an empty activity.
 Edit the xml layout file to create a layout with a List View with id lstMain.
Setting up XML file
<?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" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Setting up Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bec.poorssfeed">
<uses-permission android:name="android.permission.INTERNET"/>
<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>

Setting up Main Activity java:

40
package com.example.bec.poorssfeed;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity


{
List headlines;
List links;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new MyAsyncTask().execute();
}
class MyAsyncTask extends AsyncTask<Object,Void,ArrayAdapter>
{
@Override
protected ArrayAdapter doInBackground(Object[] params)
{
headlines = new ArrayList();
links = new ArrayList();
try
{
URL url = new URL("https://codingconnect.net/feed");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equalsIgnoreCase("item"))
{
41
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("title"))
{
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
}
else if (xpp.getName().equalsIgnoreCase("link"))
{
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}
else if(eventType==XmlPullParser.END_TAG &&
xpp.getName().equalsIgnoreCase("item"))
{
insideItem=false;
}
eventType = xpp.next(); //move to next element
}

}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayAdapter adapter)
{
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Uri uri = Uri.parse((links.get(position)).toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
public InputStream getInputStream(URL url)
{
try
{
return url.openConnection().getInputStream();
}
42
catch (IOException e)
{
return null;
}
}
}

Result: Thus the android RSS feed application was successfully executed.

43
Ex.No. CREATION OF MULTITHREADING IN ANDROID APPLICATION
Aim:
To develop Multithreading in an application using Android Studio.
Algorithm:
1. Using the Android Studio create a project of the type mobile application.
2. Create a simple application in the project.
3. Click on the Design tab and design the prototype of the application.
4. Click on source tab and modify the application logic of the application.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the android application.
Steps:

• When an application is launched, the system creates a thread of execution for the
application, called "main." This thread is very important because it is in charge of dispatching
events to the appropriate user interface widgets, including drawing events.
• It is also the thread in which your application interacts with components from the
Android UI toolkit (components from the android.widget and android.view packages). As such,
the main thread is also sometimes called the UI thread.
• The system does not create a separate thread for each instance of a component. All
components that run in the same process are instantiated in the UI thread, and system calls to
each component are dispatched from that thread.
• When your app performs intensive work in response to user interaction, this single thread
model can yield poor performance unless you implement your application properly.
• Specifically, if everything is happening in the UI thread, performing long operations such
as network access or database queries will block the whole UI.
• When the thread is blocked, no events can be dispatched, including drawing events. From
the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked
for more than a few seconds (about 5 seconds currently) the user is presented with the infamous
"application not responding" (ANR) dialog.
• Additionally, the Andoid UI toolkit is not threadsafe. So, you must not manipulate your
UI from a worker thread—you must do all manipulation to your user interface from the UI
thread. Thus, there are simply two rules to Android's single thread model:
• Do not block the UI thread.

• Do not access the Android UI toolkit from outside the UI thread?

WORKER THREADS
44
Because of the single thread model described above, it's vital to the responsiveness of your application's
UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you
should make sure to do them in separate threads ("background" or "worker" threads).

• We are going to create an app that loads image bitmap from a URL and sets it to an
ImageView.
• We are using two interface here – The User Interface and the Network Interface, we need
to implement multithreading i.e. create a new thread to interact with the network.
• Create a new Project (Multi Threading) with an empty activity (MainActivity).
• Edit the activity_main.xml to add an ImageView and a Button which when clicked loads
image to the ImageView. Testing:
 Run the application in an emulator or a device and test it.
 You need to be connected to internet to load image from internet.

Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_margin="50dp"
android:layout_gravity="center" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center"
android:text="Load Image 1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center"
android:text="Load image 2" />
</LinearLayout>

Setting up Java:
package com.example.bec.poo7;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
45
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


ImageView img;
Button bt1,bt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
bt2= (Button) findViewById(R.id.button2);
img = (ImageView)findViewById(R.id.imageView);

bt1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new Runnable()
{
@Override
public void run()
{
img.post(new Runnable()
{
@Override
public void run()
{
img.setImageResource(R.drawable.india1);
}
});
}
}).start();
}
});

bt2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new Runnable()
{
@Override
public void run()
{
img.post(new Runnable()
{
@Override
public void run()
{
img.setImageResource(R.drawable.india2);
}
46
});
}
}).start();
}
});
}
}

Output:

Result: Thus the android Multithreading application was successfully executed.

47
Ex.No. CREATION OF MULTITHREADING IN ANDROID APPLICATION
Aim:
To develop Multithreading in an application using Android Studio.
Algorithm:
8. Using the Android Studio create a project of the type mobile application.
9. Create a simple application in the project.
10. Click on the Design tab and design the prototype of the application.
11. Click on source tab and modify the application logic of the application.
12. Save the project.
13. Right click on the project and click on deploy and undeploy.
14. Then test the android application.
Steps:
• When an application is launched, the system creates a thread of execution for the
application, called "main." This thread is very important because it is in charge of dispatching
events to the appropriate user interface widgets, including drawing events.
• It is also the thread in which your application interacts with components from the
Android UI toolkit (components from the android.widget and android.view packages). As such,
the main thread is also sometimes called the UI thread.
• The system does not create a separate thread for each instance of a component. All
components that run in the same process are instantiated in the UI thread, and system calls to
each component are dispatched from that thread.
• When your app performs intensive work in response to user interaction, this single thread
model can yield poor performance unless you implement your application properly.
• Specifically, if everything is happening in the UI thread, performing long operations such
as network access or database queries will block the whole UI.
• When the thread is blocked, no events can be dispatched, including drawing events. From
the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked
for more than a few seconds (about 5 seconds currently) the user is presented with the infamous
"application not responding" (ANR) dialog.
• Additionally, the Andoid UI toolkit is not threadsafe. So, you must not manipulate your
UI from a worker thread—you must do all manipulation to your user interface from the UI
thread. Thus, there are simply two rules to Android's single thread model:
• Do not block the UI thread.

• Do not access the Android UI toolkit from outside the UI thread?

WORKER THREADS

48
Because of the single thread model described above, it's vital to the responsiveness of your application's
UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you
should make sure to do them in separate threads ("background" or "worker" threads).

• We are going to create an app that loads image bitmap from a URL and sets it to an
ImageView.
• We are using two interface here – The User Interface and the Network Interface, we need
to implement multithreading i.e. create a new thread to interact with the network.
• Create a new Project (Multi Threading) with an empty activity (MainActivity).
• Edit the activity_main.xml to add an ImageView and a Button which when clicked loads
image to the ImageView. Testing:
 Run the application in an emulator or a device and test it.
 You need to be connected to internet to load image from internet.
Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progressBar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtdis" />

49
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="@+id/button"
android:onClick="startprogress"/>
</LinearLayout></LinearLayout>
Setting up Java

package com.library.bec.ex_multithrading1;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {


private ProgressBar progress;
private TextView t1;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) findViewById(R.id.progressBar);
t1 = (TextView) findViewById(R.id.txtdis);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
public void startprogress(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
final int value = i;

50
doSomeWork();
progress.post(new Runnable() {
@Override
public void run() {
t1.setText("Updating");
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}
private void doSomeWork() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
Output:

Result: Thus the android GPS location application was successfully executed.

51
Ex.No. CREATION OF SIMPLE GPS LOCATION APPLICATION
Aim:
To develop a GPS Location application using Android Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Steps:
For this we will use:
• System location service

• LocationManager and LocationListener

• Permission to access FINE_LOCATION

• Start a new project “GeoLocation” with an empty activity.

• Edit the activity_main.xml to change the parent layout to LinearLayout (Verical) and to
add the GPS locating cannot be used indoors.
If using an emulator you need to pass the location values yourself using the settings of the emulator.
So, it is better to test it in a device outdoor.
Setting up 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" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/Linearlayout"
android:layout_below="@+id/textview1"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
52
android:id="@+id/textview1"
android:layout_alignParentTop="true"
android:text="Lattitude"
android:textSize="34dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/Linearlayout1"
android:layout_below="@+id/textview1"
android:layout_alignParentStart="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textview2"
android:layout_alignParentTop="true"
android:text="Longitude"
android:textSize="34dp" />
</LinearLayout>
</LinearLayout>
Setting up Java:

package com.javasamples.ex_8_gps;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {


LocationManager lmanager;
String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lmanager.getBestProvider(criteria, false);
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
53
Manifest.permission.ACCESS_COARSE_LOCATION) !=
packageManager.PERMISSION_GRANTED) {
return;
}
if (provider != null && !provider.equals("")) {
Location location = lmanager.getLastKnownLocation(provider);
lmanager.requestLocationUpdates(provider, 20000, 1, (LocationListener) this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location not available",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getBaseContext(), "Location Found", Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationChanged(Location location) {
TextView t1 = (TextView) findViewById(R.id.textview1);
TextView t2 = (TextView) findViewById(R.id.textview2);

t1.setText("" + location.getLatitude());
t2.setText("" + location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}}

Setting up Manifest.xml:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javasamples.ex_8_gps">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
54
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Output:

55
Result: Thus the android GPS location application was successfully executed.

Ex.No. CREATION OF WRITING DATA TO SD CARD APPLICATION


Aim:
To develop a Writing data to SD Card application using Android Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Steps:
• To learn how to use memory to store data in android studio app.
• For this we use output stream classes.
• Here we will use FileOutputStream to write data and FileInputStream to read data.
• Edit the layout to add a text field through which we will input the text to be written into
file.
• Two buttons to execute writing and reading of file respectively.

• A TextView to display the text inside the file after reading.


Setting up XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="30dp" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
56
android:text="Write Data"
android:textSize="30dp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Read data"
android:textSize="30dp" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Clear"
android:textSize="30dp" />
</LinearLayout>
Setting up Manifest.XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bec.poosdcard">
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
></uses-permission>
<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>

Setting up Java:
package com.example.bec.poosdcard;

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.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;

57
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity


{
EditText e1;
Button write,read,clear;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= (EditText) findViewById(R.id.editText);
write= (Button) findViewById(R.id.button);
read= (Button) findViewById(R.id.button2);
clear= (Button) findViewById(R.id.button3);
write.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message=e1.getText().toString();
try
{
File f=new File("/sdcard/myfile.txt");
f.createNewFile();
FileOutputStream fout=new FileOutputStream(f);
fout.write(message.getBytes());
fout.close();
Toast.makeText(getBaseContext(),"Data Written in
SDCARD",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
read.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message;
String buf = "";
try
{
File f = new File("/sdcard/myfile.txt");
FileInputStream fin = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
while ((message = br.readLine()) != null)
{
buf += message;
}
e1.setText(buf);
58
br.close();
fin.close();
Toast.makeText(getBaseContext(),"Data Recived from
SDCARD",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});

clear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
e1.setText("");
}
});
}
}

OUTPUT:

59
Result: Thus the android Writing data to SD Card application was successfully executed.

Ex.No. CREATION SIMPLE ALARM CLOCK APPLICATION


Aim:
To develop a Simple Alarm Clock application using Android Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Setting up XML.file

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:checked="false"
android:onClick="OnToggleClicked" />
</LinearLayout>

Setting up Java

package com.example.bec.pooclock;

import android.app.AlarmManager;
60
import android.app.PendingIntent;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {


TimePicker alarmTimePicker;
PendingIntent pendingIntent;
AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void OnToggleClicked(View view)
{
long time;
if (((ToggleButton) view).isChecked())
{
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

time=(calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));
if(System.currentTimeMillis()>time)
{
if (calendar.AM_PM == 0)
time = time + (1000*60*60*12);
else
time = time + (1000*60*60*24);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else
{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}

61
Setting up BroadcastReceiver java

package com.example.bec.pooclock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;
/**
* Created by bec on 18-12-2018.
*/
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}}

Setting up Manifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bec.pooclock">
<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=".AlarmReceiver" >
</receiver>
</application>
</manifest>

62
Output:

63
Result: Thus the android Alarm Clock application was successfully executed.

Ex.No. CREATION OF SIMPLE ALERT MESSAGE


Aim:
To develop an application that creates an alert upon receiving a message application using Android
Studio.
Algorithm:
• Using the Android Studio create a project of the type mobile application.
• Create a simple application in the project.
• Click on the Design tab and design the prototype of the application.
• Click on source tab and modify the application logic of the application.
• Save the project.
• Right click on the project and click on deploy and undeploy.
• Then test the android application.
Steps:
Setting up the Project
• Create a new project “Alert application” with an empty activity.

• Use the Layout editor to add two buttons to start and cancel alarm respectively.

• Set their ids to btnStart and btnCancel.


Setting up XML.file

<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Message"
android:textSize="34sp"
android:id="@+id/textview"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
64
android:ems="10"
android:id="@+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notify"
android:id="@+id/button"
android:textSize="34sp"
android:onClick="notify"
android:layout_gravity="bottom" /></LinearLayout>

Setting up Java

package com.example.bec.pooalert;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public void notify(View view) {
EditText E1 = (EditText) findViewById(R.id.editText);
Intent intent = new Intent(this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new Notification.Builder(this).setContentTitle("New
Message").setContentText(E1.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentInte
nt(pendingIntent).build();
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
int l;
l = Notification.FLAG_AUTO_CANCEL;
manager.notify(0, notification);
}
}

Output:

65
Result: Thus the android application for display alert message was successfully executed.

66

You might also like