android lab1
android lab1
Work Book
Android Programming
To be implemented from
Academic Year 2024–2025
Name:
College Name
Academic Year:
CERTIFICATE
Instructor HOD/Coordinator
1 Introduction to Android
6 Databases – SQLite
You should read the following topics before starting this exercise:
1. Java Installation
2. Android Studio
3. Android architecture
ll. Scroll
down and select ―Android 4.4.2 (API 19)‖ and ―Intel x86 Emulator
Accelerator (HAXM installer)‖
9) Install the packages. You may need to repeat the process of installing packages until all
of them are installed. When the ―Install packages…‖ button is no longer active you may
close the Android SDK Manager.
10) To create new project, click on Start a new Android Studio project.
11) You may change the Application name and Company Domain.
12) Select API 19 as the Minimum SDK.
13) Select Blank Activity.
14) The default values are good.
15) The Windows Firewall may complain again. Click on Allow access.
16) Select the AVD Manager from the toolbar at the top.
17) Edit this AVD by clicking the green marker icon on the right.
18) Change the AVD name to Nexus 5 API 19 and OS from Lollipop to KitKat.
19) Change the Google API from Lollipop to KitKat API level 19.
a. The x86 virtual devices run faster on a Windows system. If you have problems
running it then select armeabi-v7a Google APIs instead.
Android Studio is now installed. It automatically checks for updates. If you update it you may
need to repeat some of the steps above to get it working again.
In the Project > Android view of your previous task, there are three top-level folders
below your app folder: manifests, java, and res.
This folder contains AndroidManifest.xml. This file describes all of the components of
your Android app and is read by the Android run-time system when your program is
executed.
2. Expand the java folder. All your Java language files are organized in this folder. The
java folder contains three subfolders:
o com.example.hello.helloworld (or the domain name you have specified): All
the files for a package are in a folder named after the package. For your Hello
World application, there is one package and it only contains MainActivity.java
(the file extension may be omitted in the Project view). o
com.example.hello.helloworld(androidTest): This folder is for your
instrumented tests, and starts out with a skeleton test file.
o com.example.hello.helloworld(test): This folder is for your unit tests and starts
out with an automatically created skeleton unit test file.
3. Expand the res folder. This folder contains all the resources for your app, including
images, layout files, strings, icons, and styling. It includes these subfolders:
o drawable: Store all your app's images in this folder.
o mipmap: Store your launcher icons in this folder. There is a sub-folder for each
supported screen density. Android uses the screen density, that is, the number of
pixels per inch to determine the required image resolution. Android groups all
actual screen densities into generalized densities, such as medium (mdpi), high
(hdpi), or extra-extra-extra-high (xxxhdpi). The ic_launcher.png folder contains
the default launcher icons for all the densities supported by your app.
o values: Instead of hardcoding values like strings, dimensions, and colors in your
XML and Java files, it is best practice to define them in their respective values
file. This makes it easier to change and be consistent across your app.
4. Expand the values subfolder within the res folder. It includes these subfolders:
o colors.xml: Shows the default colors for your chosen theme, and you can add
your own colors or change them based on your app's requirements.
o dimens.xml: Store the sizes of views and objects for different resolutions.
o strings.xml: Create resources for all your strings. This makes it easy to translate
them to other languages.
o styles.xml: All the styles for your app and theme go here. Styles help give your
app a consistent look for all UI elements.
Android Studio uses Gradle as its build system. As you progress through these practicals,
you will learn more about gradle and what you need to build and run your apps.
1. Expand the Gradle Scripts folder. This folder contains all the files needed by the build
system.
2. Look for the build.gradle(Module:app) file. When you are adding app-specific
dependencies, such as using additional libraries, they go into this file.
In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device
or emulator that simulates the configuration for a particular type of Android device.
Using the AVD Manager, you define the hardware characteristics of a device and its API level,
and save it as a virtual device configuration.
When you start the Android emulator, it reads a specified configuration and creates an emulated
device that behaves exactly like a physical version of that device, but it resides on your
computer.
Why: With virtual devices, you can test your apps on different devices (tablets, phones) with
different API levels to make sure it looks good and works for most users. You do not need to
depend on having a physical device available for app development.
In order to run an emulator on your computer, you have to create a configuration that
describes the virtual device.
1. In Android Studio, select Tools > Android > AVD Manager, or click the AVD
4. system to run on the virtual device. You can select the latest system image.
There are many more versions available than shown in the Recommended tab. Look at
the x86 Images and Other Images tabs to see them.
5. If a Download link is visible next to a system image version, it is not installed yet, and
you need to download it. If necessary, click the link to start the download, and click
Finish when it's done.
6. On System Image screen, choose a system image and click Next.
Verify your configuration, and click Finish. (If the Your Android Devices AVD Manager
window stays open, you can go ahead and close it.) 5. Run your app on an emulator
In this task, you will finally run your Hello World app.
You should see the Hello World app as shown in the following screenshot.
Assignment Evaluation
1. Activity
An activity is a single, focused thing that the user can do. Almost all activities interact with the
user, so the Activity class takes care of creating a window for you in which you can place your
UI with setContentView(View).
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is
placed on the top of the stack and becomes the running activity - the previous activity always
remains below it in the stack, and will not come to the foreground again until the new activity
exits.
Public Methods Description
void onCreate(Bundle saveInstanceState) Called when the activity is first created. This
is where you should do all of your normal
static set up: create views; bind data to lists,
etc.
void onRestart() Called after your activity has been stopped,
prior to it being started again.
void onStart() Called when the activity is becoming visible
to the user.
void onResume() Called when the activity will start interacting
with the user.
void onPause() Called when the system is about to start
resuming a previous
void onDestroy() The final call you receive before your activity is This
can happen either because the activity is finishing
This method is used get in this method a reference to the
void onAttach (Activity activity) activity which uses the fragment for further initialization
work.
The system calls this method when creating the fragment.
activity. This is typically used to commit unsaved
void onCreate (Bundle changes to persistent
2. Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
View onCreateView (LayoutInflater The system calls this callback when it's time for the
inflater, ViewGroup container, fragment to draw its user interface for the first time.
Bundle savedInstanceState)
void onActivityCreated (Bundle This method is called when the host activity is
savedInstanceState) created. In this method you can instantiate objects
which require a Context object.
void onStart() This method is called once the fragment gets visible.
void onResume() Fragment becomes active.
void onPause() The system calls this method as the first indication
that the user is leaving the fragment. This is usually
where you should commit any changes that should
be persisted beyond the current user session. 2 In
void onStop() Fragment going to be stopped by calling onStop() tent
An
void onDestroyView() Fragment view will destroy after call this method
void onDestroy() This method is called to do final cleanup of the
fragment's state but Not guaranteed to be called by
the Android platform.
Method Description
Context.startActivity() The Intent object is passed to this method to launch a new activity
or get an existing activity to do something new.
Context.startService() The Intent object is passed to this method to initiate a service or
deliver new instructions to an ongoing service.
Context.sendBroadcast() The Intent object is passed to this method to deliver the message to
all interested broadcast receivers.
Example: Assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the
Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses
through a list of Activities and chooses the one that would best match your Intent, in this case, the
Web Browser Activity. The Intent Resolver then passes your web page to the web browser and
starts the Web Browser Activity.
String q = "developers.android";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent)
SET A
1. Create a Simple Application Which Shows Life Cycle of Activity.
2. Create a Simple Application Which Send ―Hello‖ message from one activity to another with
help of Button (Use Intent).
3. Create Simple application to display details of selected list item on Second Activity (use
Fragmentation)
SET B
1 Create simple application with Login Screen. On successful login, gives message go to
next Activity (Without Using Database)
3 . Create First Activity to accept information like Student First Name, Middle Name, Last
Name, Date of birth, Address, Email ID and display all information on Second Activity when
user click on Submit button.
SET C
Design Following Screens Using Intents. On second activity take Button. On clicking it, it
should Show Information of profile on Third activity. (Without Using Database)
Assignment Evaluation
c. 0: Not Done [ ] 1: Incomplete [] 2: Late Complete []
d. 3: Needs Improvement [] 4: Complete [] 5: Well-done []
Assignment No. 3 No. of Sessions: 02
Types of layouts
1. Linear Layout: Linear Layout is a view group that aligns all children in a single direction,
vertically or horizontally.
2. Absolute Layout:
Absolute Layout enables you to specify the exact location of its children.
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px"/>
<Button android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px"
android:layout_y="361px"/>
</AbsoluteLayout>
3. Table Layout: Table Layout is a view that groups views into rows and columns.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"/>
3. RelativeLayout: Relative Layout is a view group that displays child views in relative
positions.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder"/>
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
20
android:layout_below="@+id/name">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2"/>
</LinearLayout>
</RelativeLayout>
5. ScrollLayouts: When an app has layout content that might be longer than the height of
the device and that content should be vertically scrollable, then we need to use a Scroll
View.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:fillViewport="false">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="@drawable/image"/>
<Button android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="KNOW MORE"/>
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView android:id="@+id/textView2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/description"
android:textAppearance="?android:attr/textAppearanceSmall"/>
6. ScrollView: ScrollView
is a special kind of layout, designed to hold view larger than its actual size. When the Views
size goes beyond the ScrollView size, it automatically adds scroll bars and can be scrolled
vertically.
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_long" android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/really_long_string">
</TextView>
<Button android:id="@+id/btn_act"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View">
</Button>
</LinearLayout>
</ScrollView>
<Button android:layout_width="120px"
android:layout_height="wrap_content"
android:text="Position - Bottom Middle"
android:id="@+id/buttondisplay7"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true" />
Managing changes to screen orientation Some device configurations can change during
runtime (such as screen orientation, keyboard availability, and language). When such a
change occurs, Android restarts the running Activity. To properly handle a restart, it is
important that your activity restores its previous state through the normalActivity lifecycle,
in which Android calls onSaveInstanceState() before it destroys 24 your activity so that you
can save data about the application state. Details on how you can use onSaveInstanceState()
can be found at Saving and restoring activity state.
a. Retain an object during a configuration change Allow your activity to restart when a
configuration changes, but carry a stateful object to the new instance of your activity.
b. Handle the configuration change yourself Prevent the system from restarting your
activity during certain configuration changes, but receive a callback when the
configurations do change, so that you can manually update your activity as necessary.
c. Retaining an Object during a Configuration Change When the Android system shuts
down your activity due to a configuration change, the fragments of your activity that you
have marked to retain are not destroyed. You can add such fragments to your activity to
preserve stateful objects.
i) Extend the Fragment class and declare references to your stateful objects
. ii) Call setRetainInstance(boolean) when the fragment is created
iii) Add the fragment to your activity.
iv) Use FragmentManager to retrieve the fragment when the activity is restarted
public class RetainedFragment extends Fragment{
// data object we want to retain
private MyDataObject data;
// this method is only called once for this fragment
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setData(MyDataObject data){
25
this.data= data;
}
public MyDataObject getData(){
return data;
}
}
While onCreate() is called only once when the retained fragment is first created you can use
onAttach() or onActivityCreated() to know when the holding activity is ready to interact
with this fragment. And in your activity you can use this fragment to preserve states across
configuration change restarts. Then use FragmentManager to add the fragment to the
activity. You can obtain the data object from the fragment when the activity starts again
during runtime configuration changes.
For example, define your activity as follows:
this.data= data;
}
public MyDataObject getData(){
return data;
}
}
In order to proactively remove the retained fragment when you no longer need it, you may
check for isFinishing() in onPause() in the activity.
@Override
public void onPause(){
// perform other onPause related actions
...
// this means that this activity will not be recreated now, user is leaving it
// or the activity is otherwise finishing
if(isFinishing()){
FragmentManager fm = getFragmentManager();
// we will not need this fragment anymore, this may also be a good place to
signal
// to the retained fragment object to perform its own cleanup.
fm.beginTransaction().remove(mDataFragment).commit();
}
}
under res ⇒ menu named activity_main_actions.xml and add the following code. Here each
action bar uses the same older menu method to show action items. Create a new xml file
Here the important xml attributes should be known are android:icon – Defines the icon of
the action item
. android:title – Title for the icon.
Androidd:showAsAction – Defines the visibility of the action item. It accepts following
values.
withText Displays a text along with the icon. Normally the text value
defined by android:title will be displayed
collapseActionView Defines the action layout associated with it. This action view
defined usingandroid:actionLayout or android:actionViewClass
3. Create the simple calculator shown below also perform appropriate operation
SET B
1. Create new contact for designing following layout
SET C
1. Create following layout which is changing android spinner text size with styles.
Assignment Evaluation
Types of View
TextView: TextView used to create text field.
A TextView displays text to the user and optionally allows them to edit it.
Attribute Name Description
android:id This is the ID which uniquely identifies the control.
android:editable If set to true, specifies that this TextView has an input method.
android:inputType The type of data being placed in a text field. Phone, Date, Time,
Number, Password etc.
<TextView android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" android:id="@+id/button"
/>
To access the value of Button make following changes in MainActivity.java file
Button b1 = (Button)findViewById(R.id.button);
android:cropToPadding If true, the image will be cropped to fit within its padding.
android:src This sets a drawable as the content of this ImageView.
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
To create ImageButton
android:src="@drawable/abc"/>
To access the value of ImageButton make following changes in MainActivity.java file
<ToggleButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="On"
android:id="@+id/toggleButton"
android:checked="true" />
To access the value of ToggleButton make following changes in MainActivity.java file
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
To create RadioButton make following changes in res/layout/activity_main.xml file
android:text="ANDROID"
android:id="@+id/radioButton2" android:checked="false"
/>
• RadioGroup: A RadioGroup class is used for set of radio buttons. If we check one radio
button that belongs to a radio group, it automatically unchecks any previously checked radio
button within the same group.
<RadioGroup android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_marginTop="58dp"
android:id="@+id/radioGroup" >
<RadioButton android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:checked="false" />
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" android:id="@+id/radioButton2"
To create RadioGroup make following changes in res/layout/activity_main.xml file
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup); int
selectedId=radioGroup.getCheckedRadioButtonId();
• CheckBox: A CheckBox is an on/off switch that can be toggled by the user. You should
use check-boxes when presenting users with a group of selectable options that are not
mutually exclusive.
<CheckBox android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false" />
To access the value of CheckBox make following changes in MainActivity.java file
• ProgressBar: Allows you to create progress bar. Progress bars are used to show progress of
a task.
void incrementProgressBy(int diff) This method increment the progress bar by the
difference of value passed as a parameter.
void setMax(int max) This method sets the maximum value of the
progress dialog.
void show(Context context, CharSequence This is a static method, used to display progress
title, CharSequence message) dialog.
<ProgressBar android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress=‖25‖ />
progressBar = (ProgressBar) findViewById(R.id.progressBar); new
Thread(new Runnable() {
progressStatus += 1;
// Update the progress bar and display the current value in the text view
handler.post(new Runnable() {
textView.setText(progressStatus+"/"+ progressBar.getMax());
});
try {
} catch (InterruptedException e) {
e.printStackTrace();
}).start();
<AutoCompleteTextView android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
TimePicker:
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The
time consists of hours, minutes and clock format.
Public Methods Description
boolean is24HourView() Returns true if this is in 24 hour view
boolean isEnabled() Returns the enabled status for this view
void setCurrentHour(Integer currentHour) This method sets the current hour
void setCurrentMinute(Integer currentMinute) This method sets the current minute
void setIs24HourView(Boolean is24HourView) This method set whether in 24 hour or
AM/PM mode
void setOnTimeChangedListener
This method Set the callback that indicates the
(TimePicker.OnTimeChangedListener time has been adjusted by the user
onTimeChangedListener)
<DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
• ListView: ListView is a view which groups several items and display them in vertical
scrollable list. The list items are automatically inserted to the list using an Adapter that pulls
content from a source such as an array or database.
To create ListView make following changes in res/layout/activity_main.xml file
<ListView android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
To access the value of ListView make following changes in MainActivity.java file
// Array of strings...
• Spinner: Spinner allows you to select an item from a drop down menu To create Spinner
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"/>
To access the value of Spinner make following changes in MainActivity.java file
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
categories.add("Automobile");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
43
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
46
ListFragment:
A list fragment is a fragment that contains a ListView, displaying a list of items from a data
source such as an array or a Cursor
<fragment
44
android:id="@+id/fragment1"
android:name="com.example.admin.ListFragmentExample.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 2: Create fragment1.xml in res/layout folder and add below code in fragment1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="10dp"
android:orientation="vertical">
<ListView android:id="@id/android:list"
android:layout_width="match_parent"
package com.example.admin.ListFragmentExample;
android.os.Bundle; import
45
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1,container,false);
}
android:layout_height="match_parent"
public void onCreate(Bundle savedInstanceState) {
android:layout_weight="1"
super.onCreate(savedInstanceState);
android:drawSelectorOnTop="false" />
setListAdapter(new ArrayAdapter<String>(getActivity(),
<android.R.layout.simple_list_item_1,
/LinearLayout> CountryNames) );
}
Step 3: Create a Java Class file and name it MainActivity.
46
Toast.LENGTH_SHORT).show( );
@Override
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
Step 2: Define DialogFragment Layout as given below:
47
android:gravity="center"
android:padding="10dp"
android:orientation="vertical"> <TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:id="@+id/dismiss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dismiss" />
</LinearLayout>
Step 3: To display the DialogFragment, Add below code into MyDialogFragment.java
onCreateView() method.
FragmentManager fm = getFragmentManager();
dismiss.setOnClickListener(new View.OnClickListener() {
dismiss();
});
48
2. PreferenceFragment: Allow users to personalize the application for their own use.
Steps to create PreferenceFragment
Step 1: Create a new xml folder under res folder and then add a new Android XML file to
it. Name the xml file preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:title="CheckBox"
android:defaultValue="false"
android:summary="True or Flase"
android:key="checkboxPref" />
</PreferenceCategory>
package com.example.admin.PreferenceFragmentExample;
<PreferenceCategory android:title="Category 2">
import android.os.Bundle; import
<EditTextPreference android:name="EditText"
android.preference.PreferenceFragment; public class
android:title="Edit Text"
Fragment1 extends PreferenceFragment {
android:key="editTextPref" />
android.app.FragmentTransaction;
49
FragmentManager fragmentManager = getFragmentManager();
SET A
1. Create a custom "Contact" layout to hold multiple pieces of information, including: Photo,
Name, Contact Number, E-mail id.
2. By using Spinner, Buttons. Write a program to draw following GUI
SET B
1. Create application to demonstrate file explorer (Use ListView).
50
2. Create registration form given below. Also perform appropriate validation and display the
message using dialog fragment.
SET C
Create application to demonstrate alarm.
Assignment Evaluation
51
Assignment No. 5 No. of Sessions: 02
In your application if you want display a series of images to the user, you can make use of the
Gallery. The Gallery is a view that shows items (such as images) in a center-locked, horizontal
scrolling list.
• Gallery is used to show Views in a horizontal list, and user will select a view , User
selected view will be shown in center of the Horizontal list.
• The items of Gallery are getting from an Adapter, just like ListView, in which ListView
items are getting from an Adapter.
• We need to make an Adapter class that extends BaseAdapter class and override
getView() method.
Example:
1. Using the Gallery View
1. For Android Gallery View Example, assume you have some images stored in the
res/drawable-mdpi folder of your project.
2. Create an XML file named attrs.xml and store it in the res/values folder.
52
3. Add this content to the attrs.xml file:
<resources>
<declare-styleable name="MyGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
Open ―res/layout/activity_main.xml‖ file and put this xml code it into file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}"
android:orientation="vertical" >
<Gallery android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView android:id="@+id/image1"
android:layout_width="215dp"
android:layout_height="315dp"
android:layout_gravity="center_horizontal"
android:background="#cfcfcf"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="@drawable/pic1" />
</LinearLayout>
Open ―src/package-name/MainActivity.java‖ file and add following JAVA code.
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
53
import android.widget.ImageView;
import android.widget.Toast
public class MainActivity extends Activity {
//the images to display
Integer[] imageIDs = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Note that Gallery view is deprecated in Android 4.1---
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,long id)
{
Toast.makeText(getBaseContext(),"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
// display the images selected
ImageView imageView = (ImageView) findViewById (R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
context = c;
// sets a grey background; wraps around the images
TypedArray a =obtainStyledAttributes(R.styleable.MyGallery);
itemBackground =
a.getResourceId(R.styleable.MyGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
54
return imageIDs.length; // returns the number of images
}
public Object getItem(int position) {
return position; // returns the ID of an item
}
public long getItemId(int position) {
return position;
}
// returns an ImageView view
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
. The following Try It Out shows you how to use the Gallery view to display a set of images
Using Android Studio, create a new Android project and name it Gallery
. Add the following code in the main.xmlfile
<Gallery android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<ImageView android:id=”@+id/image1”
android:layout_width=”320dp”
android:layout_height=”250dp”
android:scaleType=”fitXY” />
Right-click on the res/valuesfolder and select New File. Name the file as attrs.xml.
Populate the attrs.xmlfile as follows:
<?xml version=‖1.0‖ encoding=‖utf-8‖?>
<resources>
<declare-styleable name=‖Gallery1‖>
<attr name=‖android:galleryItemBackground‖ />
</declare-styleable>
</resources>
Prepare a series of images and name them pic1.png, pic2.png, and so on for each
subsequent image. Drag and drop all the images into the res/drawable-mdpi folder.
When a dialog is displayed, check the Copy files option and click OK.
Add the following statements into the GalleryActivity.java file
package net.learn2develop.Gallery;
55
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
importandroid.view.ViewGroup;
import android.widget.AdapterView;
60
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity{
//---theimagestodisplay---
Integer[] imageIDs ={ R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7 };
/**Calledwhentheactivityisfirstcreated.*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery= (Gallery)findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, longid)
{
Toast.makeText(getBaseContext(), ―pic‖+(position+1)+
―selected‖, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extendsBaseAdapter {
Context context;
int itemBackground;
public ImageAdapter(Context c) {
61
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes( R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
56
}
public int getCount(){
return imageIDs.length; // returnsthenumberofimages
}
publicObjectgetItem(int position){
return position; // returns the item
}
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
57
The next thing we need to do is implement the ViewFactory interface and implement
unimplemented method that returns an imageView. Its syntax is below:
imageSwitcher.setImageResource(R.drawable.ic_launcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
return myView;
}
}
The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an
object of Animation class through AnimationUtilities class by calling a static method
loadAnimation. Its syntax is given below:
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
The method setInAnimaton sets the animation of the appearance of the object on the screen
whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation
object. Apart from these methods, there are other methods defined in the ImageSwitcher class.
They are defined below.
Example:
58
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
1. Using the ImageSwitcher View
We want
import to apply some animation toimport
android.widget.BaseAdapter; the image when it transitions from one image to another. In
android.widget.Gallery;
this case, you need to use the ImageSwitcher together with the Gallery view.
import android.widget.ImageSwitcher; import android.widget.ImageView; import
The following Try It Out shows you how.
android.widget.ViewSwitcher.ViewFactory; public class ImageSwitcherActivity
1) Using Andriod, create a new Android project and name it ImageSwitcher 2)
Modify
extends the main.xml
Activity file ViewFactory
implements by adding the{following statements:
<Gallery android:id=‖@+id/gallery1‖
//---theimages to display---
android:layout_width=‖fill_parent‖
android:layout_height=‖wrap_content‖
Integer[] imageIDs = { R.drawable.pic1, />R.drawable.pic2,
<ImageSwitcher android:id=‖@+id/switcher1‖
android:layout_width=‖fill_parent‖ R.drawable.pic3, R.drawable.pic4,
android:layout_height=‖fill_parent‖
android:layout_alignParentLeft=‖true‖ R.drawable.pic5, R.drawable.pic6, R.drawable.pic7 };
android:layout_alignParentRight=‖true‖
private ImageSwitcher imageSwitcher;
android:layout_alignParentBottom=‖true‖ />
3) Right-click on the res/values folder and select New, File. Name the file attrs.xml.
public void onCreate(Bundle savedInstanceState)
4) Populate the attrs.xml file as follows:
{ imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
<?xml version=‖1.0‖ encoding=‖utf-8‖?>
imageSwitcher.setFactory(this);
<resources>
<declare-styleable name=‖Gallery1‖>
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation
(this,android.R.anim.fade_in));
<attr name=‖android:galleryItemBackground‖ />
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation
</declare-styleable>
</resources>
(this,android.R.anim.fade_out));
5) Drag and drop a series of images into the res/drawable-mdpi folder. When a dialog is
Gallery
displayed, check gallery
the Copy = option
files (Gallery)
andfindViewById(R.id.gallery1);
click OK.
gallery.setAdapter(new ImageAdapter(this));
6) Add the following statements to the ImageSwitcherActivity.java file:
gallery.setOnItemClickListener(new OnItemClickListener(){
60
Attribute Name Description
android:id This is the ID which uniquely identifies the layout.
package com.example.helloworld;
android.app.Activity; import
android.view.Menu; import
android.widget.GridView; public
savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview.setAdapter(new ImageAdapter(this));
61
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView) convertView;
}
62
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
72
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7 };
}
Let's try to run our modified Hello World! Application we just modified.
Using Menus with Views Menus are useful for displaying additional options that are not
directly visible on the main UI of an application. There are two main types of menus in
Android:
Options menu — Displays information related to the current activity. In Android, you
activate the options menu by pressing the MENU key.
Context menu — Displays information related to a particular view on an activity. In
Android, to activate a context menu you tap and hold on to it.
Creating the Helper Methods
Before you go ahead and create your options and context menus, you need to create two
helper
methods. One creates a list of items to show inside a menu, while the other handles the
event that
i fired when the user selects an item inside the menu.
Example:
1. Creating the Menu Helper Methods:--
a. Add the following statements in the MainActivity.java fil
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
private void CreateMenu(Menu menu) {
MenuItem mnu1 = menu.add(0, 0, 0, ―Item 1‖);
{
73
mnu1.setAlphabeticShortcut(‗a‘);
mnu1.setIcon(R.drawable.icon);
}
MenuItem mnu2 = menu.add(0, 1, 1, ―Item 2‖);
{
mnu2.setAlphabeticShortcut(‗b‘);
mnu2.setIcon(R.drawable.icon);
63
}
menu.add(0, 2, 2, ―Item 3‖);
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0: Toast.makeText(this, ―You clicked on Item 1‖,
Toast.LENGTH_LONG).show();
return true;
case 1: Toast.makeText(this, ―You clicked on Item 2‖,
Toast.LENGTH_LONG).show();
return true;
case 2: Toast.makeText(this, ―You clicked on Item 3‖,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
Options Menu You are now ready to modify the application to display the options menu
when the user presses the MENU button on the Android device
Displaying an Options Menu 1. Using the same project created in the previous section,
add the following statements into the MainActivity.java file
@Override public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
CreateMenu(menu); return true; }
@Override public boolean onOptionsItemSelected(MenuItem item)
{ return MenuChoice(item); }
64
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return MenuChoice(item);
}
SET A
1. Construct an app that toggles a light bulb on and off when the user clicks on toggle
button.
2. Construct an app to display the image on date wise.
3. Create a custom launcher icon
SET B
1. Construct image switcher using setFactory().
2. Construct a bank app to display different menu like windrow, deposite etc.
SET C
1. Construct App which shows Slides of multiple images after click on Slide menu
Assignment Evaluation
65
Assignment No. 6 No. of Sessions: 02
Assignment Name : Databases – SQLite
SQLite is an open source SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation. SQLite supports all the relational
database features. In order to access this database, you don't need to establish any kind of
connections for it like ODBC
SQLiteOpenHelper
Android database sqlite.SQLiteOpenHelper manages database creation, up gradation,
down gradation, version management and opening it. We need to create sub class of
SQLiteOpenHelper and override onCreate and onUpgrade and optionally onOpen. If
database is
not created, onCreate is called where we write script for database creation. If already
created, then onOpen is called which opens database
Constructors Description
SQLiteOpenHelper(Context context, String name, Create a helper object to create, open,
SQLiteDatabase.CursorFactory factory, int version) and/or manage a database
DatabaseErrorHandler errorHandler)
66
Public Methods Description
void close() Close any open database object.
String getDatabaseName() Return the name of the SQLite database being
opened, as given to the constructor.
abstract void onCreate(SQLiteDatabase db) Called when the database is created for the first
time.
void onOpen(SQLiteDatabase db) Called when the database has been opened.
void setIdleConnectionTimeout(long Sets the maximum number of milliseconds that
idleConnectionTimeoutMs) SQLite connection is allowed to be idle before it
is closed and removed from the pool.
67
to manage your own databases:
1. Database – Creation
In a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. Its syntax is given below:
SQLiteDatabase mydatabase = openOrCreateDatabase("Database
name",MODE_PRIVATE,null);
DatabaseErrorHandler errorHandler)
openDatabase(String path, It is similar to the above method but it does
SQLiteDatabase.CursorFactory factory, int flags) not define any handler to handle the errors
of databases
2. Database – Insertion We can create table or insert data into table using execSQL
method defined in SQLiteDatabase class. Its syntax is given below Example
mydb.execSQL(―CREATE TABLE IF NOT EXISTS Login(Username
varchar,Password
Varchar)”);
mydb.execSQL(―INSERT INTO Login VALUES(‗admin‘,‘admin‘);)
Another method that also does the same job but take some additional parameter is given
below. execSQL(String sql, Object[] bindArgs):
This method not only inserts data, but also used to update or modify already existing data
in database using bind arguments.
3. Database – Fetching We can retrieve anything from database using an object of the
Cursor class. We will call a method of this class called rawQuery and it will return a
resultset with the cursor pointing to the table. We can move the cursor forward and retrieve
the data.
Cursor resultSet=mydb.rawQuery(―Select * from Login‖,null);
68
resultSet.moveToFirst();
String username= resultSet.getString(0);
String password= resultSet.getString(1);
Insert Format: long insert (String table, String nullColumnHack, ContentValues values)
First argument is the table name.
Second argument is a String nullColumnHack
o Workaround that allows you to insert empty rows
o Use null
Third argument must be a ContentValues with values for the row.
Returns the id of the newly inserted item.
Example:
newId = mWritableDB.insert( TABLE_NAME, null, values);
Delete Format:
int delete (String table, String whereClause, String[] whereArgs)
First argument is table name
Second argument is WHERE clause
Third argument are arguments to WHERE clause
Example:
deleted = mWritableDB.delete( WORD_LIST_TABLE, KEY_ID + " =? ", new String[] {
String.valueOf(id) } );
Update Format:
int update(String table, ContentValues values, String whereClause, String[] whereArgs)
First argument is table name
Second argument must be ContentValues with new values for the row
Third argument is WHERE clause.
Fourth argument are the arguments to the WHERE clause
ContentValues values = new ContentValues();
values.put(KEY_WORD, word);
mNumberOfRowsUpdated = mWritableDB.update( WORD_LIST_TABLE, values, // new
values to
insert KEY_ID + " = ?", new String[]{String.valueOf(id)});
69
SET A
1. Create table Company (id, name, address, phno). Create Application for Performing the
following operation on the table.
i) Insert New Company Details.
ii) Show All the Company Details.
2. Create table Student (sno , s_name,s_class,s_addr)
Teacher (tno, t_name, qualification, experience)
Student-Teacher has many to many relationship.
Using above database Write Application to accept a teacher name from user and display
the names of students along with subjects to whom teacher is teaching.
3. Create Following Table:
Emp (emp_no,emp_name,address,phone,salary)
Dept (dept_no,dept_name,location)
Emp-Dept is related with one-many relationship.
Create application for performing the following Operation on the table
1) Add Records into Emp and Dept table.
2) Accept Department name from User and delete employee information which belongs
to that department.
SET B
1. Create sample application with login module (Check username and password). On
successful
login, pass username to next screen And on failing login, alert user using Toast (Hint :Use
Login(username, password) Table.)
1.
70
2. Create Table project (pno, p_name, ptype, duration) and employee (id, e_name,
qulification, joindate)
Project – employee have many to many relationship.
Using database perform following operation.
1) Add new record into table.
2) Accept a project name from user and display information of employees
working on the project.
SET C
1) Create simple application shown below. Create table Student(Sid ,Sname ,phno).
Use autoincrement for Sid and Perform following Operation.
a. Add Student and display its information.
b. Delete Student.
Assignment Evaluation
71
Assignment No. 7 No. of Sessions: 02
Assignment Name : Messaging and E-mail
72
Public Methods Description
ArrayList divideMessage(String text) This method divides a message text into
several fragments, none bigger than the
maximum SMS message size.
static SmsManager getDefault() This method is used to get the default
instance of the SmsManager
void sendDataMessage (String destAddress This method is used to send a data based
, String scAddress, short destinationPort, SMS to a specific application port
byte[]data, PendingIntent sentIntent,
PendingIntent deliveryIntent)
void sendMultipartTextMessage (String Send a multi-part text based SMS.
destAddress, String scAddress, ArrayList
parts, ArrayList sentIntents, ArrayList
deliveryIntents) void
sendMultipartTextMessage (String
destAddress, String scAddress, ArrayList
parts, ArrayList sentIntents, ArrayList
deliveryIntents)
void sendTextMessage(String Send a text based SMS
destinationAddress, String scAddress,
String text, PendingIntent sentIntent,
PendingIntent deliveryIntent)
2. Sending SMS messages using Intent: We can also use built-in messaging application to
send
the message.
Steps to send SMS
1) Create an Intent Object (Action to send SMS)
ACTION_VIEW action is used to launch an SMS client installed on your Android device.
2)Using Intent Object set Data/Type to send SMS smsto: is used as a URI to send message
using setData() method. data type is set to vnd.android-dir/mms-sms using setType()
method.
smsIntent.setData(Uri.parse("smsto:"));
73
smsIntent.setType("vnd.android-dir/mms-sms")
3)Intent Object used to set a message for one or more phone number with putExtra( )
method and a message can be send to multiple receivers separated by ‗:‘.
smsIntent.putExtra(―address‖,new String(―0123456789;3398765587‖)); OR
smsInent.putExtra(―address‖,‖5556 ; 5553 ; 5566‖)
3. Getting Feedback after Sending a Message: To check the status of the SMS message
sending process, two objects of PendingIntent are created. These objects are passed as
last two arguments of the sendTextMessage() method //---sends an SMS message to
another device---
SET A
1. Create application to send and receive messages using SMSManager.
2. Create application to send email.
3. Create application to send message. After sending message display delivery
report of
message.
SET B
1. Create application to design login form, validate it. Write and send email with
appropriate message.
2. Create application to send SMS with image and contact as attachment.
SET C
1. Create application to send email with attachment
GoogleMap: This is the main class of the Google Maps Android API. You cannot instantiate
a
GoogleMap object directly, rather, you must obtain one from the getMapAsync() method on
MapFragment. This class provides methods to set type of map, add markers, add polyline or
move camera etc
76
Public Method Description
Circle addCircle(CircleOptions options) Used to add a circle on the map.
Marker addMarker(MarkerOptions options) Used to add a marker on the map.
Polyline addPolyline (PolylineOptions options) Used to add a polyline on the map.
void animateCamera(CameraUpdate update) Animates the movement of the camera from
the current position to the position defined in
the update.
mMap = googleMap;
}
}
Changing Views: Google Maps is displayed in map view, which basically drawings of streets
and places of interest.
To display the satellite view add following line in onMapReady() method in the
MapsActivity.java file
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
Getting Location Data: To know the information of a location we need to find latitude
and longitude values corresponding to the position. Converting location name to
respective latitude and longitude values is called as geocoding. To do the reverse
geocoding we need to use Geocoder class.
Package Name: android
Manifest.permission: It is static nested class of Manifest. It contains the constants to add user
permission or security settings in android application
78
Constants Description
String ACCESS_FINE_LOCATION Used to access precise location.
String ACCESS_COARSE_LOCATION Used to access approximate location.
String ACCESS_NETWORK_STATE Used to access the state of the network.
String ACCESS_WIFI_STATE Used to access the state of Wi-Fi.
String CHANGE_NETWORK_STATE Used to change network connectivity state.
String INTERNET Used to open network sockets.
String WRITE_EXTERNAL_STORAGE Allows an application to write to external storage.
Package Name:
com.google.android.gms.maps CameraUpdateFactory: This class is used to create
CameraUpdate objects that change or move a map's camera. It also provides the functionality
such as Zoom In, Zoom Out and Zoom By specific amount.
Public Methods Description
Returns a CameraUpdate that moves the camera
static CameraUpdate newCameraPosition to a specified CameraPosition.
(CameraPosition cameraPosition)
static CameraUpdate newLatLng(LatLng Returns a CameraUpdate that moves the center
latLng) of the screen to a latitude and longitude specified
by a LatLng object.
79
Constructor Description
LatLng(double latitude, double longitude) Constructs a LatLng with the given latitude
and longitude, measured in degrees.
Fields Description
public final double latitude Latitude, in degrees.
public final double longitude Longitude, in degrees.
Marker: This class is used to mark particular point on Map. This class contains methods to set
opacity, title, rotation, position, or visibility of marker.
Properties Description
Alpha Sets the opacity of the marker. Defaults to 1.0.
Position The LatLng value for the marker's position on the map.
Title Sets the title and display when the user taps the marker.
Icon An image or logo that's displayed for the marker.
Visibility Set visibility of marker. By default, the marker is visible.
Rotation The rotation of the marker in degrees clockwise about the marker's anchor
point.
zIndex The draw order for the marker. The default value is 0.
80
Methods Description
float getAlpha() Returns the alpha of the marker.
String getId() Returns the marker's id.
LatLng getPosition() Returns the position of the marker.
float getRotation() Return the rotation of the marker.
String getTitle() Return the title of the marker.
float getZIndex() Returns the zIndex of the marker.
void setPosition(LatLng latlng) Sets the location of the marker.
void remove() Removes this marker from the map.
void setAlpha(float alpha) Sets the alpha (opacity) of the marker.
void setTitle(String title) Sets the title of the marker.
void setIcon(BitmapDescriptor iconDescriptor) Sets the icon for the marker.
void setRotation(float rotation) Sets the rotation of the marker in degrees
clockwise about the marker's anchor point.
Constructor Description
MarkerOptions() Creates a new set of marker options.
Address:
A class representing an Address. An address contains methods to find the information such
as Country name, Postal Code, locality etc.
Constructors Description
81
Criteria() Constructs a new Criteria object.
Criteria(Criteria criteria) Constructs a new Criteria object that is a copy of the given criteria.
Address:
A class representing an Address. An address contains methods to find the information such as
Country name, Postal Code, locality etc.
Constructor Description
Address(Locale locale) Constructs a new Address object set to the given Locale.
Public Methods Description
String getAddressLine(int index) Returns a line of the address numbered by
the given index, or null if no such line is
present.
String getCountryCode() Returns the country code of the address, or
null if it is unknown.
Constructors Description
Geocoder (Context context) Constructs a Geocoder whose responses will be localized for
the default system Locale.
Geocoder (Context context, Constructs a Geocoder whose responses will be localized for
Locale locale) the given Locale.
83
List<Address> Returns an array of Addresses that are known to
getFromLocationName(String locationName, describe the named location.
int maxResults)
Constants Description
String GPS_PROVIDER Name of the GPS location provider.
String NETWORK_PROVIDER Name of the network location provider.
LocationManager:
This class provides access to the system location services. These services allow applications
to obtain periodic updates of the device's geographical location.
void requestLocationUpdates(String provider, Register for location updates using the named
provider, and a pending intent.
long minTime, float minDistance,
LocationListener listener)
String getBestProvider(Criteria criteria, Returns the name of the provider that best
boolean enabledOnly) meets the given criteria.
Example: 1. Program to display current location of android device on the Map a. Add below
line
in the manifests/AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
b. To display the current location add following line in onMapReady() method in the
MapsActivity.java file
2. Navigating to specific location – You can set Google Maps to display a particular location
by getting the latitude and longitude values. To display the specific location add
following line in onMapReady() method in the MapsActivity.java file
LatLng pune = new LatLng(18.531387, 73.849467); mMap.addMarker(new
MarkerOptions().position(pune).title("Pune"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pune));
3. To display the information about the location using geocoding add following line in
onMapReady() method in the MapsActivity.java file
List<Address> addresses = null;
String locationName = "Shaniwar Wada Fort";
Geocoder geocoder = new Geocoder(this);
try {
addresses = geocoder.getFromLocationName(locationName,1);
104
} catch (IOException e) {
e.printStackTrace();
}
Address address = addresses.get(0);
LatLng shaniwar_wada= new LatLng(address.getLatitude(), address.getLongitude());
String addressline = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String postalCode = addresses.get(0).getPostalCode();
String title = addressline + "\n" + city + "\n" + state + "\n" + postalCode;
mMap.addMarker(new MarkerOptions().position(shaniwar_wada).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLng(shaniwar_wada));
Toast.makeText(getBaseContext(),title,Toast.LENGTH_LONG).show();
SET A
1. Write a program to find the specific location of an Android device and display details of
the place like Address line, city with Geocoding.
85
2. Write a program to search a specific location on Google Map.
3. Write a program to perform Zoom In, Zoom Out operation and display Satellite view,
Terrain view of current location on Google Map.
SET B
1. Write a program to calculate distance between two locations on Google Map.
2. Write a program to modify the above program to draw the path along a route on Google
Map.
SET C
1. Write a program to track an android device using mobile number and display the location
on Google Map.
Assignment Evaluation
86