0% found this document useful (0 votes)
80 views56 pages

Mad Lab Manual - Formatted

This document provides instructions for developing a simple Android calculator application using Android Studio. It includes the layout and program code for the calculator app, which has two edit texts for inputting numbers, buttons for the basic math operations, and a text view to display the result. The layout uses linear and relative layouts to position the elements. The program code in the MainActivity class handles the button click events to perform the calculations and display the output.

Uploaded by

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

Mad Lab Manual - Formatted

This document provides instructions for developing a simple Android calculator application using Android Studio. It includes the layout and program code for the calculator app, which has two edit texts for inputting numbers, buttons for the basic math operations, and a text view to display the result. The layout uses linear and relative layouts to position the elements. The program code in the MainActivity class handles the button click events to perform the calculations and display the output.

Uploaded by

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

COMPUTER SCIENCE AND ENGINEERING

M.KUMARASAMY COLLEGE OF ENGINEERING


(Autonomous)
AFFILIATED TO ANNA UNIVERSITY CHENNAI

PERTINENT TO REGULATION 2016

16CS513
MOBILE APPLICATION DEVELOPMENT LAB MANUAL

1
COMPUTER SCIENCE AND ENGINEERING

Ex No:1 ANDROID PLATFORM AND PROJECT STRUCTURE

ANDROID:

Android is an open source and Linux-based operating system for mobile devices such
as smartphones and tablet computers. Android was developed by the Open Handset Alliance,
led by Google, and other companies. It is a complete set of software for mobile devices such
as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc.

It contains a linux-based Operating System, middleware and key mobile applications.

It can be thought of as a mobile operating system. But it is not limited to mobile only. It is
currently used in various devices such as mobiles, tablets, televisions etc.

ANDROID ARCHITECTURE:

2
COMPUTER SCIENCE AND ENGINEERING

ANDROID APPLICATIONS:
Android applications are usually developed in the Java language using the Android
Software Development Kit.

Once developed, Android applications can be packaged easily and sold out either through a
store such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon
Appstore.

Android powers hundreds of millions of mobile devices in more than 190 countries around the
world. It's the largest installed base of any mobile platform and growing fast. Every day more
than 1 million new Android devices are activated worldwide.

HISTORY OF ANDROID:
The code names of android ranges from A to N currently, such as Aestro, Blender,
Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean,
KitKat, Lollipop and Marshmallow

API LEVEL:
API Level is an integer value that uniquely identifies the framework API revision
offered by a version of the Android platform.

LAYOUT:
A layout describes the appearance of the screen. Layouts are written as XML files and
they tell Android how the different screen elements are arranged. A layout defines the structure
for a user interface in your app, such as in an activity. All elements in the layout are built using
a hierarchy of View and ViewGroup objects. A View usually draws something the user can see
and interact with. A layout may contain any type of widgets such as buttons, labels, textboxes,
and so on.

ACTIVITY
An activity is a single, defined thing that your user can do. You might have an activity
to compose an email, take a photo, or find a contact. Activities are usually associated with
one screen, and they’re written in Java. An activity is a single, focused thing that the user can

3
COMPUTER SCIENCE AND ENGINEERING

do. Almost all activities interact with the user, so the Activity class takes care of creating a
window for you in which you can place your UI with Activity.SetContentView(View).

RESOURCES
There are many more items which you use to build a good Android application. Apart
from coding for the application, you take care of various other resources like static content that
your code uses, such as bitmaps, colors, layout definitions, user interface strings, animation
instructions, and more. These resources are always maintained separately in various sub-
directories under res/ directory of the project

ANDROID VIRTUAL DEVICE


The Android emulator allows you to run your app on an Android virtual device
(AVD). The AVD behaves just like a physical Android device. You can set up numerous
AVDs, each emulating a different type of device.

The emulator is an application that re-creates the exact hardware environment of an Android
device: from its CPU and memory, through to the sound chips and the video display. The
emulator is built on an existing emulator called QEMU, which is similar to other virtual
machine applications you may have used, like VirtualBox or VMWare.

MANIFEST FILE
AndroidManifest.xml contains information about the app itself. It lives in the
app/src/main folder.

ANDROID SDK
The Android Software Development Kit contains the libraries and tools you need to
develop Android apps

ANDROID STUDIO
Android Studio, includes all the tools you need to develop your Android apps. IntelliJ
IDEA is one of the most popular IDEs for Java development. Android Studio is a version of
IDEA that includes a version of the Android SDK and extra GUI tools to help you with your

4
COMPUTER SCIENCE AND ENGINEERING

app development. Android Studio gives you templates you can use to help you create new
apps and classes, and it makes it easy to do things such as package your apps and run them.

ANDROID RUNTIME
Code doesn’t actually run inside an ordinary Java VM. It runs on the Android runtime
(ART) instead, and on older devices it runs in a predecessor to ART called Dalvik. This means
that you write your Java source code, compile it into .class files using the Java compiler, and
then the .class files get stitched into a single file in DEX format, which is smaller, more efficient
bytecode. ART then runs the DEX code. ART can convert the DEX bytecode into native code
that can run directly on the CPU of the Android device. This makes the app run a lot faster, and
use a lot less battery power.

5
COMPUTER SCIENCE AND ENGINEERING

Ex No:2 DEVELOPING A SIMPLE ANDROID APPLICATION

OBJECTIVE OF THE EXPERIMENT


To develop an Android Native Calculator application using android studio.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:
<?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">

<LinearLayout
android:id="@+id/ll1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:orientation="horizontal">

6
COMPUTER SCIENCE AND ENGINEERING

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:ems="5"
android:inputType="number"
android:textSize="20sp" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:ems="5"
android:inputType="number"
android:textSize="20sp" />
</LinearLayout>

<LinearLayout
android:id="@+id/ll2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="167dp"
android:orientation="horizontal">

7
COMPUTER SCIENCE AND ENGINEERING

<Button
android:id="@+id/btnAdd"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:onClick="Add"
android:text="+"
android:textSize="30sp" />

<Button
android:id="@+id/btnSub"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:onClick="Substract"
android:text="-"
android:textSize="30sp" />

<Button
android:id="@+id/btnMul"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:onClick="Multiply"
android:text="*"
android:textSize="30sp" />

<Button
android:id="@+id/btnDiv"
android:layout_width="55dp"

8
COMPUTER SCIENCE AND ENGINEERING

android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:text="/"
android:textSize="30sp" />
</LinearLayout>

<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="180dp"
android:text="Answer is"
android:textSize="35sp" />
</RelativeLayout>

Activity:

package com.example.naveenrajy.ex1nativecalc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText editTextN1;
EditText editTextN2;
Button buttonDiv;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonDiv = findViewById(R.id.btnDiv);

9
COMPUTER SCIENCE AND ENGINEERING

result = findViewById(R.id.resultText);
editTextN1 = findViewById(R.id.editText1);
editTextN2 = findViewById(R.id.editText2);

View.OnClickListener ocl = new View.OnClickListener() {


@Override
public void onClick(View v) {
if(TextUtils.isEmpty(editTextN1.getText().toString()) ||
TextUtils.isEmpty(editTextN2.getText().toString()))
return;
float div;
String n1 = editTextN1.getText().toString();
int num1 = Integer.valueOf(n1);
String n2 = editTextN2.getText().toString();
int num2 = Integer.valueOf(n2);
div = (float)num1 / (float)num2;
result.setText(num1+" / "+num2+" = "+div);
}
};
buttonDiv.setOnClickListener(ocl);
}

public void Add(View view){


if(TextUtils.isEmpty(editTextN1.getText().toString()) ||
TextUtils.isEmpty(editTextN2.getText().toString()))
return;
int sum;
String n1 = editTextN1.getText().toString();
int num1 = Integer.valueOf(n1);
String n2 = editTextN2.getText().toString();
int num2 = Integer.valueOf(n2);
sum = num1 + num2;
result.setText(num1+" + "+num2+" = "+sum);
}

public void Substract(View view){


if(TextUtils.isEmpty(editTextN1.getText().toString()) ||
TextUtils.isEmpty(editTextN2.getText().toString()))
return;
int sub;
String n1 = editTextN1.getText().toString();
int num1 = Integer.valueOf(n1);
String n2 = editTextN2.getText().toString();
int num2 = Integer.valueOf(n2);
sub = num1 - num2;
result.setText(num1+" - "+num2+" = "+sub);
}

public void Multiply(View view){

10
COMPUTER SCIENCE AND ENGINEERING

if(TextUtils.isEmpty(editTextN1.getText().toString()) ||
TextUtils.isEmpty(editTextN2.getText().toString()))
return;
int mul;
String n1 = editTextN1.getText().toString();
int num1 = Integer.valueOf(n1);
String n2 = editTextN2.getText().toString();
int num2 = Integer.valueOf(n2);
mul = num1 * num2;
result.setText(num1+" * "+num2+" = "+mul);
}

11
COMPUTER SCIENCE AND ENGINEERING

SAMPLE OUTPUT

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

12
COMPUTER SCIENCE AND ENGINEERING

Ex No:3 CREATING APPLICATIONS WITH MULTIPLE ACTIVITIES AND


A SIMPLE MENU USING LISTVIEW

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application with multiple activities and simple menu using list view..

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

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

<ListView
android:id="@+id/lview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

13
COMPUTER SCIENCE AND ENGINEERING

activity_list.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:id="@+id/listLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ListActivity">

<TextView
android:id="@+id/textViewList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="40sp" />
</LinearLayout>

activity_second.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=".SecondActivity">

<ImageView
android:id="@+id/imageViewFlag"
android:layout_width="172dp"
android:layout_height="159dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="24dp"
android:layout_marginTop="18dp"
android:src="@drawable/india" />

<TextView
android:id="@+id/textViewCountry"

14
COMPUTER SCIENCE AND ENGINEERING

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="38dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_marginTop="20dp"
android:text="@string/India"
android:textSize="20sp" />
</LinearLayout>

strings.xml

<resources>
<string name="app_name">Ex2ListViewFlags</string>
<string-array name="options">
<item>India</item>
<item>England</item>
<item>China</item>
</string-array>
<string name="India">The National Flag of India is a horizontal rectangular tricolour of
India saffron, white and India green; with the Ashoka Chakra, a 24-spoke wheel, in navy blue
at its centre
</string>
<string name="China">The flag of China, also known as the Five-star Red Flag, is a red
field charged in the canton (upper corner nearest the flagpole) with five golden stars.</string>
<string name="Japan">The Nisshōki flag is designated as the national flag in the Law
Regarding the National Flag and National Anthem, which was promulgated and became
effective on August 13, 1999.</string>
<string name="America">It consists of thirteen equal horizontal stripes of red (top and
bottom) alternating with white, with a blue rectangle in the canton (referred to specifically as
the "union") bearing fifty small, white, five-pointed stars arranged in nine offset horizontal
rows, where rows of six stars (top and bottom) alternate with rows of five stars.</string>
<string name="Brazil">The flag of Brazil (Portuguese: Bandeira do Brasil), known in
Portuguese as A Auriverde (The Yellow-and-green One), is a blue disc depicting a starry sky
(which includes the Southern Cross) spanned by a curved band inscribed with the national
motto "Ordem e Progresso" ("Order and Progress"), within a yellow rhombus, on a green
field</string>
</resources>

15
COMPUTER SCIENCE AND ENGINEERING

Activity:

MainActivity.java

package com.example.naveenrajy.ex2listviewflags;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {


ListView lv;
String[] countries = {"India","China","Japan","America","Brazil"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.lview);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this,
R.layout.activity_list,R.id.textViewList,countries);
lv.setAdapter(arrayAdapter);
AdapterView.OnItemClickListener ocl = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("index",id+"");
startActivity(intent);
}
};
lv.setOnItemClickListener(ocl);
}
}

16
COMPUTER SCIENCE AND ENGINEERING

SecondActivity.java

package com.example.naveenrajy.ex2listviewflags;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {


TextView textView;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textView = findViewById(R.id.textViewCountry);
imageView = findViewById(R.id.imageViewFlag);
Intent intent = getIntent();
int i = Integer.parseInt(intent.getStringExtra("index"));
switch (i){
case 0:
textView.setText(R.string.India);
imageView.setImageResource(R.drawable.india);
break;
case 1:
textView.setText(R.string.China);
imageView.setImageResource(R.drawable.china);
break;
case 2:
textView.setText(R.string.Japan);
imageView.setImageResource(R.drawable.japan);
break;
case 3:
textView.setText(R.string.America);
imageView.setImageResource(R.drawable.america);
break;
case 4:
textView.setText(R.string.Brazil);
imageView.setImageResource(R.drawable.brazil);
break;
default:

17
COMPUTER SCIENCE AND ENGINEERING

textView.setText("hello");
}
}
}

SAMPLE OUTPUT

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

18
COMPUTER SCIENCE AND ENGINEERING

Ex No:4 Developing an application with the support of activity lifecycle

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application to implement activity lifecycle.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

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

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

19
COMPUTER SCIENCE AND ENGINEERING

</android.support.constraint.ConstraintLayout>

Activity:

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@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
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}

20
COMPUTER SCIENCE AND ENGINEERING

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

SAMPLE OUTPUT

21
COMPUTER SCIENCE AND ENGINEERING

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

22
COMPUTER SCIENCE AND ENGINEERING

Ex No:5 Write an application that uses SQLite databases

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of SQLite databases.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"

23
COMPUTER SCIENCE AND ENGINEERING

android:text="Enter Rollno:"
android:textSize="20sp" />

<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />

<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />

<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"

24
COMPUTER SCIENCE AND ENGINEERING

android:inputType="number"
android:textSize="20sp" />

<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />

<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />

<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />

<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />

<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"

25
COMPUTER SCIENCE AND ENGINEERING

android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />

</AbsoluteLayout>

Activity:

MainActivity.java

package com.example.exno5;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener


{
EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);

26
COMPUTER SCIENCE AND ENGINEERING

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

Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);

// Creating database and table


db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name
VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
// Inserting a record to the Student table
if(view==Insert)
{
// Checking for empty fields
if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0||
Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student
VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
// Deleting a record from the Student table
if(view==Delete)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);

27
COMPUTER SCIENCE AND ENGINEERING

if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Updating a record in the Student table
if(view==Update)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" +
Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Display a record from the Student table
if(view==View)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}

28
COMPUTER SCIENCE AND ENGINEERING

Cursor c=db.rawQuery("SELECT * FROM student WHERE


rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");

29
COMPUTER SCIENCE AND ENGINEERING

Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}
}

SAMPLE OUTPUT

30
COMPUTER SCIENCE AND ENGINEERING

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

31
COMPUTER SCIENCE AND ENGINEERING

Ex No:6 Creating activity for parsing the XML file

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of RSS Feed.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

32
COMPUTER SCIENCE AND ENGINEERING

AndroidManifest.xml:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exno6" >

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

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


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

</manifest>

Activity:

MainActivity.java

package com.example.exno6;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
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;

33
COMPUTER SCIENCE AND ENGINEERING

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)

34
COMPUTER SCIENCE AND ENGINEERING

{
if (xpp.getName().equalsIgnoreCase("item"))
{
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);

35
COMPUTER SCIENCE AND ENGINEERING

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();
}
catch (IOException e)
{
return null;
}
}
}

36
COMPUTER SCIENCE AND ENGINEERING

SAMPLE OUTPUT

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

37
COMPUTER SCIENCE AND ENGINEERING

Ex No:7 Write an application to implement Fragment

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of fragment.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment No.1"
android:onClick="selectFrag" />

<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"

38
COMPUTER SCIENCE AND ENGINEERING

android:text="Fragment No.2" />

<fragment
android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

fragment_one.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"
android:background="#00ffff">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="This is fragment No.1"
android:textStyle="bold" />

</LinearLayout>

fragment_two.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"
android:background="#ffff00">

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"

39
COMPUTER SCIENCE AND ENGINEERING

android:layout_height="match_parent"
android:text="This is fragment No.2"
android:textStyle="bold" />

</LinearLayout>

Activity:

FragmentOne.java:

import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment

return inflater.inflate(
R.layout.fragment_one, container, false);
}
}

FragmentTwo.java:

import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

40
COMPUTER SCIENCE AND ENGINEERING

public class FragmentTwo extends Fragment{


@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

// Inflate the layout for this fragment

return inflater.inflate(
R.layout.fragment_two, container, false);
}
}

MainActivity.java

import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

public void selectFrag(View view) {


Fragment fr;

41
COMPUTER SCIENCE AND ENGINEERING

if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();

}else {
fr = new FragmentOne();
}

FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();

SAMPLE OUTPUT

42
COMPUTER SCIENCE AND ENGINEERING

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

43
COMPUTER SCIENCE AND ENGINEERING

Ex No:8 Develop an android application that makes use of GPS

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of GPS.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

<?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="com.naveenraj.appeightgps.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Latitude:"

44
COMPUTER SCIENCE AND ENGINEERING

android:textSize="24sp" />
<TextView
android:id="@+id/textlat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp" />
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
android:textSize="24sp" />
<TextView
android:id="@+id/textLong"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp" />
</LinearLayout>
</RelativeLayout>

AndroidManifest.xml:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.naveenraj.appeightgps">
<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>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>

45
COMPUTER SCIENCE AND ENGINEERING

Activity:

MainActivity.java

package com.naveenraj.appeightgps;
import android.Manifest;
import android.app.Activity;
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.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity 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,android.Manifest.Permission.ACCESS_FINE_LO
CATION)!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.CheckSelfPermission(this,android.Manifest.Permission.ACCESS_COARSE
_LOCATION)!= PackageManager.PERMISSION_GRANTED)
// {
// return; //use this condition for AppCompatActivity
// }
if (provider != null && !provider.equals("")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling

46
COMPUTER SCIENCE AND ENGINEERING

// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}
Location location = lmanager.getLastKnownLocation(provider);
lmanager.requestLocationUpdates(provider,2000,1,this);
if (location!=null)
{
onLocationChanged(location);
}
else
{
Toast.makeText(getBaseContext(),"Location not available",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getBaseContext(),"No Provider Found",Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationChanged(Location location) {
TextView tv1 = (TextView) findViewById(R.id.textlat);
TextView tv2 = (TextView) findViewById(R.id.textLong);
tv1.setText(""+location.getLatitude());
tv2.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) {
}
}

47
COMPUTER SCIENCE AND ENGINEERING

SAMPLE OUTPUT

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

48
COMPUTER SCIENCE AND ENGINEERING

Ex No:9 Media and Camera API

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of media and camera API.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

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

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Take a Photo" >

49
COMPUTER SCIENCE AND ENGINEERING

</Button>

<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/button1"
android:layout_alignParentTop="true"
android:src="@drawable/ic_launcher" >
</ImageView>
</RelativeLayout>

Activity:

MainActivity.java

package com.example.simplecamera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {


private static final int CAMERA_REQUEST = 1888;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {

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

50
COMPUTER SCIENCE AND ENGINEERING

imageView = (ImageView) this.findViewById(R.id.imageView1);


Button photoButton = (Button) this.findViewById(R.id.button1);

photoButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

51
COMPUTER SCIENCE AND ENGINEERING

SAMPLE OUTPUT

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

52
COMPUTER SCIENCE AND ENGINEERING

Ex No:10 Sensor programming

OBJECTIVE OF THE EXPERIMENT


To develop an Android Application that makes use of accelerometer.

PROCEDURE
1. Open Android Studio and then click on File -> New -> New project.
2. Then type the Application name and click Next.
3. Then select the Minimum SDK and click Next.
4. Then select the Empty Activity and click Next.
5. Finally click Finish.
6. Click on app -> res -> layout -> activity_main.xml and edit it
7. Click on app -> java -> com.example.exno -> MainActivity.java and edit it
8. Start the Android Virtual Device
9. Click on run button to start the application in AVD

PROGARAM:

Layout:

activity_main.xml:

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

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="114dp"
android:text="TextView" />

</RelativeLayout>

53
COMPUTER SCIENCE AND ENGINEERING

Activity:

MainActivity.java

package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView textView1 = null;
List list;

SensorEventListener sel = new SensorEventListener(){


public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
};

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

/* Get a SensorManager instance */


sm = (SensorManager)getSystemService(SENSOR_SERVICE);

textView1 = (TextView)findViewById(R.id.textView1);

list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0),
SensorManager.SENSOR_DELAY_NORMAL);
}else{

54
COMPUTER SCIENCE AND ENGINEERING

Toast.makeText(getBaseContext(), "Error: No Accelerometer.",


Toast.LENGTH_LONG).show();
}
}

@Override
protected void onStop() {
if(list.size()>0){
sm.unregisterListener(sel);
}
super.onStop();
}
}

SAMPLE OUTPUT

55
COMPUTER SCIENCE AND ENGINEERING

CONCLUSION
Thus the android application is developed and executed using android studio
successfully.

56

You might also like