SDLLab Manual Updated - Google Docs
SDLLab Manual Updated - Google Docs
TECHNOLOGY,BHOPAL
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE
LEARNING
LAB MANUAL
S.no EXPERIMENTS
.
1.
DesignasystemwiththehelpofadvanceddatastructuresinJavaandenhancethesystem
using collections and generics.
2. Enhance the system with the help of socket programming using client server
architecture.
4. Transform the system from command line system to GUI based application using applet.
7. Design a mobile app to store data using internal or external storage.
8. Design a mobile app using Google Map and GPS to trace the location.
ExperimentNo:01
Problem Statement::
Design a system with the help of advanced data structure inJava and enhance the system
using collection and generics.
Objectives:
●To learn the process of creation of data-driven web applications using current
technologies
●Tounderstandhowtoincorporatebestpracticesforbuildingenterpriseapplications
SoftwareRequirements: -
HardwareRequirements: -
Theory Concept:
IntroductiontotheCollectionFramework
Collection:-
Collections in java is a framework that provides an architecture to store and
manipulatethegroupo fo bjects.Eachiteminacollectioniscalledanelement.Allthe
o perationsthatyouperformonadatasuchas
searching,sorting,insertion,manipulation,deletionetc.canbeperformedbyJavaCollection
s.JavaCollectionsimply meansa
singleunitofobjects.JavaCollectionframeworkprovidesmanyinterfaces(Set,List,Queue,D
equeetc.) and classes (Array List, Vector, LinkedList,Priority
Queue,HashSet,LinkedHashSet,Treeset Etc.).
Framework:-
A framework by definition is a set o f interfaces that force you to adopt some
designpractices.Awell-designedframeworkcanimproveyourproductivityandprovide
ease of maintenance.
Thecollectionframeworkprovidesaunifiedinterfacetostore,retrieveandmanipulatet
heelementsofacollection,regardlessoftheunderlyingandactualimplementation. This
allows the programmers toprogramat the interfaces, insteadoftheactualimplementation.
TheJavaCollectionFrameworkpackage(java.util)contains
1. Aset Interfaces,
2. Implementation Classes,and
3. Algorithms(such as sorting and searching).
HierarchyofCollectionFramework
Letusseethe Hierarchy Collection Framework.The Java.util package contains
all the classes and interfaces of Collection Framework.
IntroductiontoGenerics
Java Generics Programming isintroducedinJ2SE5todealwithtype-safeo bjects.
We can store any type o f o bjects in collection i.e. non-generic.Nowgenerics,forcesthe
java programmer tostorespecifictypeofobjects.
AdvantageofJavaGenerics
1) Type-safety:Wecanholdonlyasingletypeofobjectsingenerics.Itdoesn’tallowstorin
gotherobjects.
2) Typecastingisnotrequired:Thereisnoneedtotypecasttheobject.BeforeGenerics,w
eneed totypecast.
e.g.
List
List=newArrayList();list.ad
d("hello");
Strings=(String)list.get(0);//typecasting
AfterGenerics,we don't need to typecast the object.
e.g.
List<String> list
=newArrayList<String>();
list.add("hello");Strings=list.get(0);
3) Compile-Time Checking:It is checked at compile time so problem will
noto ccuratruntime.Thegoodprogrammingstrategysaysitisfarbetter
to handle the problem at compile time than runtime.
Syntaxtousegenericcollection
ClassOrInterface<Type>
e.g. ArrayList<String>
ExampleofGenericsinJava
Import Java.util.*;
classTestGenerics1
{
{
ArrayList<String> list=new
ArrayList<String>();list.add("rahul");
list.add("jai");
Iterator<String>itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next())}}
Output:
elementis:jai
rahul
jain
ProblemStatement::
Enhance the system with the help of socket programming client server
architecture.
Objectives::
SoftwareRequirements: -
HardwareRequirements: -
Theory Concept::
W hat Is Socket?
A socket is o ne end-point o f a two-way communication link between two
programsrunningo nthenetwork.Socketclassesareusedtorepresenttheconnection
between a client program and a server program. The java.net package provides two
classes--SocketandServerSocket--thatimplementtheclientsideo ftheconnectionand
theserverside the connection,respectively.
Client/ServerCommunication
At a basic level, network-based systems consist o f a server, client, and a media for
communication.Acomputerrunningaprogramthatmakesarequestforservicesiscalleda
client machine. A computer running a program that o ffers requested service from o ne o r
more clients is called a server machine. The media for communication can
bewiredorwirelessnetwork.Generally,programsrunningonclientmachinesmakerequests to a
program (often called as server program) running o n a server machine.They involve
networking services provided bythetransportlayer,whichisparto ftheInternetsoftware
stack,oftencalled TCP/IP (TransportControlProtocol/InternetProtocol)Thetransportlayer
comprises two types o f protocols, TCP (Transport
ControlProtocol)andUDP(UserDatagramProtocol).The Most Widely Used Programming
interfacesfortheseprotocolsaresockets.TCPisaconnection-orientedprotocolthatprovides a
reliableflowo fdatabetweentwocomputers.Exampleapplicationsthatusesuchservices
HTTP,FTP,andTelnet.
SocketsandSocket-basedCommunication
Sockets provide an interface for programming networks at the transport
layer.NetworkcommunicationusingSocketsisverymuchsimilartoperformingfileI/O.
Infact, socket handles are treated like file handles. The streams used in file I/O
o peration are also applicable to socket-based I/O. Socket-based communication is
independent o f the programming language used for implementing it. That means, a
socket program written in Java language can communicate to a program written in
non-Java (say C o r C++)socket program. A server (program) runs o n a specific
computer and has a socket that
isboundtoaspecificport.Theserverlistenstothesocketforaclienttomakeaconnectionreque
st(seeFig.13.4a).If Everything Goes Well,the server accepts the connection (see Fig.
13.4b). Upon acceptance, the server gets a new socket bound to a different port. It
needs a new socket (consequentlyadifferentportnumber)sothatitcancontinueto
listen to the original socket for connection requests while serving the connected client.
Asocketisanendpointo fatwo-waycommunicationlinkbetweentwoprograms
running o n the network. Socket is bound to aportnumbersothattheTCPlayercan
identify the application that data is destined to be sent. Java provides a set o f
classes,definedinapackagecalledjava.net,toenabletherapiddevelopmento network
applications. Keyclasses,interfaces,andexceptionsinjava.netpackagesimplifyingthe
complexity involved in creating client and server programs are:
TheClasses
• DatagramSocketImpl
• HttpURLConnection
• InetAddress
• MulticastSocket
• ServerSocket
• Socket
• SocketImpl
• URL
• URLConnection
• URLEncoder
• URLStreamHandler
TheInterfaces
• ContentHandlerFactory
• FileNameMap
• SocketImplFactory
• URLStreamHandlerFactory
ExceptionsinJava
•BindException
•ConnectException
•MalformedURLException
•NoRoutetoHostException
•ProtocolException
•SocketException
Client-ServerCommunicationStructure
The InetAddressClass: -
publicbooleanisMulticastAddress()pu
blicStringgetHostName()
public byte[]
getAddress()publicStringgetHos
tAddress()public inthashCode()
publicStringtoString()
e.g.
importjava.net.*;
publicclassMyLocalIPAddress
{
{
try
{
InetAddressaddress=InetAddress.getLocalHost();Syste
m.out.println(address);
}
catch(UnknownHostException)
{
}
}
}
TheJava.net.SocketClass
• Sendingandreceivingdataisaccomplishedwithoutputandinputstreams.
There are methods to get an input stream for a socket and
anoutputstreamforthesocket.
1) publicInputStreamgetInputStream()throwsIOException
2) publicOutputStreamgetOutputStream()throwsIOException
ExampleofJavaSocketProgramming
1) MyServer.java
import java.io.*;
importjava.net.*;public
class Server{
ServerSocketss=newServerSocket(6666);Soc
DataInputStream
dis=newDataInputStream(s.getInputStream());String
Str=(String)dis.readUTF();System.out.println("messa
ge=
"+str);ss.close();
}catch(Exceptione){System.out.println(e);}
}
}
)MyClient.java
2
import
java.io.*;import
java.net.*;publicclass
MyClient{
{try{
Sockets=newSocket("localhost",6666);Da
taOutputStreamdout=new
DataOutputStream(s.getOutputStream());dout.writeUTF("Hello
Server");
dout.flush();
dout.close();
s.close();
}catch(Exceptione){System.out.println(e);}
}
}
Conclusion:-
Welearnsocketprogrammingusingclientserverarchitecture
ExperimentNo:03
ProblemStatement::
HardwareRequirements:-
-AnyProcessor abovePentium4
Theory Concept::
Java JDBC:
Java JDBC is a java API to connect and execute queries with the database. JDBC API
uses jdbc drivers to connect with the database.
W hyuseJDBC
BeforeJDBC,ODBCAPIwasthedatabaseAPItoconnectandexecutequerywith
the database.But,ODBCAPIuses ODBCdriverwhichis written in language (i.e.platform
dependent and unsecured). That is why Java has defined its own API
(JDBCAPI)thatusesJDBCdrivers(writteninJavalanguage).
JDBCConnectionBasics
Java Database Connectivity(JDBC)isa standard application programming
interface (API) specification that is implemented by different database vendors to
allowJava programs to access their database management systems. The JDBC API
consists o f a set o f interfaces and classes written in the Javaprogramminglanguage.
Interestingly,JDBCis notanacronymandthus stands
fornothingbutpopularasJavaDatabaseConnectivity. According toSun (now merged in
Oracle) JDBC is a trademark term note acronym. It Was Named toby redolent ofODBC.
JDBC implementation comes in form o f a database driver for a particular
DBMSvendor. A Java program that uses the JDBC API loadsthespecifieddriverfora
particularDBMSbeforeit actually connects to the database.
JDBCConnection-JDBCDesign
JDBC --a trademark comes bundled with Java SE as a set o f APIs that facilitates Java
Programs to access data stored in a database management system, particularly in
aRelationalDatabase.AtthetimeofdesigningJDBC(Java Database Connectivity),following
goals were kept in mind:
• JDBC(Java Database Connectivity)shouldbeanSQLlevelAPI;therefore,it should
allow users to construct SQL statements and embedthemintoJavaAPIcallsto
run those statements o n a database. And then results from the database
returned as Java objects(ResultSets)and access-problems as exceptions.
JDBCConnection-CreateDatabaseforUse
To start using JDBC (Java database connectivity) first you would need a
database system, and then a JDBC (Java database connectivity) driver for your
database. During This articleJDBC(Javadatabaseconnectivity)willbeexplainedwith
MySQL, but you can use it with any database system (such as Microsoft SQL, Oracle,
IBM DB2, PostgresQL),provided that you have a JDBC (Java database connectivity)
driver for your database system.
JDBCConnection-UsingJDBC
2.JDBCConnection-DriverClass
As we have obtained theJDBC driver info mofaJAR file(mysql-connector-java-
***-bin.jar)inwhichthedriverforMySQLdatabaseislocated.Thisdriverneedstobe
registeredinordertoaccessEX PDB.DriverfilenameforMySQLi com.mysql.jdbc.Driver.
Thisfilehastobeloadedintomemorybeforeyougetconnectedtothedatabase,else
you will result in java.sql. SQL Exception: No suitable driver exception.
3.JDBCConnection-DatabaseUserNameandPassword
To get a JDBC connection to the database you would require theusernameand
password, it is the same username and password which we used, while connecting
toMySQL.
JavaProgramforJDBCConnection
UsingDriverManagergetsyouaconnectiontothedatabasespecifiedbyconnection
Url.Whenabovecodefragmentisexecuted,theDriverManageriteratethroughthe
registered JDBC drivers to find a driver that can use the subprotocol specifiedin
the connectionUrl. Don't forget to surround getConnection() code by try
block,because it can throw SQLException.
2.ExecuteSQLStatementsthroughJDBCConnection
Now that you have a JDBC Connection o bject, you would like to executeSQL
statements through the conn (JDBC connection) o bject. A connection in JDBC is a
session withaspecificdatabase,whereSQLstatementsareexecutedandresultsare
returned within the context o f a connection. To execute SQL statements you would
need a Statement o bject that you would acquire by invoking
createStatement()methodonconn as illustrated below.
e.g.
try
Statementobjectstmtbyexecutingabovepieceofcode.Bydefinition,createStatement()
throwsanSQLExceptionsothecodelineStatementstmt=conn.createStatement(); should
either surroundedbytryblocko rthrowtheexceptionfurther.Onsuccessfulcreation
o f stmt you can send SQL queries to yourdatabasewithhelpo fexecuteQuery(),and
executeUpdate() methods. Also the Statement has many more useful methods.
Next,formaquerythatyouwouldliketoexecuteo nthedatabase.Forinstance,
we will select all records fromEXPDP,o urexampledatabase.MethodexecuteQuery()
will get you a ResultSet o bject that contains the query results. You can think a
ResultSetobject as two dimensional array o bject, where each row o f an array
represents o ne record. And, all rows have an identical number o f columns; some
columns may contain null values.Itisal Depends upon what is stored in the database.
e.g.
e.g.
System.out.p
rintln("ID\tNAME");
We process o ne record at a time o r you say o ne row at a time.
ResultSet'snext()method helps us to move o ne record forward in o ne iteration, it
returns true
untilreachestolastrecord,falseiftherearenomorerecordstoprocess.WeaccessResultSet's
columns by supplying column headers to getXxx() methods as they areinEXPTABLE
e.g., rs.getInt("id"). You can also access those columns bysupplyingcolumnindicesto
getXxx() methods e.g., rs.getInt(1) will return you the first column o f currentrow
pointed byrs.
2.CloseJDBCConnection
J DBCconnectiontodatabaseisasession;ithasbeenmentionedearlier.Assoon
as you close the sessionyouarenolongerconnectedtothedatabase;therefore,you
wouldn't be able to perform anyo perationo nthedatabase.Closingconnectionmust
be the verylaststep when you aredonewithall databaseoperations
e.g.
JAVAMySQLConnectivityProgram:
importjava.sql.*;i
mport
java.io.*;classJay
{
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
Con=DriverManager.getConnection("mysql:jdbc://localhost:3306/stud","root","siem ");
Statement St=con.createStatement();
ResultSetrs=st.executeQuery("select * from
student");while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}
con.close();
}
catch(Exceptione)
{
System.out.println("Error:-"+e);
}
}
}
o/p
Conclusion:
We Understand The Java Mysql Connectivity.
ExperimentNo:04
ProblemStatement::
Transform the system from command line system to GUI based application using applet
Objectives::
1)TounderstandGUIconcept.
2)TounderstandApplet andEventhandlingusingapplet
SoftwareRequirements:-
-Ubuntu 14.04,Geditor,JDK
HardwareRequirements:-
– AnyProcessorabovePentium4
Theory Concept::
JavaApplet
ppletisaspecialtypeofprogramthatisembeddedinthewebpagetogeneratethedynamic
A
content.Itrunsinsidethebrowserandworksatclient side.
AdvantageofApplet
• Secured
• Itcanbeexecutedbybrowsersrunningundermany
Platforms,includingLinux,Windows,MacOsetc.
DrawbackofApplet
As displayed in the above diagram,Applet class extends Panel .Panel class extends Container which
is the subclass Component.
LifecycleofJavaApplet
java.applet.Appletclass
java.awt.Componentclass
TheComponentclassprovides1lifecyclemethodofapplet.
What is anEvent?
Change in the state o f an o bject is known as event i.e. event describes the change in state o f
source. Events are generated as result o f user interaction with the
graphicaluserinterfacecomponents.Forexample,clickingonabutton,movingthemouse,enteringacharacter
through keyboard,selecting an item from list, scrolling the page aretheactivitiesthatcausesan event to
happen
ypesofEvent
T
The Event Scan Be Broadly Classified Into Two Categories:
• ForegroundEvents-Thoseeventswhichrequirethedirectinteractionofuser.Theyaregenerate
dasconsequencesofapersoninteractingwiththegraphicalcomponents in Graphical User Interface.
For example, clicking o n a button, moving the mouse, entering a character through
keyboard,selecting anitem fromlist,scrolling thepageetc.
• Background Events - Those events that require the interaction o f end user
areknownasbackgroundevents.Operatingsysteminterrupts,hardwareorsoftwarefailure,timerexpir
es,anoperationcompletionaretheexampleofbackgroundevents.
add(t3);
add(b);b.addActionListener(this);
}
publicvoidactionPerformed(ActionEvent)
{
if(e.getSource()==b)
{
intn1=Integer.parseInt(t1.getText());intn2=Integer.parse
Int(t2.getText());t3.setText(""+(n1+n2));
}
}
}
/*
<html><body><appletcode="Q2.class"height=500width=500>
</applet></body></html>*/
UTPUT:
O
Conclusion:WelearntheAppletdesigningandEventhandlingforsystemdesigning
ExperimentNo:05
P roblemDefinition
Install and Configure Android Studio on Linux.
1.1Prerequisite:
● Basic concepts of Installation and Configuration of Android Studio on Linux.
● Concepts of Android Platform Architecture and component of Android.
1.2SoftwareRequirements:
AndroidStudio
1.3Tools/Framework/LanguageUsed:
AndroidStudio
1.4HardwareRequirement:
PIV,4GB RAM,500GB HDD, LenovoA13-4089Model
1.5LearningObjectives:
InstallandConfigureAndroidStudioonLinux.
1.6Outcomes:
After completion o f this assignment, students are able toUnderstand Howto Install
andConfigureAndroidStudioonLinuxandAndroidPlatformArchitecture.
1.7TheoryConcepts:
Android is a complete set o f software for mobile devices such as tablet
computers,notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a
Linux-basedOperatingSystem,middlewareandkeymobileapplications.Itcanbethought
o f as a mobile o perating
system.Butitisnotlimitedtomobileonly.Itiscurrentlyusedinvariousdevicessuchasmobiles,tablets,te
levisions etc.
HistoryofAndroid
The History And versions of android are interesting to know.The Codenames Android
Ranges from A to J currently, s uch as Aestro, Blender, Cupcake, Donut,
Eclair,Froyo,G
ingerbread,Honeycomb,Ice Cream Sandwich,JellyBean,KitKat and Lollipop.Let's
Understandthe androidhistoryina sequence.
1) Initially,AndyRubinfoundedAndroid Incorporation Palo Alto,California,United States October,2003.
2) On 17th August 2005, Google acquired Android Incorporation. Since then, it is a subsidiary
o fGoogleIncorporation.
3) ThekeyemployeesofAndroidIncorporationareAndy Rubin,Rich Miner,Chris Whiteand
NickSears.
4) Originally intended for cameras but shifted to smart phones later
becauseoflowmarketforcameraonly.
5) AndroidisthenicknameofAndyRubin givenbycoworkersbecauseofhislovetorobots.
6) In2007,GoogleannouncesthedevelopmentofandroidOS.
7) In2008,HTClaunchedthefirstandroidmobile.
AndroidArchitecture
androidarchitectureorAndroidsoftwarestackiscategorizedintofiveparts:
2)NativeLibraries
On the top of linux kernel, there areNative librariessuch as WebKit, OpenGL,
FreeType,SQLite,Media,Cruntimelibrary(libc)etc.TheWebKitlibraryisresponsibleforbrowsersup
port,SQLiteisfordatabase,FreeTypeforfontsupport,Mediaforplayingandrecordingaudioandvideo
formats.
3)AndroidRuntime
Inandroidruntime,therearecorelibrariesandDVM(DalvikVirtualMachine)which
is responsible for running android applications. DVM is like JVM but it is o ptimized for
mobile devices. It Consumes Less Memory And Provides Fast Performance.
4)AndroidFramework
On the top o f Native libraries and androidruntime,thereisanandroidframework.
Android Framework includes Android APIs such as UI (User Interface), telephony,
resources, locations,Content Providers (data) and package managers. It provides a lot o f
classes and interfaces for android application development.
5)Applications
On the top o f android framework, there are applications. All applications such as
home,contact, settings, games, browsers are using android framework that uses android
runtime and libraries.Androidruntime And nativelibrariesareusingLinuxkernel.
An Android component is simply a piece o f code that has a well-defined life cycle e.g.
Activity,Receiver,Serviceetc.
Thecore building blocks or fundamental components ofandroid are activities, views, intents,
s ervices,content providers,fragmentsandAndroidManifest.xml.
Activity
Anactivityisaclassthatrepresentsasinglescreen.ItislikeaFrameinAWT.
View
Aview istheUIelementsuch as button,label,textfield etc.Anythingthatyou seeisaview.
Intent
Intentisusedto invokecomponents.Itismainlyusedto:
o
Starttheservice
o
Launcheractivity
o
Display Webpage
o
Displayalistof contacts
o
Broadcast Message
o
Dialaphone Calletc.
For Example,you may write the following codetoview the webpage.
1. Intent Intent=newIntent(Intent.ACTION_VIEW);
2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);
Service
S erviceisabackgroundprocessthatcanrunforalongtime.Therearetwotypeso fserviceslocaland
remote. Local service is accessed from within the application whereas remote service is accessed
remotely from other applications running on the same device.
ContentProvider
ContentProvidersareusedto share data between the applications.
Fragment
Fragmentsarelikepartsofactivity.Anactivitycandisplayoneormorefragmentsonthescreenatthesametime.
AndroidManifest.xml
Itcontainsinformationabout Activities,content providers,permissions etc.Itisliketheweb.xml
file in Java EE.
AndroidVirtualDevice(AVD)
DalvikVirtualMachine|DVM
As we know the modern JVM is high performance and provides excellent
memorymanagement.Butitneedsto
beoptimizedforlow-poweredhandhelddevicesaswell.
TheDalvik Virtual Machine(DVM)is an android virtual machine optimized for mobile devices.It
optimizes the virtual machine for memory,battery life and performance.
DalvikisanameofatowninIceland.TheDalvikVMwaswrittenbyDanBornstein.
TheDexcompilerconvertstheclassfilesintothe.dexfilethatrunontheDalvikVM.Multipleclassfilesareconve
rted intoonedexfile.
Let's See The Compiling And Packaging process from the source file:
Thejavactoolcompilesthejavasourcefileintotheclassfile.
Thedxtooltakesalltheclassfilesofyourapplicationandgeneratesasingle.dexfile.Itisaplatform-
specifictool.
TheAndroidAssetsPackagingTool(aapt)handle the packaging process.Internal
Details For working helloandroid example.
AndroidStudioisthepremiertoolproducedbyGoogleforcreatingAndroidappsanditmorethanmatchesthat
o ther IDEusedbyMicrosoftdevelopersforcreating Windowsphoneapps.
Step-1
DownloadandInstallAndroidStudio
ThefirsttoolyouneedtodownloadisofcourseAndroidStudio.YoucandownloadAndroidStudio
AndroidVirtualDevice(AVD)
Itisusedtotesttheandroidapplicationwithouttheneedformobileortabletetc.Itcanbecreatedindifferentcon
figurationstoemulatedifferenttypesofreal devices.
AndroidEmulatorisusedtorun,debugandtestthe android application.If Don'thavethereal
device,itcanbethebestwaytorun,debug andtestthe application.
ItusesanopensourceprocessoremulatortechnologycalledQEMU.
Theemulatortoolenablesyoutostarttheemulatorfromthecommandline.Youneedtowrite:emul
ator-avd<AVD NAME>
IncaseofEclipseIDE,you cancreateAVDbyW indowmenu>AVDManager> New.
TheDalvikVirtualMachine(DVM)isanandroidvirtualmachineoptimizedformobiledevices.It
optimizes the virtual machine for memory,battery life and performance.
DalvikisanameofatowninIceland.TheDalvikVMwaswrittenbyDanBornstein.
TheDexcompilerconvertstheclassfilesintothe.dexfilethatrunontheDalvikVM.Multipleclassfilesareconve
rted intoonedexfile.
Let's See The Compiling And Packaging process from the source file:
Thejavactoolcompilesthejavasourcefileintotheclassfile.
Thedxtooltakesalltheclassfilesofyourapplicationandgeneratesasingle.dexfile.Itisaplatform-
specifictool.
TheAndroidAssetsPackagingTool(aapt)handles the packaging process.Internal
Details For working helloandroid example.
Step-1
DownloadandInstallAndroidStudio
ThefirsttoolyouneedtodownloadisofcourseAndroidStudio.YoucandownloadAndroidStudio
this:
android-studio-
ide-143.2915827-linux.zipExtractthezipfilebyrunni
ngthefollowingcommand:
sudounzipandroid-studio-ide-143.2915827-linux.zip-d/optR
eplacetheandroidfilenamewiththeonelistedbythelscommand.
Step-2
RunAndroidStudio
TorunAndroidStudio,navigatetothe/opt/android-studio/binfolderusingthecdcommand:
cd/opt/android-studio/bin
Thenrunthefollowing command:
shstudio.sh
✔ A screen will appear asking whether you want to import settings. Choose thesecond
✔ ThiswillbefollowedbyaWelcomescreen.
Step-4
ChooseanInstallationType
✔ Screenwillappearwithoptionsforchoosingstandardsettingsorcustomsettings.
✔ Now,click"Finish".
Step-5
CreatingYourFirstProject
Ascreenwillappearwithoptionsforcreatinganewprojectandopeningexisting
projects.Choosethestartanew projectlink.
Ascreenwillappearwiththefollowingfi
elds:
Applicationname
Company
For This example, change the application name to"HelloWorld"and leave the
restasthedefaults.Click"Next"
Step-6
Choose Which Android Devices Target
Ucannow Choose Which Type of Android device you
wish to target.
he Options Are As Follows:
T
Phone/Tablet
Wear
TV
Android
Auto Glass
that for each o ption you choose it will show you how many devices will be able to run
yourapp.
✔
✔
✔
✔
✔ Click"Next"
Step-7
Choose anActivity
✔Ascreenwillappearaskingforyoutochooseanactivity.
✔Anactivityinitssimplestformisascreenandtheoneyouchooseherewillactasyourmainacti
vity.
✔Choose"BasicActivity"and click"Next".
AndroidStudiowillnowloadandyoucanrunthe
defaultprojectthathasbeensetupbypressingshiftandF10.
✔Don'tworryyoudon'tneedtheactualdeviceasthephoneortabletwillbeemulatedbyyour
computer.
✔ Click"Next".
✔You will now be back at the choose a deployment target screen. Select the phone or
1.9OralQuestion?
1.What Is the Current Version ofAndroid?
2.What Is the Difference Between Android andiOS?
3.Whoisfounderof Android?
4.Does Android Support Other Languages Than Java?
WhatisActivity?
EXPERIMENT-6
Title:
Design Mobile App For media player.
ProblemDefinition:
ImplementingmediaplayerforAudioandVideo.
1.1Prerequisite:
● ConceptsofMediaPlayerClass.
● BasicconceptsofMediaPlayerAudio andVideo.
1.2 SoftwareRequirements:
AndroidStudio
1.3Tools/Framework/LanguageUsed:
AndroidStudio
1.4 HardwareRequirement:
PIV,4GB RAM,500GB HDD, LenovoA13-4089Model
1.5LearningObjectives:
Implementing Arrayadapter And Mediaplayer Class.
1.6 Outcomes:
AftercompletionofthisassignmentstudentareabletoImplementMediaplayer.
1.7 TheoryConcepts:
AndroidMediaPlayerExample
✔ WecanplayandcontroltheaudiofilesinandroidbythehelpofMediaPlayerclass.
audioplaybacklikestart,stop,pause etc.
✔ MediaPlayerclass
publicvoidsetDataSource(Stringpath) Setsthedatasource(filepathorhttpurl)t
use.
playback synchronously.
publicbooleanisLooping() Checksiftheplayerisloopingornon-loopi
ng.
AndroidVideoPlayerExample
✔ Theandroid.widget.MediaControllerisaviewthatcontainsmediacontrolslikeplay/pause,pre
vious,next,fast-forward,rewindetc.
✔VideoViewclass
✔ Theandroid.widget.VideoViewclassprovidesmethodstoplayandcontrolthevideoplayer.Th
Method Description
ublicvoid
P etsthemediacontrollertothe
S
setMediaController(MediaControllercontroller Videoview.
)
publicvoidsuspend() Suspendstheplayback.
1.8AssignmentQuestion?
1.Explain ArrayAdapter Class?
2.ExplainMedia PlayerClass?
3.ExplainVideo ViewClass?
4.ExplainList ViewClass?
5.ExplainMedia RecorderClass?
EXPERIMENT- 7
Title:
1.2SoftwareRequirements:
AndroidStudio
1.3Tools/Framework/LanguageUsed:
AndroidStudio
1.4HardwareRequirement:
PIV,4GB RAM,500GB HDD, LenovoA13-4089Model
1.5LearningObjectives:
Implementapptostoredatausinginternalorexternalstorage.
1.6Outcomes:
AftercompletionofthisassignmentstudentareabletoImplementApptostoredatausingint
ernalor externalstorage.
1.7TheoryConcepts:
AndroidPreferencesExample
Android shared preference is used to store and retrieve primitive
information. In android,string,integer,long,number etc.are considered
asprimitivedatatype.
Android Shared preferences are used tostoredatainkeyandvaluepairsso
that we can retrieve the value on the basis key.
Android provides many kinds o f storage for applications to store their data.
These storage places are shared preferences, internal and external storage,
SQLite storage, and storage via network connection.
Itiswidelyusedtogetinformationfromusersuchasinsettings
AndroidInternalStorageExample
Weareabletosaveo rreaddatafromthedeviceinternalmemory.
FileInputStream andFileOutputStream
classesareusedtoreadandwritedataintothefile.
Here,wearegoingtoreadandwritedatatothe internal storage the device.
In o rder to use internal storage to write some data in the file, call the
o penFileOutput() method with the name o f the file andthemode.Themode
could be private, public etc. Its syntax is given below –
Reading File
In order to read from the file you just created, call the
o penFileInput() method with
thenameofthefile.ItreturnsaninstanceofFileInputStream.Itssyntaxisgivenbel
ow −
ethodsofwriteandclose,thereareothermethodsprovidedbytheFileOutputStreamclas
M
sfor
better writing files.These Methods Are Listed Below −
FileOutputStream(File File,Booleanappend)
1
ThismethodconstructsanewFileOutputStreamthatwritesto file.
etChannel()
g
2 Thismethodreturnsawrite-onlyFile
Channelthatsharesitspositionwiththisstream
getFD()
3
This Method Returns The Underlying File Descriptor
rite(byte[]buffer,intbyteOffset,intbyteCount)
w
4 ThismethodWritescountbytesfromthebytearraybufferstartingatposition
o ffsettothisstream
Apart from the methods of read and close,
thereareothermethodsprovided byte FileInput Stream Class
Forbetterreadingfiles.These Methods Are Listedbelow–
vailable()
a
1 Thismethodreturnsanestimatednumberofbytesthatcanbereador skipped
withoutblockingfor moreinput
etChannel()
g
2 Thismethodreturnsaread-onlyFileChannelthatsharesitspositionwiththisst
ream
getFD()
3
This Method Returns The Underlying file descriptor
r ead(byte[]buffer,intbyteOffset,intbyteCount)
4 Thismethodreadsatmostlengthbytesfromthisstreamandstoresthem in
thebytearraybstarting atoffset
AndroidExternalStorageExample
Like internal storage, we are able to saveo rreaddatafromthedevice's
external memory such as sd card. The File Input Stream and File Output
Stream classes are used to read and write data into the file.
1.8AssignmentQuestion?
1.ExplaingetExternalstorageDirectory()?
2.What Is the Difference Between InternalandExternalmemory?
3.WhatistheuseofsharedpreferenceinAndroidandwherearetheystored?
4.What Do You Mean Contentprovider? ExplaingetPathmethod
EXPERIMENT-8
Title:
DesignamobileappusingGoogleMapandGPStotracethelocation.
ProblemDefinition:
ImplementapptousingGoogleMapandGPStotracethelocation.
1.1 Prerequisite:
● BasicconceptsofGoogleMap.
● BasicConceptofGPSfortracelocation.
1.2 SoftwareRequirements:
AndroidStudio
1.3 Tools/Framework/LanguageUsed:
AndroidStudio
1.4 HardwareRequirement:
PIV,4GB RAM,500GB HDD, LenovoA13-4089Model
1.5 LearningObjectives:
ImplementapptousingGoogleMapandGPStotracethelocation.
1.6 Outcomes:
After completion o f this assignmentstudentareabletoImplementAppto
using Google Map andGPStotracethelocation
1.7 TheoryConcepts
Androidapplicationwhichwilldisplaylatitudeandlongitudeo fthecurrent
locationinatextviewandcorrespondinglocationintheGoogleMap.Thecurrent
location will be retrieved using GPSand LocationManagerAPIoftheAndroid.
Location
publicclassLocation
extends Object implements Parcelable Java.lang.Object
↳ android.location.Location
LocationManager
public class
LocationMan
agerextends
Objectjava.la
ng.Object
↳ android.location.LocationManager
Unless Noted,allLocationAPImethodsrequire
The ACCESS_COARSE_LOCATIONo r ACCESS_FINE_LOCATIONpermissions. If your
applicationo nlyhasthecoarsepermissionthenitwillnothaveaccesstotheGPS
o rpassivelocationproviders.OtherProviderswillstillreturnlocationresults,but
the update rate will be throttled and the exact location will deobfuscate
toacoarselevel inaccuracy.
LocationProvider
public class LocationProvider
extendsObjectjava.lang.Object
android.location.LocationProvider
Anabstractsuperclassforlocationproviders.Alocationproviderprovides
periodic reports on geographical location of the device.
Each provider has a set o f criteria under which it may be used; for
example, some providers require GPS hardware and visibility to a number o f
satellites; o thers require the use o f the cellular radio, o r access to a specific
carrier's network, o r to the internet. They may also have different battery
consumption characteristics o r monetary costs to the user. The Criteriaclass
allows providers to be selected based on user-specified criteria.
Location ManagerMethods: -
Public Methods
boolean addNmeaListener(OnNmeaMessageListenerlistener,Handlerhandler)
Addison NMEA listener.
void addTestProvider(Stringname,booleanrequiresNetwork,booleanrequiresSatellite,
booleanrequiresCell,booleanhasMonetaryCost,booleansupportsAltitude,boolean
supportsSpeed,booleansupportsBearing,intpowerRequirement,intaccuracy)
Createsamocklocationproviderandaddsittothesetofactive
providers.
void c learTestProviderEnabled(Stringprovider)
Removesanymockenabledvalueassociatedwiththegivenprovider.
void c learTestProviderLocation(Stringprovider)
Removesanymocklocationassociatedwiththegivenprovider.
void c learTestProviderStatus(Stringprovider)
Removesanymockstatusvaluesassociatedwiththegivenprovider.
List<String> getAllProviders()
Returnsalistofthenamesofallknownlocationproviders.
GpsStatus getGpsStatus(GpsStatusstatus)
RetrievesinformationaboutthecurrentstatusoftheGPSengine.
Location etLastKnownLocation(Stringprovider)
g
ReturnsaLocationindicatingthedatafromthelastknownlocationfixobtainedfromthe
givenprovider.
LocationProvi getProvider(String Name)
der Returnstheinformationassociatedwiththelocationproviderofthe
given name, or null if no provider exists by that name.
List<String> getProviders(booleanenabledOnly)
Returns A List Of The names of location providers.
boolean isProviderEnabled(Stringprovider)
Returns The Current Enabled/disabled status of the given provider.
boolean registerGnssMeasurementsCallback(GnssMeasurementsEvent.Callbackc allback,H
andlerhandler)
Register GPS Measurement callback.
boolean registerGnssMeasurementsCallback(GnssMeasurementsEvent.Callbackc allback)
Register GPS Measurement callback.
void r equestSingleUpdate(Stringprovider,PendingIntentintent)
Registerforasinglelocationupdateusinganamedproviderandpendingintent.
void requestSingleUpdate(Stringprovider,LocationListenerlistener,
L
o
o
p
e
r
l ooper)
Registerforasinglelocationupdateusingthenamedproviderandacallback.
listener,Looperlooper)
RegisterforasinglelocationupdateusingaCriteriaandacallback.
void requestSingleUpdate(Criteriac riteria,PendingIntentintent)
RegisterforasinglelocationupdateusingaCriteriaandpendingintent.
PermissionRequiredforGPSTracking
Onlyfinelocationwillallowyouaccesstogpsdata,andallowsyouaccess
toeverythingelsecoarselocationgives.YoucanusethemethodsoftheLocationManage
rto acquire location data from gps and cell tower sources already,you
donothavetoworkoutthisinformation yourself.
The main permissions you need
areandroid.permission.ACCESS_COARSE_LOCATIONorandroid.permission.ACCESS_
FINE_LOCATION.
This permission should allow your app to use location services through the
devicesGPS,Wi-Fi,and cell towers.Justplopitinyourmanifest Wherever Put Your
permissions,anditshoulddothetrick.Youcanfindalltheotherpermissionshere:(http://
developer.android.com/reference/android/Manifest.permission.html)
Hereisthecity:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
LocationListener
public interface
LocationListener
android.location.LocationList
ener
Used forreceivingnotificationsfromtheLocationManagerwhenthelocationhaschanged.
These methods are called if the LocationListener has been registered with the location
manager service using therequestLocationUpdates(String, long,float,LocationListener)
method.
Public Methods
extrasBundle:anoptionalBundlewhichwillcontainproviderspecificstatusvariables.
Anumberofcommonkey/valuepairsfortheextrasBundlearelistedb
elow.Providersthatuseanyo fthekeyso nthislistmustprovide
the corresponding value as described below.
1. ExplainimportantstepsforTracethelocationusingGoogleMap?
2. Explain Important Steps For TracethelocationusingGPS?
3. Whataredifferenttypesofsensorsavailableinmobiledevice?
4. ExplainonProviderDisabledandonProviderEnabledmethod?
5. Explainlocation.getLatitude()andlocation.getLongitude()?