SlideShare a Scribd company logo
1 of 111
5105 –BHARATHIDASAN ENGINEERING COLLEGE
1
NATTRAMPALLI – 635 854
(Approved by AICTE New Delhi and Affiliated to Anna University)
NAME :
REGISTER NUMBER
SUBJECT CODE / NAME : ………………………………………..
YEAR/SEM : …………………………………….......
MAY 2016
Department of Computer Science Engineering
5105 –BHARATHIDASAN ENGINEERING COLLEGE
2
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 _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 6h Semester Computer Science
Engineering in Mobile Application Development LAB-CS6611 during the period JAN 2016 to
APR 2016
Staff In-Charge Head of the Department
University RegisterNumber:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
3
Submitted for the Practical examination held on……….....…………….at Bharathidasan
Engineering College, Nattrampalli.
Internal Examiner External Examiner
TABLE OF CONTENTS
Ex.
No
Date Name of the Experiment
Page
No.
Staff
Signature
5105 –BHARATHIDASAN ENGINEERING COLLEGE
4
CS6611 MOBILE APPLICATION DEVELOPMENT LABORATORY
OBJECTIVES:
The student should be made to:
 Know the components and structure of mobile application development frameworks for
 Android and windows OS based mobiles.
 Understand how to work with various mobile application development frameworks.
 Learn the basic and important design concepts and issues of development of mobile
 applications.
 Understand the capabilities and limitations of mobile devices.
LIST OF EXPERIMENTS:
1. Develop an application that uses GUI components, Font and Colours
2. Develop an application that uses Layout Managers and event listeners.
3. Develop a native calculator application.
4. Write an application that draws basic graphical primitives on the screen.
5. Develop an application that makes use of database.
6. Develop an application that makes use of RSS Feed.
7. Implement an application that implements Multi-threading
8. Develop a native application that uses GPS location information.
9. Implement an application that writes data to the SD card.
10. Implement an application that creates an alert upon receiving a message.
11. Write a mobile application that creates alarm clock
5105 –BHARATHIDASAN ENGINEERING COLLEGE
5
Mission
Our mission is to be the leading mobile application development organization. We aim to
develop mobile apps that can change the way we do our day to day work, with a click of a
button.
Vision Our vision is to be one of the most innovative organizations in around the world. We
believe technology can makes life better for everyone, if used for a good cause. We want to
develop mobile application development training and methodologies, which can make cutting
edge technologies so that the world is a better place.
Ex.No. CREATION OF SIMPLE UI DESIGN ANDROID APPLICATION
Aim:
To create an application that uses GUI components, Font and Colors 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:
1. Select FileNew Project from the menu to create a new project, Studio will present you with
your first project creation screen:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
6
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
7
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
8
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 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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
9
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.
Note: What it’s actually doing is making a subclass of Activity. Those familiar with
object-oriented programming will know what this is, but for newcomers, this basically
means that yourMainActivity is going to be a customized version of Activity that acts just
like the default one, handling things like its lifecycle and the user interface display.
 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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
10
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
5105 –BHARATHIDASAN ENGINEERING COLLEGE
11
• 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
<?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"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
12
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.library.bec.ui.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/txt"
android:textColor="#f90101"
android:textSize="34sp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/logo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Main Activity.java:
package com.library.bec.ui;
import android.graphics.Typeface;
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.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
5105 –BHARATHIDASAN ENGINEERING COLLEGE
13
TextView tF = (TextView) findViewById(R.id.txt); //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/Android Insomnia
Regular.ttf"); //Set the typeface of the textView tF.setTypeface(typeface);
//the type-face will change at
tF.setTypeface(typeface);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
14
5105 –BHARATHIDASAN ENGINEERING COLLEGE
15
5105 –BHARATHIDASAN ENGINEERING COLLEGE
16
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
17
 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…
5105 –BHARATHIDASAN ENGINEERING COLLEGE
18
5105 –BHARATHIDASAN ENGINEERING COLLEGE
19
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
20
5105 –BHARATHIDASAN ENGINEERING COLLEGE
21
5105 –BHARATHIDASAN ENGINEERING COLLEGE
22
Output :
5105 –BHARATHIDASAN ENGINEERING COLLEGE
23
Result: Thus the UI android application that uses GUI components, Font and Colours was
successfully executed.
Ex.No.1. 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:
<RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
24
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.kani.student.text1.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SampleProgram!"
android:id="@+id/textSample" />
</RelativeLayout>
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
left-to-right.
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
25
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).
5105 –BHARATHIDASAN ENGINEERING COLLEGE
26
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).
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:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
27
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
XML Coding:
<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="Click or Long CLick n Me"
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" />
5105 –BHARATHIDASAN ENGINEERING COLLEGE
28
<EditText
android:layout_width="match_parent"
android:layout_height="62dp"
android:id="@+id/txtName"
android:layout_row="3"
android:layout_column="3"
android:hint="Enter your Name"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />
</GridLayout>
Final XML:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools=http://schemas.android.com/tools
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<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" />
5105 –BHARATHIDASAN ENGINEERING COLLEGE
29
<LinearLayout
android:orientation="vertical"
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>
5105 –BHARATHIDASAN ENGINEERING COLLEGE
30
<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="ClickorLongCLicknMe"
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="ShownMynName"
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"
android:layout_row="3"
android:layout_column="3"
android:hint="EnteryourName"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />
</GridLayout></LinearLayout></RelativeLayout>
5105 –BHARATHIDASAN ENGINEERING COLLEGE
31
Setting up Java Code:
package com.kani.student.eventlisteners;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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 {
Button clickBtn, longClickBtn, allBtn, btnShow;
TextView sample;
EditText nameTxt;
/**
* 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);
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!",
5105 –BHARATHIDASAN ENGINEERING COLLEGE
32
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();
}
});
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();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
33
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
34
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
Output:
Result: Thus the Layout and Event listener android application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
35
Ex.No.2. 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"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.library.bec.ex_1_eventlistener.MainActivity"
tools:showIn="@layout/activity_main">
<TextView android:text="hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<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">
5105 –BHARATHIDASAN ENGINEERING COLLEGE
36
<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>
</RelativeLayout>
Setting up Java:
package com.library.bec.ex_1_eventlistener;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
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 {
LinearLayout background;
Button btnGreen, btnBlue;
/**
* 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);
background = (LinearLayout) findViewById(R.id.background);
5105 –BHARATHIDASAN ENGINEERING COLLEGE
37
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.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
38
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Event Listener application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
39
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…..).
5105 –BHARATHIDASAN ENGINEERING COLLEGE
40
Setting up Layout
Skip to XML Code
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.calci1.MainActivity"
tools:showIn="@layout/activity_main">
<EditText
android:id="@+id/result_id"
android:layout_width="fill_parent"
android:layout_height="120dp" />
<Button
android:id="@+id/Btn7_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:text="7"
android:onClick="btn7Clicked"/>
<Button
android:id="@+id/Btn8_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn7_id"
android:text="8"
android:onClick="btn8Clicked"/>
<Button
android:id="@+id/Btn9_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn8_id"
android:text="9"
android:onClick="btn9Clicked"/>
<Button
android:id="@+id/Btnclear_id"
android:layout_width="90dp"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
41
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn9_id"
android:text="clear"
android:onClick="btnclearClicked"/>
<Button
android:id="@+id/Btn4_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn7_id"
android:text="4"
android:onClick="btn4Clicked"/>
<Button
android:id="@+id/Btn5_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn8_id"
android:layout_toRightOf="@id/Btn4_id"
android:text="5"
android:onClick="btn5Clicked"/>
<Button
android:id="@+id/Btn6_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn9_id"
android:layout_toRightOf="@id/Btn5_id"
android:text="6"
android:onClick="btn6Clicked"/>
<Button
android:id="@+id/Btnplus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnclear_id"
android:layout_toRightOf="@id/Btn6_id"
android:text="+"
android:onClick="btnplusClicked"/>
<Button
android:id="@+id/Btn1_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn4_id"
android:text="1"
android:onClick="btn1Clicked"/>
<Button
android:id="@+id/Btn2_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn5_id"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
42
android:layout_toRightOf="@id/Btn1_id"
android:text="2"
android:onClick="btn2Clicked"/>
<Button
android:id="@+id/Btn3_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn6_id"
android:layout_toRightOf="@id/Btn2_id"
android:text="3"
android:onClick="btn3Clicked"/>
<Button
android:id="@+id/Btnminus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnplus_id"
android:layout_toRightOf="@id/Btn3_id"
android:text="-"
android:onClick="btnminusClicked"/>
<Button
android:id="@+id/Btnequal_id"
android:layout_width="110dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:text="="
android:onClick="btnequalClicked" />
<Button
android:id="@+id/Btndivide_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:layout_toRightOf="@id/Btnequal_id"
android:text="/"
android:onClick="btndivideClicked" />
<Button
android:id="@+id/Btnmulti_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnminus_id"
android:layout_toRightOf="@id/Btndivide_id"
android:text="*"
android:onClick="btnmultiClicked"/></RelativeLayout>
Setting up Java
package com.javasamples.calci1;
import android.net.Uri;
5105 –BHARATHIDASAN ENGINEERING COLLEGE
43
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
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 {
public String str = "";
Character op = 'q';
int i, num, numtemp;
EditText showResult;
/**
* 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);
showResult = (EditText) findViewById (R.id.result_id);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }
public void btn1Clicked(View v) {
insert(1); }
public void btn2Clicked(View v) {
insert(2); }
public void btn3Clicked(View v) {
insert(3); }
public void btn4Clicked(View v) {
insert(4); }
public void btn5Clicked(View v) {
insert(5); }
public void btn6Clicked(View v) {
insert(6); }
public void btn7Clicked(View v) {
insert(7); }
public void btn8Clicked(View v) {
insert(8); }
public void btn9Clicked(View v) {
insert(9); }
public void btnplusClicked(View v) {
perform();
op = '+'; }
public void btnminusClicked(View v) {
perform();
5105 –BHARATHIDASAN ENGINEERING COLLEGE
44
op = '-'; }
public void btndivideClicked(View v) {
perform();
op = '/'; }
public void btnmultiClicked(View v) {
perform();
op = '*'; }
public void btnequalClicked(View v) {
calculate(); }
public void btnclearClicked(View v) {
reset(); }
private void reset() {
// TODO Auto-generated method stub
str = "";
op = 'q';
num = 0;
numtemp = 0;
showResult.setText(""); }
private void insert(int j) {
// TODO Auto-generated method stub
str = str + Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str); }
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num; }
private void calculate() {
// TODO Auto-generated method stub
if (op == '+')
num = numtemp + num;
else if (op == '-')
num = numtemp - num;
else if (op == '/')
num = numtemp / num;
else if (op == '*')
num = numtemp * num;
showResult.setText("" + num); }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
45
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.calci1/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.calci1/http/host/path"));
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Calculator application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
46
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:
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
47
4. In the Add an Activity section Select No Activity.
5. Open the Project Window.
6. Expand the app and then the java folders.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
48
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) ;
5105 –BHARATHIDASAN ENGINEERING COLLEGE
49
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:
packagecom.kani.student.kani;
importandroid.graphics.Bitmap;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.drawable.BitmapDrawable;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.support.design.widget.FloatingActionButton;
importandroid.support.design.widget.Snackbar;
importandroid.support.v7.app.AppCompatActivity;
importandroid.support.v7.widget.Toolbar;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.widget.LinearLayout;
importcom.google.android.gms.appindexing.Action;
importcom.google.android.gms.appindexing.AppIndex;
importcom.google.android.gms.common.api.GoogleApiClient;
importcom.google.android.gms.common.api.PendingResult;
importcom.google.android.gms.common.api.Status;
publicclassMainActivity extends AppCompatActivity {
floatx,y,radius;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
50
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paintpaint =new Paint();
paint.setColor(Color.parseColor("#CD5C5C"));
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bg);
canvas.drawRect(50, 50, 300, 300, paint);
LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
ll.setBackgroundDrawable(new BitmapDrawable(bg));
paint.setColor(Color.parseColor("#FF0786FC"));
canvas.drawCircle(200, 200, 100,paint);
LinearLayout ll1 = (LinearLayout) findViewById(R.id.circle);
paint.setColor(Color.BLACK);
canvas.drawLine(100, 200, 300, 200, paint);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} });
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
5105 –BHARATHIDASAN ENGINEERING COLLEGE
51
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true; }
return super.onOptionsItemSelected(item); }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.kani/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
5105 –BHARATHIDASAN ENGINEERING COLLEGE
52
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.kani.student.kani/http/host/path") );
PendingResult<Status> end = AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Content_main.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.kani.student.kani.MainActivity"
tools:showIn="@layout/activity_main">
<LinearLayout
5105 –BHARATHIDASAN ENGINEERING COLLEGE
53
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="184dp"
android:id="@+id/rect"></LinearLayout>
</RelativeLayout>
Output:
Result: Thus the android Graphical Primitive Screens application was successfully
executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
54
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.
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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
55
Start a New Project“Namelist”:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
56
5105 –BHARATHIDASAN ENGINEERING COLLEGE
57
 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:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
58
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.mydata1.MainActivity"
tools:showIn="@layout/activity_main">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:weightSum="1">
<TextView
android:layout_width="276dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter your name"
android:id="@+id/textView"
android:layout_weight="0.03" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:layout_weight="0.03"
android:hint="your name here" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter your Age"
android:id="@+id/textView2"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
59
android:layout_weight="0.03" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/age"
android:layout_weight="0.03"
android:hint=" your Age Here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD DATA"
android:id="@+id/button_add"
android:layout_weight="0.03" />
</LinearLayout>
</RelativeLayout>
Setting up Main activity .java
DatabaseHelper.java
package com.infotech.rit.database_con;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME="student.db";
public static final String TABLE_NAME="student_tb";
public static final String COL1="ID";
public static final String COL2="NAME";
public static final String COL3="AGE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,AGE INTEGER)");
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
60
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name,String age)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL2,name);
contentValues.put(COL3,age);
long result=db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
return false;
else
return true; }}
MainActivity.java
package com.infotech.rit.database_con;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper mydb;
EditText name,age;
Button btnaddData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new DatabaseHelper(this);
name=(EditText)findViewById(R.id.name);
age=(EditText)findViewById(R.id.age);
btnaddData=(Button)findViewById(R.id.button_add);
addData();
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
61
public void addData()
{
btnaddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted=
mydb.insertData(name.getText().toString(),age.getText().toString());
if(isInserted=true)
Toast.makeText(MainActivity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"insertion
failed",Toast.LENGTH_LONG).show(); } }); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) { return true; }
return super.onOptionsItemSelected(item); }}
Output:
Result: Thus the android Database handling application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
62
Ex.No. CREATION OF SIMPLE RSS FEED PARSING APPLICATION
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 Main Activity java:
package com.infotech.rit.database_con;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
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 android.widget.TextView;
import android.widget.Toast;
5105 –BHARATHIDASAN ENGINEERING COLLEGE
63
public class AndroidRssReader extends ListActivity
{
private RSSFeed myRssFeed= null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyTask().execute();
}
private class MyTask extends AsyncTask
{
@Override
protected Void doInBackground(Void... arg0)
{
try
{
URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed= myRSSHandler.getFeed();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
5105 –BHARATHIDASAN ENGINEERING COLLEGE
64
if (myRssFeed!=null)
{
TextView feedTitle = (TextView)findViewById(R.id.feedtitle);
TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate);
TextView feedLink = (TextView)findViewById(R.id.feedlink);
feedTitle.setText(myRssFeed.getTitle());
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
ArrayAdapter adapter =
new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_list_item_1,myRssFeed.getList());
setListAdapter(adapter);
}else{
TextView textEmpty = (TextView)findViewById(android.R.id.empty);
textEmpty.setText("No Feed Found!");
}
super.onPostExecute(result);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink());
Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri);
startActivity(myIntent);
}
}
XML Coding:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
5105 –BHARATHIDASAN ENGINEERING COLLEGE
65
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/feedtitle" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/feeddescribtion" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/feedpubdate" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:id="@+id/feedlink" />
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="waiting" />
</LinearLayout>
Setting up Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javasamples.rss">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="19" />
<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>
5105 –BHARATHIDASAN ENGINEERING COLLEGE
66
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
Output:
5105 –BHARATHIDASAN ENGINEERING COLLEGE
67
Result: Thus the android RSS feed application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
68
Ex.No. 1. 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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
69
• Additionally, the Andoid UI toolkit is not thread-safe. 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
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 multi-threading 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"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.multi1.MainActivity"
tools:showIn="@layout/activity_main">
5105 –BHARATHIDASAN ENGINEERING COLLEGE
70
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/TextView01"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/Button01" android:text="click to change text"
android:layout_below="@+id/EditText01"
android:layout_alignParentStart="true"
android:layout_marginTop="89dp"
android:textColor="#f90303"
android:textSize="34sp" />
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/EditText01"
android:text="@+id/EditText01"
android:textSize="34dp"
android:textColor="#fc0505" />
</RelativeLayout>
Setting up Java:
package com.javasamples.multi1;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
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 {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
71
* 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);
((Button)findViewById(R.id.Button01)).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
updateUI("start of long operation");
// This will cause the UI to freeze
updateUI(doLongOperation());
//This causes the application to crash
/* (new Thread(new Runnable() {
@Override
public void run() {
updateUI(doLongOperation());
}
})).start(); */
/*
// option 1
final Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
updateUI((String)msg.obj);
}
};
(new Thread(new Runnable() {
5105 –BHARATHIDASAN ENGINEERING COLLEGE
72
@Override
public void run() {
Message msg = myHandler.obtainMessage();
msg.obj = doLongOperation();
myHandler.sendMessage(msg);
}
})).start();
*/
// option 2
final Handler myHandler = new Handler();
(new Thread(new Runnable() {
@Override
public void run() {
final String res = doLongOperation();
for (int i = 0; i < 30; i++) {
myHandler.post(new Runnable() {
@Override
public void run() {
updateUI(res);
}
});
}
}
})).start();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
73
public void updateUI(String str) {
((TextView) findViewById(R.id.TextView01)).setText(str);
}
public String doLongOperation() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "end of long operation";
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's
content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.multi1/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
74
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's
content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.javasamples.multi1/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android Multithreading application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
75
Ex.No. 2. 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.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
76
• Additionally, the Andoid UI toolkit is not thread-safe. 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
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 multi-threading 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"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
77
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.library.bec.ex_multithrading1.MainActivity"
tools:showIn="@layout/activity_main">
<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" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="@+id/button"
android:onClick="startprogress"/>
</LinearLayout></RelativeLayout>
5105 –BHARATHIDASAN ENGINEERING COLLEGE
78
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.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
5105 –BHARATHIDASAN ENGINEERING COLLEGE
79
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void startprogress(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
final int value = i;
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) { } }
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
80
Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") );
AppIndex.AppIndexApi.start(client, viewAction); }
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") );
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect(); }}
Output:
Result: Thus the android GPS location application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
81
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"?>
<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"
5105 –BHARATHIDASAN ENGINEERING COLLEGE
82
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.ex_8_gps.MainActivity"
tools:showIn="@layout/activity_main">
<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"
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>
</RelativeLayout>
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;
5105 –BHARATHIDASAN ENGINEERING COLLEGE
83
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,
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();
}
}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
84
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@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) {
}}
5105 –BHARATHIDASAN ENGINEERING COLLEGE
85
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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application></manifest>
Output:
Result: Thus the android GPS location application was successfully executed.
5105 –BHARATHIDASAN ENGINEERING COLLEGE
86
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"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.javasamples.ex_9.MainActivity"
tools:showIn="@layout/activity_main">
<LinearLayout
5105 –BHARATHIDASAN ENGINEERING COLLEGE
87
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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtdata"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="286dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:onClick="readdata"
android:text="Read data"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:onClick="writedata"
android:text="Write data"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button3"
android:onClick="clear"
android:text="Clear"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
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_9">
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<application
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual
Cs 6611 mad lab manual

More Related Content

What's hot

Shader Programming With Unity
Shader Programming With UnityShader Programming With Unity
Shader Programming With UnityMindstorm Studios
 
NVIDIA OpenGL and Vulkan Support for 2017
NVIDIA OpenGL and Vulkan Support for 2017NVIDIA OpenGL and Vulkan Support for 2017
NVIDIA OpenGL and Vulkan Support for 2017Mark Kilgard
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I💻 Anton Gerdelan
 
Future Directions for Compute-for-Graphics
Future Directions for Compute-for-GraphicsFuture Directions for Compute-for-Graphics
Future Directions for Compute-for-GraphicsElectronic Arts / DICE
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016Mark Kilgard
 
Deep Dive: Amazon Lumberyard & Amazon GameLift
Deep Dive: Amazon Lumberyard & Amazon GameLiftDeep Dive: Amazon Lumberyard & Amazon GameLift
Deep Dive: Amazon Lumberyard & Amazon GameLiftAmazon Web Services
 
Publish Android Application on Google Play Store
Publish Android Application on Google Play Store Publish Android Application on Google Play Store
Publish Android Application on Google Play Store Sandip Kalola
 
Front end developer responsibilities what does a front-end developer do?
Front end developer responsibilities  what does a front-end developer do?Front end developer responsibilities  what does a front-end developer do?
Front end developer responsibilities what does a front-end developer do?Katy Slemon
 
Skia & Freetype - Android 2D Graphics Essentials
Skia & Freetype - Android 2D Graphics EssentialsSkia & Freetype - Android 2D Graphics Essentials
Skia & Freetype - Android 2D Graphics EssentialsKyungmin Lee
 
Spotlight on Media & Entertainment: Virtual Reality
Spotlight on Media & Entertainment: Virtual RealitySpotlight on Media & Entertainment: Virtual Reality
Spotlight on Media & Entertainment: Virtual RealityL.E.K. Consulting
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and MoreMark Kilgard
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDuraSpace
 
Graphics programming in open gl
Graphics programming in open glGraphics programming in open gl
Graphics programming in open glArvind Devaraj
 
Gen AI Cognizant & AWS event presentation_12 Oct.pdf
Gen AI Cognizant & AWS event presentation_12 Oct.pdfGen AI Cognizant & AWS event presentation_12 Oct.pdf
Gen AI Cognizant & AWS event presentation_12 Oct.pdfPhilipBasford
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesNarann29
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019Paul Bele
 
AR Glasses with Gaze-locked projection
AR Glasses with Gaze-locked projection AR Glasses with Gaze-locked projection
AR Glasses with Gaze-locked projection Boris Greenberg
 
Manage your ODI Development Cycle – ODTUG Webinar
Manage your ODI Development Cycle – ODTUG WebinarManage your ODI Development Cycle – ODTUG Webinar
Manage your ODI Development Cycle – ODTUG WebinarJérôme Françoisse
 

What's hot (20)

Shader Programming With Unity
Shader Programming With UnityShader Programming With Unity
Shader Programming With Unity
 
NVIDIA OpenGL and Vulkan Support for 2017
NVIDIA OpenGL and Vulkan Support for 2017NVIDIA OpenGL and Vulkan Support for 2017
NVIDIA OpenGL and Vulkan Support for 2017
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
 
Future Directions for Compute-for-Graphics
Future Directions for Compute-for-GraphicsFuture Directions for Compute-for-Graphics
Future Directions for Compute-for-Graphics
 
Flutter
FlutterFlutter
Flutter
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016
 
Deep Dive: Amazon Lumberyard & Amazon GameLift
Deep Dive: Amazon Lumberyard & Amazon GameLiftDeep Dive: Amazon Lumberyard & Amazon GameLift
Deep Dive: Amazon Lumberyard & Amazon GameLift
 
Publish Android Application on Google Play Store
Publish Android Application on Google Play Store Publish Android Application on Google Play Store
Publish Android Application on Google Play Store
 
Front end developer responsibilities what does a front-end developer do?
Front end developer responsibilities  what does a front-end developer do?Front end developer responsibilities  what does a front-end developer do?
Front end developer responsibilities what does a front-end developer do?
 
Skia & Freetype - Android 2D Graphics Essentials
Skia & Freetype - Android 2D Graphics EssentialsSkia & Freetype - Android 2D Graphics Essentials
Skia & Freetype - Android 2D Graphics Essentials
 
Spotlight on Media & Entertainment: Virtual Reality
Spotlight on Media & Entertainment: Virtual RealitySpotlight on Media & Entertainment: Virtual Reality
Spotlight on Media & Entertainment: Virtual Reality
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and More
 
DSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/ExportDSpace 4.2 Transmission: Import/Export
DSpace 4.2 Transmission: Import/Export
 
Graphics programming in open gl
Graphics programming in open glGraphics programming in open gl
Graphics programming in open gl
 
Gen AI Cognizant & AWS event presentation_12 Oct.pdf
Gen AI Cognizant & AWS event presentation_12 Oct.pdfGen AI Cognizant & AWS event presentation_12 Oct.pdf
Gen AI Cognizant & AWS event presentation_12 Oct.pdf
 
OpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering TechniquesOpenGL 4.4 - Scene Rendering Techniques
OpenGL 4.4 - Scene Rendering Techniques
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019
 
AR Glasses with Gaze-locked projection
AR Glasses with Gaze-locked projection AR Glasses with Gaze-locked projection
AR Glasses with Gaze-locked projection
 
Manage your ODI Development Cycle – ODTUG Webinar
Manage your ODI Development Cycle – ODTUG WebinarManage your ODI Development Cycle – ODTUG Webinar
Manage your ODI Development Cycle – ODTUG Webinar
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 

Viewers also liked

CS6611 Mobile Application Development Laboratory
CS6611 Mobile Application Development LaboratoryCS6611 Mobile Application Development Laboratory
CS6611 Mobile Application Development Laboratorybalasubramani manickam
 
It6611 mobile application development laboratory l t p c0 0 3 2
It6611 mobile application development laboratory l t p c0 0 3 2It6611 mobile application development laboratory l t p c0 0 3 2
It6611 mobile application development laboratory l t p c0 0 3 2MNM Jain Engineering College
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environmentmuthusvm
 
"JavaME + Android in action" CCT-CEJUG Dezembro 2008
"JavaME + Android in action" CCT-CEJUG Dezembro 2008"JavaME + Android in action" CCT-CEJUG Dezembro 2008
"JavaME + Android in action" CCT-CEJUG Dezembro 2008Vando Batista
 
MIDP GUI Development: Alert, List, Form, TextBox
MIDP GUI Development: Alert, List, Form, TextBoxMIDP GUI Development: Alert, List, Form, TextBox
MIDP GUI Development: Alert, List, Form, TextBoxJussi Pohjolainen
 
Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Fafadia Tech
 
Java ME CLDC MIDP
Java ME CLDC MIDPJava ME CLDC MIDP
Java ME CLDC MIDPSMIJava
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) APImuthusvm
 
Impact of Corporate Social Responsibility on consumers' preference for a bran...
Impact of Corporate Social Responsibility on consumers' preference for a bran...Impact of Corporate Social Responsibility on consumers' preference for a bran...
Impact of Corporate Social Responsibility on consumers' preference for a bran...Muzamil Quadir
 
Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-pptSrijib Roy
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application DevelopmentBenny Skogberg
 
android technology presentation
android technology presentationandroid technology presentation
android technology presentationNishul Tomar
 
Presentation on Android application
Presentation on Android applicationPresentation on Android application
Presentation on Android applicationAtibur Rahman
 
Android Project Presentation
Android Project PresentationAndroid Project Presentation
Android Project PresentationLaxmi Kant Yadav
 
Relieving Letter Format
Relieving Letter FormatRelieving Letter Format
Relieving Letter FormatYour HR World
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Javaamaankhan
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating systemSalma Begum
 

Viewers also liked (20)

CS6611 Mobile Application Development Laboratory
CS6611 Mobile Application Development LaboratoryCS6611 Mobile Application Development Laboratory
CS6611 Mobile Application Development Laboratory
 
It6611 mobile application development laboratory l t p c0 0 3 2
It6611 mobile application development laboratory l t p c0 0 3 2It6611 mobile application development laboratory l t p c0 0 3 2
It6611 mobile application development laboratory l t p c0 0 3 2
 
Qp mobile &amp; pervasive 2015
Qp mobile &amp; pervasive 2015Qp mobile &amp; pervasive 2015
Qp mobile &amp; pervasive 2015
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environment
 
"JavaME + Android in action" CCT-CEJUG Dezembro 2008
"JavaME + Android in action" CCT-CEJUG Dezembro 2008"JavaME + Android in action" CCT-CEJUG Dezembro 2008
"JavaME + Android in action" CCT-CEJUG Dezembro 2008
 
MIDP GUI Development: Alert, List, Form, TextBox
MIDP GUI Development: Alert, List, Form, TextBoxMIDP GUI Development: Alert, List, Form, TextBox
MIDP GUI Development: Alert, List, Form, TextBox
 
Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)Introduction To J2ME(FT - Prasanjit Dey)
Introduction To J2ME(FT - Prasanjit Dey)
 
Java ME CLDC MIDP
Java ME CLDC MIDPJava ME CLDC MIDP
Java ME CLDC MIDP
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) API
 
J2ME GUI Programming
J2ME GUI ProgrammingJ2ME GUI Programming
J2ME GUI Programming
 
Impact of Corporate Social Responsibility on consumers' preference for a bran...
Impact of Corporate Social Responsibility on consumers' preference for a bran...Impact of Corporate Social Responsibility on consumers' preference for a bran...
Impact of Corporate Social Responsibility on consumers' preference for a bran...
 
Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-ppt
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 
android technology presentation
android technology presentationandroid technology presentation
android technology presentation
 
Presentation on Android application
Presentation on Android applicationPresentation on Android application
Presentation on Android application
 
Android Project Presentation
Android Project PresentationAndroid Project Presentation
Android Project Presentation
 
Relieving Letter Format
Relieving Letter FormatRelieving Letter Format
Relieving Letter Format
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating system
 

Similar to Cs 6611 mad lab manual

Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdfRebaMaheen
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdfRebaMaheen
 
React Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfReact Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfTechugo
 
Android + training + philippines
Android + training + philippinesAndroid + training + philippines
Android + training + philippinesdiosa06
 
Android + training + philippines
Android + training + philippinesAndroid + training + philippines
Android + training + philippineskerwin1116
 
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdf
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdfPERTEMUAN 3_INTRO TO ANDROID APP DEV.pdf
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdfarfa442827
 
2011B1A7689G-TrishuDey-Report
 2011B1A7689G-TrishuDey-Report 2011B1A7689G-TrishuDey-Report
2011B1A7689G-TrishuDey-ReportTrishu Dey
 
Top 8 Flutter App Development Tools.pdf
Top 8 Flutter App Development Tools.pdfTop 8 Flutter App Development Tools.pdf
Top 8 Flutter App Development Tools.pdfFuGenx Technologies
 
iOS Application Development Step by Step to develop an iOS App.pdf
iOS Application Development Step by Step to develop an iOS App.pdfiOS Application Development Step by Step to develop an iOS App.pdf
iOS Application Development Step by Step to develop an iOS App.pdfJPLoft Solutions
 
Platform Independent App design
Platform Independent App designPlatform Independent App design
Platform Independent App designArnab Pradhan
 
08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phoneTOPS Technologies
 
Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Katy Slemon
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studioParinita03
 

Similar to Cs 6611 mad lab manual (20)

Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdf
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdf
 
Sampath_iosLatest
Sampath_iosLatestSampath_iosLatest
Sampath_iosLatest
 
React Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfReact Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdf
 
Bird.pdf
 Bird.pdf Bird.pdf
Bird.pdf
 
Android + training + philippines
Android + training + philippinesAndroid + training + philippines
Android + training + philippines
 
Android + training + philippines
Android + training + philippinesAndroid + training + philippines
Android + training + philippines
 
How to build your own Android App -Step by Step Guide
How to build your own Android App -Step by Step GuideHow to build your own Android App -Step by Step Guide
How to build your own Android App -Step by Step Guide
 
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdf
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdfPERTEMUAN 3_INTRO TO ANDROID APP DEV.pdf
PERTEMUAN 3_INTRO TO ANDROID APP DEV.pdf
 
2011B1A7689G-TrishuDey-Report
 2011B1A7689G-TrishuDey-Report 2011B1A7689G-TrishuDey-Report
2011B1A7689G-TrishuDey-Report
 
Top 8 Flutter App Development Tools.pdf
Top 8 Flutter App Development Tools.pdfTop 8 Flutter App Development Tools.pdf
Top 8 Flutter App Development Tools.pdf
 
iOS Application Development Step by Step to develop an iOS App.pdf
iOS Application Development Step by Step to develop an iOS App.pdfiOS Application Development Step by Step to develop an iOS App.pdf
iOS Application Development Step by Step to develop an iOS App.pdf
 
Platform Independent App design
Platform Independent App designPlatform Independent App design
Platform Independent App design
 
RakeshKushwaha
RakeshKushwahaRakeshKushwaha
RakeshKushwaha
 
Resume
ResumeResume
Resume
 
08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone
 
Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
 
My cv
My cvMy cv
My cv
 
Stacker's
Stacker'sStacker's
Stacker's
 

Recently uploaded

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Recently uploaded (20)

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Cs 6611 mad lab manual

  • 1. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 1 NATTRAMPALLI – 635 854 (Approved by AICTE New Delhi and Affiliated to Anna University) NAME : REGISTER NUMBER SUBJECT CODE / NAME : ……………………………………….. YEAR/SEM : ……………………………………....... MAY 2016 Department of Computer Science Engineering
  • 2. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 2 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 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 6h Semester Computer Science Engineering in Mobile Application Development LAB-CS6611 during the period JAN 2016 to APR 2016 Staff In-Charge Head of the Department University RegisterNumber:
  • 3. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 3 Submitted for the Practical examination held on……….....…………….at Bharathidasan Engineering College, Nattrampalli. Internal Examiner External Examiner TABLE OF CONTENTS Ex. No Date Name of the Experiment Page No. Staff Signature
  • 4. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 4 CS6611 MOBILE APPLICATION DEVELOPMENT LABORATORY OBJECTIVES: The student should be made to:  Know the components and structure of mobile application development frameworks for  Android and windows OS based mobiles.  Understand how to work with various mobile application development frameworks.  Learn the basic and important design concepts and issues of development of mobile  applications.  Understand the capabilities and limitations of mobile devices. LIST OF EXPERIMENTS: 1. Develop an application that uses GUI components, Font and Colours 2. Develop an application that uses Layout Managers and event listeners. 3. Develop a native calculator application. 4. Write an application that draws basic graphical primitives on the screen. 5. Develop an application that makes use of database. 6. Develop an application that makes use of RSS Feed. 7. Implement an application that implements Multi-threading 8. Develop a native application that uses GPS location information. 9. Implement an application that writes data to the SD card. 10. Implement an application that creates an alert upon receiving a message. 11. Write a mobile application that creates alarm clock
  • 5. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 5 Mission Our mission is to be the leading mobile application development organization. We aim to develop mobile apps that can change the way we do our day to day work, with a click of a button. Vision Our vision is to be one of the most innovative organizations in around the world. We believe technology can makes life better for everyone, if used for a good cause. We want to develop mobile application development training and methodologies, which can make cutting edge technologies so that the world is a better place. Ex.No. CREATION OF SIMPLE UI DESIGN ANDROID APPLICATION Aim: To create an application that uses GUI components, Font and Colors 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: 1. Select FileNew Project from the menu to create a new project, Studio will present you with your first project creation screen:
  • 6. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 6 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.
  • 7. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 7 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.
  • 8. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 8 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 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.
  • 9. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 9 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. Note: What it’s actually doing is making a subclass of Activity. Those familiar with object-oriented programming will know what this is, but for newcomers, this basically means that yourMainActivity is going to be a customized version of Activity that acts just like the default one, handling things like its lifecycle and the user interface display.  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.
  • 10. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 10 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
  • 11. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 11 • 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 <?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"
  • 12. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 12 android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.library.bec.ui.MainActivity" tools:showIn="@layout/activity_main"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/txt" android:textColor="#f90101" android:textSize="34sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/logo" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> Main Activity.java: package com.library.bec.ui; import android.graphics.Typeface; 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.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
  • 13. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 13 TextView tF = (TextView) findViewById(R.id.txt); //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/Android Insomnia Regular.ttf"); //Set the typeface of the textView tF.setTypeface(typeface); //the type-face will change at tF.setTypeface(typeface); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
  • 16. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 16 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.
  • 17. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 17  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…
  • 19. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 19 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.
  • 22. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 22 Output :
  • 23. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 23 Result: Thus the UI android application that uses GUI components, Font and Colours was successfully executed. Ex.No.1. 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: <RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"
  • 24. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 24 app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.kani.student.text1.MainActivity" tools:showIn="@layout/activity_main"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SampleProgram!" android:id="@+id/textSample" /> </RelativeLayout> 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 left-to-right. 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.
  • 25. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 25 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).
  • 26. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 26 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). 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:
  • 27. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 27 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 XML Coding: <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="Click or Long CLick n Me" 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" />
  • 28. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 28 <EditText android:layout_width="match_parent" android:layout_height="62dp" android:id="@+id/txtName" android:layout_row="3" android:layout_column="3" android:hint="Enter your Name" android:layout_columnSpan="1" android:layout_rowSpan="1" /> </GridLayout> Final XML: <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=http://schemas.android.com/tools android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <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" />
  • 29. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 29 <LinearLayout android:orientation="vertical" 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>
  • 30. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 30 <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="ClickorLongCLicknMe" 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="ShownMynName" 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" android:layout_row="3" android:layout_column="3" android:hint="EnteryourName" android:layout_columnSpan="1" android:layout_rowSpan="1" /> </GridLayout></LinearLayout></RelativeLayout>
  • 31. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 31 Setting up Java Code: package com.kani.student.eventlisteners; 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.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; 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 { Button clickBtn, longClickBtn, allBtn, btnShow; TextView sample; EditText nameTxt; /** * 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); 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!",
  • 32. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 32 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(); } }); 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(); } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); }
  • 33. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 33 }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
  • 34. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 34 @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } } Output: Result: Thus the Layout and Event listener android application was successfully executed.
  • 35. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 35 Ex.No.2. 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"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.library.bec.ex_1_eventlistener.MainActivity" tools:showIn="@layout/activity_main"> <TextView android:text="hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <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">
  • 36. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 36 <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> </RelativeLayout> Setting up Java: package com.library.bec.ex_1_eventlistener; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; 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 { LinearLayout background; Button btnGreen, btnBlue; /** * 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); background = (LinearLayout) findViewById(R.id.background);
  • 37. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 37 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. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information.
  • 38. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 38 client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }} Output: Result: Thus the android Event Listener application was successfully executed.
  • 39. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 39 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…..).
  • 40. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 40 Setting up Layout Skip to XML Code <?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.calci1.MainActivity" tools:showIn="@layout/activity_main"> <EditText android:id="@+id/result_id" android:layout_width="fill_parent" android:layout_height="120dp" /> <Button android:id="@+id/Btn7_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:text="7" android:onClick="btn7Clicked"/> <Button android:id="@+id/Btn8_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn7_id" android:text="8" android:onClick="btn8Clicked"/> <Button android:id="@+id/Btn9_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn8_id" android:text="9" android:onClick="btn9Clicked"/> <Button android:id="@+id/Btnclear_id" android:layout_width="90dp"
  • 41. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 41 android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn9_id" android:text="clear" android:onClick="btnclearClicked"/> <Button android:id="@+id/Btn4_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn7_id" android:text="4" android:onClick="btn4Clicked"/> <Button android:id="@+id/Btn5_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn8_id" android:layout_toRightOf="@id/Btn4_id" android:text="5" android:onClick="btn5Clicked"/> <Button android:id="@+id/Btn6_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn9_id" android:layout_toRightOf="@id/Btn5_id" android:text="6" android:onClick="btn6Clicked"/> <Button android:id="@+id/Btnplus_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnclear_id" android:layout_toRightOf="@id/Btn6_id" android:text="+" android:onClick="btnplusClicked"/> <Button android:id="@+id/Btn1_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn4_id" android:text="1" android:onClick="btn1Clicked"/> <Button android:id="@+id/Btn2_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn5_id"
  • 42. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 42 android:layout_toRightOf="@id/Btn1_id" android:text="2" android:onClick="btn2Clicked"/> <Button android:id="@+id/Btn3_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn6_id" android:layout_toRightOf="@id/Btn2_id" android:text="3" android:onClick="btn3Clicked"/> <Button android:id="@+id/Btnminus_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnplus_id" android:layout_toRightOf="@id/Btn3_id" android:text="-" android:onClick="btnminusClicked"/> <Button android:id="@+id/Btnequal_id" android:layout_width="110dp" android:layout_height="60dp" android:layout_below="@id/Btn1_id" android:text="=" android:onClick="btnequalClicked" /> <Button android:id="@+id/Btndivide_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btn1_id" android:layout_toRightOf="@id/Btnequal_id" android:text="/" android:onClick="btndivideClicked" /> <Button android:id="@+id/Btnmulti_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnminus_id" android:layout_toRightOf="@id/Btndivide_id" android:text="*" android:onClick="btnmultiClicked"/></RelativeLayout> Setting up Java package com.javasamples.calci1; import android.net.Uri;
  • 43. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 43 import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; 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 { public String str = ""; Character op = 'q'; int i, num, numtemp; EditText showResult; /** * 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); showResult = (EditText) findViewById (R.id.result_id); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } public void btn1Clicked(View v) { insert(1); } public void btn2Clicked(View v) { insert(2); } public void btn3Clicked(View v) { insert(3); } public void btn4Clicked(View v) { insert(4); } public void btn5Clicked(View v) { insert(5); } public void btn6Clicked(View v) { insert(6); } public void btn7Clicked(View v) { insert(7); } public void btn8Clicked(View v) { insert(8); } public void btn9Clicked(View v) { insert(9); } public void btnplusClicked(View v) { perform(); op = '+'; } public void btnminusClicked(View v) { perform();
  • 44. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 44 op = '-'; } public void btndivideClicked(View v) { perform(); op = '/'; } public void btnmultiClicked(View v) { perform(); op = '*'; } public void btnequalClicked(View v) { calculate(); } public void btnclearClicked(View v) { reset(); } private void reset() { // TODO Auto-generated method stub str = ""; op = 'q'; num = 0; numtemp = 0; showResult.setText(""); } private void insert(int j) { // TODO Auto-generated method stub str = str + Integer.toString(j); num = Integer.valueOf(str).intValue(); showResult.setText(str); } private void perform() { // TODO Auto-generated method stub str = ""; numtemp = num; } private void calculate() { // TODO Auto-generated method stub if (op == '+') num = numtemp + num; else if (op == '-') num = numtemp - num; else if (op == '/') num = numtemp / num; else if (op == '*') num = numtemp * num; showResult.setText("" + num); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown.
  • 45. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 45 // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.calci1/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.calci1/http/host/path")); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }} Output: Result: Thus the android Calculator application was successfully executed.
  • 46. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 46 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: 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.
  • 47. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 47 4. In the Add an Activity section Select No Activity. 5. Open the Project Window. 6. Expand the app and then the java folders.
  • 48. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 48 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) ;
  • 49. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 49 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: packagecom.kani.student.kani; importandroid.graphics.Bitmap; importandroid.graphics.Canvas; importandroid.graphics.Color; importandroid.graphics.Paint; importandroid.graphics.drawable.BitmapDrawable; importandroid.net.Uri; importandroid.os.Bundle; importandroid.support.design.widget.FloatingActionButton; importandroid.support.design.widget.Snackbar; importandroid.support.v7.app.AppCompatActivity; importandroid.support.v7.widget.Toolbar; importandroid.view.Menu; importandroid.view.MenuItem; importandroid.view.View; importandroid.widget.LinearLayout; importcom.google.android.gms.appindexing.Action; importcom.google.android.gms.appindexing.AppIndex; importcom.google.android.gms.common.api.GoogleApiClient; importcom.google.android.gms.common.api.PendingResult; importcom.google.android.gms.common.api.Status; publicclassMainActivity extends AppCompatActivity { floatx,y,radius; /** * ATTENTION: This was auto-generated to implement the App Indexing API.
  • 50. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 50 * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Paintpaint =new Paint(); paint.setColor(Color.parseColor("#CD5C5C")); Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bg); canvas.drawRect(50, 50, 300, 300, paint); LinearLayout ll = (LinearLayout) findViewById(R.id.rect); ll.setBackgroundDrawable(new BitmapDrawable(bg)); paint.setColor(Color.parseColor("#FF0786FC")); canvas.drawCircle(200, 200, 100,paint); LinearLayout ll1 = (LinearLayout) findViewById(R.id.circle); paint.setColor(Color.BLACK); canvas.drawLine(100, 200, 300, 200, paint); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
  • 51. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 51 } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.kani/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
  • 52. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 52 @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.kani/http/host/path") ); PendingResult<Status> end = AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }} Content_main.xml: <?xmlversion="1.0"encoding="utf-8"?> <RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.kani.student.kani.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout
  • 53. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 53 android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="184dp" android:id="@+id/rect"></LinearLayout> </RelativeLayout> Output: Result: Thus the android Graphical Primitive Screens application was successfully executed.
  • 54. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 54 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. 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.
  • 55. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 55 Start a New Project“Namelist”:
  • 57. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 57  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:
  • 58. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 58 <?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.mydata1.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:weightSum="1"> <TextView android:layout_width="276dp" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Enter your name" android:id="@+id/textView" android:layout_weight="0.03" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/name" android:layout_weight="0.03" android:hint="your name here" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Enter your Age" android:id="@+id/textView2"
  • 59. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 59 android:layout_weight="0.03" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/age" android:layout_weight="0.03" android:hint=" your Age Here" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ADD DATA" android:id="@+id/button_add" android:layout_weight="0.03" /> </LinearLayout> </RelativeLayout> Setting up Main activity .java DatabaseHelper.java package com.infotech.rit.database_con; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME="student.db"; public static final String TABLE_NAME="student_tb"; public static final String COL1="ID"; public static final String COL2="NAME"; public static final String COL3="AGE"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,AGE INTEGER)"); }
  • 60. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 60 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists "+TABLE_NAME); onCreate(db); } public boolean insertData(String name,String age) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put(COL2,name); contentValues.put(COL3,age); long result=db.insert(TABLE_NAME,null,contentValues); if(result==-1) return false; else return true; }} MainActivity.java package com.infotech.rit.database_con; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { DatabaseHelper mydb; EditText name,age; Button btnaddData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb=new DatabaseHelper(this); name=(EditText)findViewById(R.id.name); age=(EditText)findViewById(R.id.age); btnaddData=(Button)findViewById(R.id.button_add); addData(); }
  • 61. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 61 public void addData() { btnaddData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean isInserted= mydb.insertData(name.getText().toString(),age.getText().toString()); if(isInserted=true) Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show(); else Toast.makeText(MainActivity.this,"insertion failed",Toast.LENGTH_LONG).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }} Output: Result: Thus the android Database handling application was successfully executed.
  • 62. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 62 Ex.No. CREATION OF SIMPLE RSS FEED PARSING APPLICATION 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 Main Activity java: package com.infotech.rit.database_con; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; 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 android.widget.TextView; import android.widget.Toast;
  • 63. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 63 public class AndroidRssReader extends ListActivity { private RSSFeed myRssFeed= null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new MyTask().execute(); } private class MyTask extends AsyncTask { @Override protected Void doInBackground(Void... arg0) { try { URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml"); SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance(); SAXParser mySAXParser = mySAXParserFactory.newSAXParser(); XMLReader myXMLReader = mySAXParser.getXMLReader(); RSSHandler myRSSHandler = new RSSHandler(); myXMLReader.setContentHandler(myRSSHandler); InputSource myInputSource = new InputSource(rssUrl.openStream()); myXMLReader.parse(myInputSource); myRssFeed= myRSSHandler.getFeed(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) {
  • 64. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 64 if (myRssFeed!=null) { TextView feedTitle = (TextView)findViewById(R.id.feedtitle); TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion); TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate); TextView feedLink = (TextView)findViewById(R.id.feedlink); feedTitle.setText(myRssFeed.getTitle()); feedDescribtion.setText(myRssFeed.getDescription()); feedPubdate.setText(myRssFeed.getPubdate()); feedLink.setText(myRssFeed.getLink()); ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,myRssFeed.getList()); setListAdapter(adapter); }else{ TextView textEmpty = (TextView)findViewById(android.R.id.empty); textEmpty.setText("No Feed Found!"); } super.onPostExecute(result); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink()); Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri); startActivity(myIntent); } } XML Coding: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
  • 65. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 65 <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feedtitle" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feeddescribtion" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feedpubdate" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoLink="web" android:id="@+id/feedlink" /> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@android:id/empty" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="waiting" /> </LinearLayout> Setting up Manifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasamples.rss"> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="19" /> <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>
  • 66. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 66 <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- ATTENTION: This was auto-generated to add Google Play services to your project for App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> </manifest> Output:
  • 67. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 67 Result: Thus the android RSS feed application was successfully executed.
  • 68. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 68 Ex.No. 1. 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.
  • 69. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 69 • Additionally, the Andoid UI toolkit is not thread-safe. 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 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 multi-threading 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"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.multi1.MainActivity" tools:showIn="@layout/activity_main">
  • 70. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 70 <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/TextView01"/> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button01" android:text="click to change text" android:layout_below="@+id/EditText01" android:layout_alignParentStart="true" android:layout_marginTop="89dp" android:textColor="#f90303" android:textSize="34sp" /> <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/EditText01" android:text="@+id/EditText01" android:textSize="34dp" android:textColor="#fc0505" /> </RelativeLayout> Setting up Java: package com.javasamples.multi1; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; 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 { /** * ATTENTION: This was auto-generated to implement the App Indexing API.
  • 71. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 71 * 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); ((Button)findViewById(R.id.Button01)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateUI("start of long operation"); // This will cause the UI to freeze updateUI(doLongOperation()); //This causes the application to crash /* (new Thread(new Runnable() { @Override public void run() { updateUI(doLongOperation()); } })).start(); */ /* // option 1 final Handler myHandler = new Handler(){ @Override public void handleMessage(Message msg) { updateUI((String)msg.obj); } }; (new Thread(new Runnable() {
  • 72. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 72 @Override public void run() { Message msg = myHandler.obtainMessage(); msg.obj = doLongOperation(); myHandler.sendMessage(msg); } })).start(); */ // option 2 final Handler myHandler = new Handler(); (new Thread(new Runnable() { @Override public void run() { final String res = doLongOperation(); for (int i = 0; i < 30; i++) { myHandler.post(new Runnable() { @Override public void run() { updateUI(res); } }); } } })).start(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }
  • 73. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 73 public void updateUI(String str) { ((TextView) findViewById(R.id.TextView01)).setText(str); } public String doLongOperation() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return "end of long operation"; } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.multi1/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }
  • 74. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 74 @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.multi1/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }} Output: Result: Thus the android Multithreading application was successfully executed.
  • 75. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 75 Ex.No. 2. 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.
  • 76. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 76 • Additionally, the Andoid UI toolkit is not thread-safe. 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 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 multi-threading 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"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin"
  • 77. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 77 android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.library.bec.ex_multithrading1.MainActivity" tools:showIn="@layout/activity_main"> <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" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:id="@+id/button" android:onClick="startprogress"/> </LinearLayout></RelativeLayout>
  • 78. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 78 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. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true;
  • 79. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 79 } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void startprogress(View view) { Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { final int value = i; 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) { } } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct.
  • 80. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 80 Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }} Output: Result: Thus the android GPS location application was successfully executed.
  • 81. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 81 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"?> <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"
  • 82. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 82 android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_8_gps.MainActivity" tools:showIn="@layout/activity_main"> <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" 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> </RelativeLayout> 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;
  • 83. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 83 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, 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(); } }
  • 84. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 84 @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @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) { }}
  • 85. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 85 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" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> Output: Result: Thus the android GPS location application was successfully executed.
  • 86. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 86 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"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_9.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout
  • 87. 5105 –BHARATHIDASAN ENGINEERING COLLEGE 87 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"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/txtdata"/> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="286dp"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button1" android:onClick="readdata" android:text="Read data"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:onClick="writedata" android:text="Write data"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:onClick="clear" android:text="Clear"/> </LinearLayout> </LinearLayout> </RelativeLayout> 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_9"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission> <application