0% found this document useful (0 votes)
22 views35 pages

Androidnotes 5

Uploaded by

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

Androidnotes 5

Uploaded by

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

Introduction to Android

Android is an operating system which is based on the Linux kernel. Android system is also called as
Android Open Source Project (AOSP), lead by Google. Android is used for mobile devices, such as smart
phones and tablet computers. The Android application makes life more comfortable and advanced for the
users.

Features of Android

The above diagram shows some features of Android:

 Android is a powerful, open source, Linux – based operating system.


 It provides a rich development environment for building the applications.
 Android has a higher success ratio, because it reduces the development cost.
 Android has a large developer community which integrates the internal application.
 It has reached the top of the smart phone market segment and day by day its user base is growing
strong.
 Android supports audio, video formats like JPEG, PNG, GIF, BMP, MP3, MP4, MIDI, AMR, AMR-
WB, MPEG-4 etc.

History of Android
 Android was developed by the Open Handset Alliance, led by Goggle.
 The first version of Android was released by Google in 2007 and the Android version 1.0 was
released in September 2008.
 In June 2012, Google announced the next Android version 4.1 Jelly Bean. This version of Android is
an incremental update which is mostly used for improving the user interface.

Android Version Description


This version comes in all shapes and sizes. It allows Android to run on a variety of
Android 1.6 Donut screen resolutions and aspect ratios.
It has a quick search box that searches the result from the web, from your phone's local
content all at once from a single box on the home screen.
This version provides Google map navigation. For example, in car navigation system,
a forward looking 3D view, voice guidance and traffic information all for free.
Android 2.1 Eclair
It provides customized ring tones, wallpapers and ability to arrange apps (applications)
and widgets across multiple screens and in folders. The 'Speech-to-text' is introduced in
this version where your spoken words appear straight on your screen.
This version provides voice capabilities which let you perform key functions on your
phone like searching, getting directions, making notes, setting alarms and more with
just the sound of your voice.
Android 2.2 Froyo
It provides portable Wi-Fi hotspot into your phone where you could stay connected
even when on the go.
This version provides gaming APIs. It builds rich, graphics-intensive 3D games. This
version introduces NFC (Near Field Communication) which supports to transmit the
Android 2.3 information between devices just by bringing them close together.
Gingerbread
This version displays how much battery of your device has been consumed, allows
you to adjust the screen brightness, find out the active applications.
This version introduces tablet-friendly design with a larger layout pattern. It enhances
the experience of reading books, watching videos, exploring maps and more.
Android 3.0
It provides a new system bar which is enabled on-screen navigation that controls your
Honeycomb
Android device. This version gives rights to the user to access essential
information easily like time, date, battery life and connection status of your device all
in one place.
This version provides Widgets which embed live app content directly on your home
screen that becomes more flexible to customize the home screen.
Android 4.0 Ice
Cream Sandwich
It manages the network data usage. It tracks how much data you used, set warning
levels and hard limits and disable your service if you reach the limit.
This version provides actionable notifications which take action directly from the
notification.
Android 4.1 Jelly
Bean It enables multiple users on one device. It provides an account switching feature where
each account has its own customized space from the home screen to wallpaper, widgets
and apps, so user can share a device and not his/her information.
This version helps to get the things done without touching the mobile screen, just with
the sound of your voice – just say “OK Google” to launch voice search, send a text, get
Android 4.4 KitKat directions or even play a song.

It has immersive design which hides everything except what you really want to see.
This version has a bold visual style and the fluid tactile response of Material Design. It
makes easier to navigate your device which is based on the shadows and motion.
Android 5.0
Lollipop
Using this version, user can move from phone to tablet. It works on all devices, you
can pick up where you left off with the songs, apps, photos and even recent searches.
Android 6.0 This version is the latest android version, which provides last longer battery life and
Marshmallow new permissions that give you more control.

Advantages of Android
 Android is largely supported by Google allowing you to use various services of Google.
 Android is an open source and runs on mobile devices, tablets etc.
 It is multitasking that means you can run many applications at the same time. For example, you can
browse Facebook while listening the song.
 The Android operating system is available on mobile phones from various manufacturers like
Samsung, Motorola, HTC, Sony Ericsson etc.
 Using Android phone, you can easily check e-mail from Gmail if your Gmail account is integrated
with Google Services.
 User can easily access a variety of settings quickly and easily.

Disadvantages of Android
 Android requires continuous Internet connection if you are using Google services.
 Android shows error & forces to close the large apps/games, which is very annoying.
 It takes large amount of mobile data if a large number of background processes are running.
 It increases the usage of RAM and decreases battery performance when many processes are running
in the background.

Android Application Components


 Application components are the essential part of the Android operating system which is used to build
the Android applications.
 The AndroidManifest.xml file describes each component of the application and how they interact.

Following are the Android Application Components,


1. Activities
2. Services
3. Content Providers
4. Broadcast Receivers
5. Intents

1. Activities

 Activity is also known as Widgets.


 Activity represents a single screen with a user interface.
 It is an individual user interface screen in an Android Application where visual elements called
Views.
 It interacts with the user to do only one thing, such as unlock screen, dial a phone, etc.
 If new activity starts, then previous activity is stopped, but the data is preserved.
 An application consists of multiple activities.
For example, an email application has one activity to display a list of new emails, another activity is
to compose email, reading email and so on.

2. Services

 Services performs the action without user interaction in the background, but does not get initiated
without user invocation.
 It does not require a user interface.
 It is an android application component which runs in a background and has no visual UI.
 It is used to perform the processing part of your application in the background.
For example, music player application. When the music station is playing the song, the user can
open another application and the song plays in the background.

3. Content Providers
 Content providers are the android application component that provide a flexible way to make data
available across applications.
 It manages common data based on permissions.
 It manages the data which is being shared by more than one application.
 Content provider is a critical concept that has led to develop in-house android applications in a better
way.

4. Broadcast Receivers

 Broadcast receivers are used to receive messages which are broadcast by the Android applications.
For example, the warning where the battery is getting low, change of time zone, etc.
 They respond to broadcast messages from other applications.

5. Intent

 Intent is a message which allows components to request activities from other components.

There are two types of Intents,


1. Explicit Intents
2. Implicit Intents

1. Explicit intents are used for application's internal communications.

2. Implicit intent means sending a message to the Android system to find a suitable activity that can be
responded to the intent.

Architecture of Android
Android architecture is a stack of software components. It is in the form of a software application, operating system,
run-time environment, middleware, native libraries and services.

It is categorized into five parts as below:


1. Linux Kernel
2. Native Libraries
3. Android Runtime
4. Application Framework
5. Applications

Each part of the stack and the elements within each layer are integrated and provide optimal application
development and execution environment for mobile devices.

The following diagram shows the architecture of Android,


1. Linux Kernel

 Linux is the heart of Android architecture.


 It provides a level of abstraction between the hardware devices and the upper layers of the Android software
stack.
 The Android operating system is based on the Linux kernel.
 The Linux kernel is responsible for various device drivers such as Camera driver, Display driver, Bluetooth
driver, Keypad driver, Memory management, Process management, Power management, etc.

2. Native Libraries

 The native libraries such as Media, WebKit, SQLite, OpenGL, FreeType, C Runtime library (libc) etc. are
situated on the top of a Linux kernel.
 Media library is responsible for playing and recording audio and video formats, FreeType is for font support,
WebKit is for browser support, SQLite is for database, SSL is for Internet security etc.

3. Android Runtime

 Android Runtime is the third section of the architecture and situated on the second layer from the bottom.
 Android Runtime includes core libraries and Dalvik Virtual Machine (DVM), which is responsible to run
android application.
 Dalvik Virtual Machine (DVM) is like Java Virtual Machine (JVM) in Java, but DVM is optimized for mobile
Devices.
 DVM makes use of the Linux core features like memory management and multi-threading, which are
essential in the Java language.
 DVM provides fast performance and consumes less memory.

4. Application Framework

 Application framework is situated on the top of the Native libraries and Android runtime.
 Android framework provides a lot of classes and interfaces for Android application development and higher
level services to the applications in the form of Java classes.
 It includes Android API's such as Activity manager, Window manager, Content Provider, Telephony Manager,
etc.
 Activity manger is responsible for controlling all the aspects of the application lifecycle and activity stack,
Content provider is responsible for allowing the applications to publish and share the data with the other
applications, View system is responsible for creating application user interfaces, etc.

5. Applications

 Applications are situated on the top of the Application framework.


 The applications such as Home, Contact, Alarm, Calender, Camera, Browsers, etc. use the Android framework
which uses Android runtime and libraries. Android runtime and Native libraries use Linux kernel.
 The user can write his/her application to be installed on this layer only.

Structure of Android Application


Developing an Android project, you have to install the Android plug-ins for Eclipse and at least have some
knowledge of Java programming.
After installing all the plug-ins for an Android file, you can begin to develop an Android application.
Android uses packages not only to arrange the code in an application but also to manage the application themselves.
The above diagram shows the basic building blocks of an Android application. Android application in Eclipse or in any
development tool have a pre-defined structure with code and resource organized into a number of folders.
Every Android project contains several folders, like:

Folder Name Description

src The 'src' stands for Source Code. It contains the Java Source files.

gen The 'gen' stands for Generated Java Library. This library is for Android internal use only.

Android 2.2 The Android Framework Library is stored here.

assets It is used to store raw asset files.

libs It contains private libraries.

The 'res' stands for Resource file. It can store resource files such as pictures, XML files, etc. It
contains some additional folders such as Drawable, Layout and Values.

anim: It is used for XML files that are compiled into animation objects.
color: It is used for XML files that describe colors.
drawable: It is used to store various graphics files. In Android project structure,

there are three types of drawable folders,


1. drawable-mdpi
2. drawable-hdpi
3. drawable-ldpi

The above drawable folders are required in order to adapt to different screen resolutions.
res

layout: It is used for placing the XML layout files, which defines how various Android objects
such as textbox, buttons, etc. are organized on the screen.

menu: It is used for defining the XML files in the application menu.

raw: The 'raw' stands for Raw Asset Files. These files are referenced from the application
using a resource identifier in the R class.
For example, good place for media is MP3 or Ogg files.

values: It is used for XML files which stores various string values, such as titles, labels, etc.

xml: It is used for configuring the application components.

This file indicates the Android definition file. This file contains the information about the
AndroidManifest.xml Android application such as minimum Android version, permission to access Android device
capabilities such as Internet access permission, phone permission etc.

This file contains the project settings, such as build the target. Do not edit this file manually. It
default.properties
should be maintained in a Source Revision Control System.
Proguard.cfg This file defines how ProGuard optimizes and makes your code unclear.

This file describes the layout of the page. So all the components such as textboxes, labels,
MainLayout.xml
radio buttons, etc. are displaying on the application screen.

The application occupies the entire device screen which needs at least one class inherits from
Activity class
the Activity class. OnCreate() method initiates the application and loads the layout page.

Android SQLite Database


What is SQLite?

SQLite is an open source database. It supports standard relational database features like SQL syntax, transactions,
prepared statement, etc. It has methods to create, delete, execute SQL commands and perform other common
database management tasks.

SQLite supports following datatypes:

Datatype Description

TEXT It is similar to String in Java.

INTEGER It is similar to Long in Java.

REAL It is similar to Double in Java.

SQLite in Android
 Android does not require a setup procedure or administration of the database using an SQLite database.
 SQLite database is embedded in every Android device.
 It stores data to a text file on a device and supports all the relational database features.
 To use the SQLite database, the SQLiteOpenHelper class is used which provides various functionality.

SQLite Database Architecture

The android.database.sqlite is the main package in Android SQLite which contains the classes
Package
to manage your own databases.

The openOrCreateDatabase() method is called for creating a database with your database
name and mode as a parameter.
This method returns an instance of SQLite database.
Creation
Syntax
SQLiteDatabse mydatabase = openOrCreateDatabase (“database_name”, MODE_PRIVATE,
null);

The execSQL() method is used to insert the data into table. This method is defined in
Insertion SQLiteDatabse class.
Syntax:
execSQL(String SQL, Object[] bind Args)

The execSQL() method is used not only to insert a data, but also to update or modify the
existing data in database, using bind arguments.

Example:

mydatabase.execSQL(“CREATE TABLE TutorialRide(Admin_name VARCHAR, Password


VARCHAR);”);

mydatabase.execSQL(“INSERT INTO TutorialRide VALUES('ABC', '123');”);

An object of the Cursor class is used to fetch the data from the database. Calling a method of
Cursor class is called rawQuery which returns a resultset with the cursor pointing to the table.
The rawQuery() accepts an SQL SELECT statement as an input.

Example:

Fetching
Cursor resultset = mydatabase.rawQuery(“SELECT * FROM Employee”, null);

resultset.moveToFirst();

String eid = resultset.getString(1);


String ename = resultset.getString(2);

This class is used for creating a database and version management.

In this class, there are two methods which need to override for creating and updating the
database, they are onCreate() and onUpgrade().

If the database is accessed but not yet created then onCreate() method is called by the
SQLiteOpenHelper
framework.
Class

If the database version is increased in your application code then onUpgrade() method is
called. It allows to modify the exisitng database.

The SQLiteOpenHelper class provides the getReadableDatabase() and


getWriteableDatabase() methods to get access to an SQLiteDatabase object.

Gravity
Gravity provides the standard constants and tools for placing an object within a larger container.
The Android RelativeLayout attribute enables you to specify how child views are positioned relative to each other.
The position of each view can be specified as relative to sibling elements or to the parent. Gravity is used to align its
child to a specific position.

What is android:gravity?

 android:gravity is an attribute that sets the gravity of the content of the view its used on.
 The android:gravity specifies how an object should position its content on both X and Y axis.
 The possible values of android:gravity are top, bottom, left, right, center, center_vertical, center_horizontal
etc.
 The android:gravity is used to control gravity of all child views of a container.
 It is the inside gravity of the View.
 It specifies the direction in which its content should align.
 It controls your view placed inside the parent.

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<EditText
android:id="@+id/enterNumberEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter No." >

<requestFocus />
</EditText>
</LinearLayout>

 In the above example, android:gravity aligns the child of LinearLayout in center.


 The android:gravity is for child components.
 It is not a Layout Parameter. It is an attribute of the View Group.

What is android:layout_gravity?
 The android:layout_gravity is an attribute that sets the gravity of the View or Layout in its parent.
 The android:layout_gravity is used to control the gravity of an individual view in a container.
 It is the outside gravity of the View.
 It specifies the direction in which the View should touch it's parent's border.

Example : android:layout_gravity=“center”

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:background="@drawable/dialog_background" >
</LinearLayout>

 In the above example, android:layout_gravity aligns the child of LinearLayout in center.


 The android:layout_gravity is for child parent components.
 It is a Layout Parameter. All View groups do not support this Layout Param.
 The LinearLayout does support android:layout_gravity Layout Param.

LinearLayout
 LinearLayout is a view group that aligns all children in a single direction, vertically, horizontally.
 It is a commonly used view group that lays out its children views either horizontally or vertically.

Example : Demonstrating android:gravity and android:layout_gravity

File Name: content_main.xml

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


<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "com.example.custom.and gravity.MainActivity"
tools:showIn = "@layout/activity_main"
android:orientation = "vertical"
>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button1"
android:id = "@+id/button1"
android:gravity = "top"
android:textSize = "20dp"
android:background = "#FF0000"
/>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button2"
android:id = "@+id/button2"
android:gravity = "bottom"
android:textSize = "20dp"
android:background = "#00FF00"
/>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button3"
android:id = "@+id/button3"
android:textSize = "20dp"
android:layout_gravity = "right"
android:gravity = "top"
android:background = "#FFFF00"
/>
</LinearLayout>
Output:

Android AlertDialog

Dialog is used for modal events which require users to take an action before they can proceed. The Android
AlertDialog is the subclass of Dialog Class. The Dialog class is the base class of AlertDialog class. It is used to display
the dialog message with 'Ok' and 'Cancel' buttons. The AlertDialog class is used for creating Alert notification or alert
dialog box.

Definition of Dialog
“A dialog is a small window that prompts the user to make a decision or enter additional information.”

AlertDialog is composed of three regions:

1. Title defines the title of the AlertDialog.


2. Content area displays message or custom layout.
3. Action button is used to add one, two or three buttons on AlertDialog, but it does not allow more than three.

To build an AlertDialog window you have to instantiate an AlertDialog.Builder with its constructor.
AlertDialog.Builder dialog = new AlertDialog.Builder(this);

AndroidDialog class has following three standard methods to add positive, negative and cancel button.

Methods Description

setNegativeButton(CharSequence text, This method sets a listener and it will be invoked when
DialogInterface.OnClickListener listener) the negative button of the dialog is pressed.

setNeutralButton(CharSequence text, This method sets a listener and it will be invoked when
DialogInterface.OnClickListener listener) the neutral button of the dialog is pressed.

setPositiveButton(CharSequence text, This method sets a listener and it will be invoked when
Dialognterface.OnClickListener listener) the positive button of the dialog is pressed.

Example : AlertDialog

File Name: activity_main.xml

<LinearLayoutxmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical">

<Button
android:id="@+id/threeButtonDialog"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginTop = "50dp"
android:text = "ThreeButtonDialog"
android:textSize = "30dp"/>
</LinearLayout>

File Name: MainActivity.java

public class MainActivity extends Activity implements OnClickListener


{
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
button1 = (Button)findViewById(R.id.threeButtonDialog);
button1.setOnClickListener (this);
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showThreeButtonDialog();
}
public void showThreeButtonDialog()
{
AlertDialog.Builder dialog = newAlertDialog.Builder(this);
dialog.setTitle("Save Confirm");
dialog.setMessage("Are You Sure to save");
dialog.setPositiveButton("OK",newDialogInterface.OnClickListener()
{
@Override
publicvoidonClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You clicked on OK",
Toast.LENGTH_SHORT).show();
}
});
dialog.setNegativeButton("NO", newDialogInterface.OnClickListener()
{
@Override
publicvoidonClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You clicked on NO",
Toast.LENGTH_SHORT).show();
}
});
dialog.setNeutralButton("Cancel", newDialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "You clicked on Cancel button",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog ad = dialog.create();
ad.show();
}
}

Output:
What is ListView?
 ListView is a view group that displays a list of scrollable items.
 ListView is used to show a vertical list of scrollable items, which has data populated using an Adpater.
 The simplest adapter to use in ListView is called an ArrayAdapter.
 The main purpose of an ArrayAdapter is to convert an ArrayList of objects into View items loaded into the
ListView container.

 In the above diagram, The Adapter (which means ArrayAdapter) fits in between an Data source (ArrayList)
and the Adapter View (List View).

The ArrayAdapter configures two aspects:


1. Which array is used as the data source for the list?
2. How to convert any given item in the array into a corresponding View object?

Adapter
 Adapter manages the data model.
 It extends the BaseAdapter class.
 It adopts the data model to the individual entries in the widget.

ListView with ArrayAdapter


 ArrayAdapter class handles a list or array of Java objects as input.
 The user can add new elements with the add() method.
 This class allows to remove all elements in its underlying data structure with the clear() method call.
 ArrayAdapter creates a view for each array item by calling toString() method and place the contents in a
TextView.

Syntax:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,StringArray);

Parameters of the above constructor

this – It is the application content.


R.layout – It is a layout defined in an XML file and have TextView for each string in the array.
StringArray – It is an array of strings, populated in the text view.

ListView Attributes
Attributes Description

android:id It is the ID of layout for identifying uniquely.

android:entries It specifies the reference to an array resource that will populate the ListView.

android:divider It is drawable or color to draw between list items.

android:dividerHeight It specifies the height of the divider.

Its default value id true. If it sets to false, the ListView will not draw the divider
android:footerDividersEnabled
before each footer view.

Its default value is true. If it sets to false, the ListView will not draw the divider after
android:headerDividersEnabled
each header view.

Example : ListView Control with ArrayAdapter

XML file for ListView Control

<ListView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/listView"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true" />

File Name: MainActivity.java

public class MainActivity extends AppCompatActivity


{
ListView lvObj;
String [] city={"Pune","Gwalior","Patna","Nasik","Kashmir",""};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //XML file name activity_main.xml
lvObj = (ListView)findViewById(R.id.listView);
ArrayAdapter<String>arrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,city);
lvObj.setAdapter(arrayAdapter);
lvObj.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick (AdapterView<?> parent, View view, intposition, long id)
{
String item = (String)lvObj.getItemAtPosition(position);
Toast toast = Toast.makeText(getApplicationContext(),"Your selected city
="+item,Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,30,150);
toast.show();
}
});
}
}

Output:

Spinner Control
 Android Spinner allows you to select an item from a drop down menu list. It provides a quick way to select
one value from a set.
 Android Spinner class is the subclass of AsbSpinner class.
 Android Spinner provides an easy way to select value from list.
 It shows its currently selected value with all other available values from which the user can select a new one.
For example:

 In the above example, it displays a dropdown list which indicates the category of phone number. When user
touches the spinner, it displays a dropdown menu with all other available values from which the user can
selects one.
 This class is like the dropdown menu with multiple values from which the end user can select only one value.

 In the above figure, an Adapter works as a bridge between DataSource (Array, ArrayList etc.) and
AdapterView. Some of the important objects of AdapterView are Spinner, ListView and GridView.
 The user can add a spinner to his/her layout with the Spinner object.

For example
<Spinner
android:id=”@+id/planets_spinner”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content” />

 SpinnerAdapter is used to populate the spinner with a list of choices. The user then needs to specify this in
his/her Activity or Fragment source code.
 The Spinner is associated with AdapterView. User needs to use one of the adapter classes with Spinner.

Example

Following example demonstrates Spinner Class demo and displays the dropdown list of days.

File Name: strings.xml

<resources>
<string name = "app_name">SpinnerDemo</string>
<string name = "action_settings">Settings</string>
<string-array name = "Days">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>

</string-array>
</resources>

File Name: content_main.xml

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


<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "com.example.custom.spinnerdemo.MainActivity"
tools:showIn = "@layout/activity_main">

<Spinner
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/spinner"
android:layout_alignParentTop = "true"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true" />
</RelativeLayout>

File Name: MainActivity.java

public class MainActivity extends AppCompatActivity


{
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.Days, android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected (AdapterView parent, View view, intposition, long id)
{
TextView txt = (TextView)view;
Toast toast = Toast.makeText(getApplicationContext(), "Selected day ="+txt.getText(),
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
@Override
public void onNothingSelected (AdapterView parent)
{

}
});
}
}

Output:

Android Toast Message


 Toast message is a simple feedback about an operation in a small group. These messages only fill the amount
of space required for the message.
 Toast messages automatically disappears after a timeout. It can be used to display information for the short
period of time.

For example: In Gmail app, when a mail is saved into draft box, it shows a toast message “Saved to Draft”
this message is called a toast message.

 The android.widget.Toast class is the subclass of Java.lang.Object class.


 The android.widget.Toast class is used to show notification or message for a particular interval of time and
does not block the user interaction.
 The makeText() method is used to create an object of android.widget.Toast class.
The makeText() method takes three parameters:
1. Application Context
2. Text Message
3. Duration for the toast

 The show() method is used to display the toast notification.

Syntax:
Toast toast = Toast.makeText(getApplicationContext, “Toast message”, Toast.LENGTH_SHORT);
toast.show();

 Android toast message is a solution for android developer to notify users about an operation without
expecting any user input.
 It provides a small popup which displays a message for a small period and fades out automatically after
timeout.
 By default, the toast notification appears near the bottom of the screen, but developer can change the
position by using setGravity() method.

The setGravity() method takes three arguments:


I. Gravity constant
II. x-position offset
III. y-position offset

For Example:
Toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);

Example : Creating Toast Message

The following example demonstrates how to create a toast message in a device.

File name: content_main.xml

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


<RelativeLayoutxmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "com.example.itwin.toastdemo.MainActivity"
tools:showIn = "@layout/activity_main">

<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Show Message"
android:textSize = "30dp"
android:id = "@+id/btnShow"
android:layout_marginTop = "72dp"
android:onClick = "showToast" // It will call showTost() method
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true" />
</RelativeLayout>

File name: MainActivity.java

public class MainActivity extends AppCompatActivity


{
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btnShow);
}
public void showToast(View v)
{
Toast toast = Toast.makeText(getApplicationContext(), "Welcome to TutorialRide",
Toast.LENGTH_SHORT);
toast.show();
}
}

Output:

Android Internal Storage


Android provides several storage options to store the data.

Following are the data storage options


1. Shared Preferences
2. Internal Storage
3. External Storage
4. SQLite Database
5. Network Connection

Internal storage helps users to save or read their data from the device Internal memory. The FileInputStream and
FileOutputStream classes are used to read and write data into the file.

A. Write Operation
The openFileOutput() method is called for writing the data in the file using Internal storage. It takes two parameters.
First parameter is the file name and second one is file mode.

Syntax:
FileOutputStreamfopStream = openFileOutput(“file_name”, MODE_PRIVATE);

Example

String str = “TutorialRide”;


fopStream.write(str.getBytes());
fopStream.close();

B. Read Operation
The openFileInput() method is called for reading the data from file with the name of the file. It takes one parameter
as file name. The file name should be same as you have written in the openFileOutput() method. It returns an
instance of FileInputStream class.

Example

int read = -1;


StringBuffersb = newStringBuffer();
FileInputStreamfipStream = openFileInput(“file_name”);
while((read = fibStream.read()) != -1)
{
sb.append((char)read);
}

1. Shared Preference
 The SharedPreferences class is used to store the private primitive data (such as int, float, boolean, long and
string) in key-value pairs.
 This class provides a general framework which allows to save and retrieve persistent key-value pairs of
primitive data types.
 The getSharedPreferences() and getPreferences() methods are used to get a SharedPreferences object for
the application.
 The getSharedPreferences() method is used when user needs multiple preferences file which is identified by
name.
 The getPreferences() method is used when user needs only one preferences file for his/her activity. Because
this will be the only preferences file for Activity which don't supply a name.

2. Internal Storage
 Internal storage is used to store private data on the device memory.
 This storage enables you to read and write data into files that are associated with each application's internal
memory.
 By default, the user can save the files to the internal storage which are private to the application. Neither
other applications nor the user can access these files.
 When the user uninstalls the application, these files are removed from the device memory.
 When users use MODE-PRIVATE for files on the internal storage, they are never accessible to the other
applications.

The other modes are


i) MODE_APPEND
ii) MODE_WORLD_READABLE
iii) MODE_WORLD_WRITEABLE

3. External Storage
 External storage is used to store public data on the shared external storage.
 This storage can be removable storage media such as an SD card or an internal (non-removable) storage.
 The user can read and modify the files if they are stored in the external storage.
 The READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE is used to acquire the system permissions
to read or write the files on the external storage.
 The WRITE_EXTERNAL_STORAGE permission is used when the user needs both read and write files, because
it implicitly requires read access as well.

4. SQLite Database
 SQLite database is used to store the structured data in a private database.
 The database will be accessible by its name to any class in the application, but not outside the application.
 Android provides full support to SQLite databases.
 The SQLiteOpenHelper class is used for creating a database and version management. This class includes two
methods onCreate() and onUpgrade() for creating and updating the database.

5. Network Connection
 Network Connection is used to store the data on the web with your own network server.
 The user can use the network connection when it's available to store and retrieve the data on your own web-
based services.

The following packages are used with the classes for performing the network connection
1. Java.net.*
2. android.net.*

 The Java.net.* package provides the classes for implementing the networking applications.

This package is divided into two sections,


i. Low Level API deals with addresses, sockets and interfaces.
ii. High Level API deals with URIs, URLs and connections.

 The android.net.* package classes provide network access, beyond the normal java.net.* APIs.

Example : Android Internal Storage

Following internal storage example demonstrates, how the user's data is stored into an Android internal
memory.

Write Operation

File name: activity_main.xml

<RelativeLayoutxmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
tools:context = ".MainActivity">

<Button
android:id = "@+id/btnNext"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/btnSave"
android:layout_marginLeft = "35dp"
android:layout_toRightOf = "@+id/btnSave"
android:text = "Next Activity"
android:onClick = "next"
/>

<TextView
android:id = "@+id/textView2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/textView1"
android:layout_below = "@+id/txtUserName"
android:layout_marginTop = "70dp"
android:text = "Password"
android:textSize = "15dp"
/>

<EditText
android:id = "@+id/txtPassword"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/textView2"
android:layout_toRightOf = "@+id/textView1"
android:ems = "10"
android:inputType = "textPassword">

</EditText>

<Button
android:id = "@+id/btnSave"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@+id/textView2"
android:layout_marginTop = "96dp"
android:layout_toLeftOf = "@+id/editText1"
android:text = "Save"
android:onClick = "save"
/>

<TextView
android:id = "@+id/textView1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/btnSave"
android:layout_alignParentTop = "true"
android:layout_marginTop = "30dp"
android:text = "UserName"
android:textSize = "15dp"/>

<EditText
android:id="@+id/txtUserName"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/textView1"
android:layout_alignLeft = "@+id/txtPassword"
android:ems = "10"/>
<requestFocus/>
</RelativeLayout>

File name: MainActivity.java

public class MainActivity extends Activity


{
EditTextname,password;
FileOutputStreamfopStream;
File file = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//XML file name activity_main.xml
name = (EditText)findViewById(R.id.txtUserName);
password = (EditText)findViewById(R.id.txtPassword);
}
public void save(View v)
{
String txt1 = name.getText().toString();
String txt2 = password.getText().toString();
txt1 = txt1+" ";
try
{
file = getFilesDir();
fopStream = openFileOutput ("data.txt",Context.MODE_PRIVATE);
fopStream.write(txt1.getBytes ());
fopStream.write(txt2.getBytes ());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fopStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), "Data Stored Successfully at location "+file,
Toast.LENGTH_LONG).show();
}
public void next(View v)
{
Toast.makeText(getApplicationContext(), "Next Activity called", Toast.LENGTH_LONG).show();
Intent intent = newIntent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
}

Output:
Android Event Handling
What are events in android?

Events are the messages or notifications, which are generated by controls such as buttons, checkbox, radio buttons
etc. System responds to those messages or notifications by executing some code.

Following are the three concepts related to Android Event Management,

1. Event Listener contains a single callback method. It is an interface in the View class.
2. Event Handler is the method that handles the event. The Event Listener calls the Event Handlers.
3. Event Listener Registration is a process, where an Event Handler gets registered with an Event Listener. Event
Handler is called when the Event Listener fires the event.

Following are the Event Handlers and Event Listeners that handle the user's interaction with interactive
components of Application

Event Handler Event Listener Description

Called when the user either clicks or touches any


onClick() OnClickListener()
widget like button, images, text etc.
Called when the user either clicks or touches any
onLongClick() OnLongClickListener() widget like button, text, image etc. for one or more
seconds.

Called when the widget looses its focus that means


onFocusChange() OnFocusChangeListener()
the user goes away from the view point.

Called when the user is focused on the item and


onKey() OnFocusChangeListener()
presses or releases a key on the device.

onTouch() OnTouchListener() Called when the user presses or releases the key.

onMenuItemClick() OnMenuItemClickListener() Called when the user selects a menu item.

OnCreateContextMenu() OnCreateContextMenuITemListener() Called when the context menu is being built.

What Does Dalvik Debug Monitor Service (DDMS) Mean?


The Dalvik Debug Monitor Service (DDMS) is a debugging tool used in the Android platform. The Dalvik
Debug Monitor Service is downloaded as part of the Android SDK. Some of the services provided by the
DDMS are port forwarding, on-device screen capture, on-device thread and heap monitoring, and radio state
information.

The Dalvik Debug Monitor Service allows developers to spot bugs in applications running on either an
emulator or an actual Android device.

For example, by using the DDMS’ LogCat feature, developers can view log messages regarding the state of
the application and the device. LogCat can pinpoint the exact line number on which an error occurred.

Another DDMS feature, known as the Emulator Control, allows developers to simulate phone states and
activities. For example, it can simulate different types of networks such as GPRS, EDGE, and UTMS, which
can have different network characteristics such as speed and latency.

Aside from the features mentioned earlier, the Dalvik Debug Monitor Service also provides LogCat, process,
and radio state information as well as incoming call, SMS, and location data spoofing.

This debugging tool can be integrated into the Eclipse IDE by adding the ADT (Android Development
Tools) plug-in. Otherwise, it can be accessed from the command line and will automatically connect to any
running emulator.

Screen Orientations in Android with Examples


Screen Orientation, also known as screen rotation, is the attribute of activity element in android. When screen
orientation change from one state to other, it is also known as configuration change.
States of Screen orientation

There are various possible screen orientation states for any android application, such as:

ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED

ActivityInfo.SCREEN_ORIENTATION_USER

ActivityInfo.SCREEN_ORIENTATION_SENSOR

ActivityInfo.SCREEN_ORIENTATION_BEHIND

ActivityInfo.SCREEN_ORIENTATION_NOSENSOR

ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE

ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT

ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT

R.Java
Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory. The id for the created component is
automatically generated in the R.java whenever a component is created in the android
activity_main.xml file. The created ID can later be used in the Java Source file. To act on a
component, the corresponding id can be used in the activity source file. The android creates
the R.jar file automatically in case the R.jar file is deleted. The android R.java file contains
many static nested classes such as menu, id, layout, attr, drawable, string, etc. Now we will
see the code of the android R.java file.

Dalvik Virtual Machine (DVM)

The modern JVM is high performance and provides excellent memory management. But it
needs to be optimized for low-powered handheld devices as well. The Dalvik Virtual
Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the
virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Java Compiler(javac) converts the Java Source Code into Java Byte-Code(.class). Then DEX
Compiler converts this (.class) file into in Dalvik Byte Code i.e. “.dex” file.
What are the advantages of Android?

Open-source: It means no license, distribution and development fee.

Platform-independent: It supports Windows, Mac, and Linux platforms.

Supports various technologies: It supports camera, Bluetooth, wifi, speech, EDGE etc. technologies.

Highly optimized Virtual Machine: Android uses a highly optimized virtual machine for mobile devices,
called DVM (Dalvik Virtual Machine).

There are two lightweight techniques for saving simple application data for
Android applications: Shared Preferences and a set of event handlers used for
saving Activity instance state. Both mechanisms use an NVP mechanism to store
simple primitive values. Both techniques support primitive types Boolean, string,
fl oat, long, and integer, making them ideal means of quickly storing default
values, class instance variables, the current UI state, and user preferences.

What is Android Style?


Android-style is a set of all attributes that are applied to view elements. The following are some of the
common characteristics that are used to style an element.

 Font
 Background
 Margin
 Padding
 Text Size
 Text Style

To create a style for some specific UI element, you can follow the below steps:

1: First, go to your Project Structure—select res and then select values. Now here, you need to open the
themes.xml. (res—->values—–>themes.xml)

2: The root tag of the XML file is <resources>. In this, you need to create a <style> tag.

3: Now, you need to keep a name attribute to the style tag. It helps you in identifying the style uniquely.

4: Now, you just need to use the <item> tag to define each attribute. You should keep a value that is
acceptable by that specific attribute.

For example
<resources>
<style name=”MyTextViewStyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#960959</item>
<item name="android:textSize">40sp</item>
<item name="android:textStyle">italic</item>
<item name="android:textAllCaps">true</item>
</style>
</resources>

How to use Android Style?


The style you defined in your styles.xml file can be used by the elements present in your layout XML file.
For this, you need to open your layout XML file and then use the style attribute to call your defined style.
After doing so, your element will follow that style.

Below is an implementation of the same.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/techVidvanTitle”
style="@style/MyTextViewStyle"
android:text="Tech Vidvan"/>
</LinearLayout>

Simple Values
Supported simple values include strings, colors, dimensions, styles, and string or integer arrays. All simple values are
stored within XML fi les in the res/values folder. Within each XML fi le, you indicate the type of value being stored
using tags.

The Cursor class includes a number of navigation functions, including, but not limited to, the
following:

moveToFirst — Moves the cursor to the fi rst row in the query result
moveToNext — Moves the cursor to the next row
moveToPrevious — Moves the cursor to the previous row
getCount — Returns the number of rows in the result set
getColumnIndexOrThrow — Returns the zero-based index for the column with the specified
name (throwing an exception if no column exists with that name)
getColumnName — Returns the name of the specifi ed column index
getColumnNames — Returns a string array of all the column names in the current Cursor
moveToPosition — Moves the cursor to the specifi ed row
getPosition — Returns the current cursor position

Action bar
ActionBar is the element present at the top of the activity screen. It is a salient feature of a
mobile application that has a consistent presence over all its activities. This This pre-included
ActionBar display title for the current activity that is managed by the AncdroidManifest.xml
fileActionBar display title for the current activity that is managed by the
AncdroidManifest.xml file

Android SDK
(Software Development Kit) is a set of development tools which is required when building any android
application.

Android SDK consists of several components within it such as −

 SDK Platforms.
 SDK Tools.
 SDK Update Sites.
 Android Emulator.

In this article, we will take a look at What is Android SDK and what are the different components which are
present in the Android SDK.

Android SDK
It is a collection of software development tools and libraries which are required for building any android
application in any IDE whether it may be android studio, eclipse or any other. When Google releases any
new features in a specific android version or releases a new version for android then they also release a new
SDK version for it which consist of that updated features within it. These SDK tools are essential for
developing any android application. Android SDK can be installed in any system whether it may be
windows, Mac OS or Linux.

Components of Android SDK


SDK Platform

Whenever a newer version of android is released such as Android 9,10 or it may be also called as Android
Oreo, Android Marshmallow or others. New SDK platform tools are also available to download in SDK
Platform tools. Each SDK platform tools package consists of android platform and sources pertaining to an
API level by default. The latest package of SDK Platform tools comes with the latest updates related to
android such as Android Tiramisu comes with updated clipboard manager and we can also get to see other
updated features in the latest SDK Platform tools.

SDK Tools

SDK tools is a package of many essential tools which are required for development of any android
application. SDK tools consist of several different components such as Android SDK Build
Tools,NDK,Android SDK Command Line Tools, CMake and other. When any new update is released by
google for the updates of these tools. These tools are updated automatically to get the latest one.
SDK Update Sites

SDK Update Sites consist of collections of different websites which are required for installation for different
SDK components inside your android SDK. This update sites section consists of website links for different
google websites which provides installation details for different SDK components in Android SDK.

Android Emulator

Android Emulator is a virtual android mobile device which is provided by android studio IDE. We can use
this virtual device to run our android studio applications on it. We can generate so many types of different
emulators depending on our requirements which might have different android versions. With the help of an
android emulator we can test our android application on a wide range of devices. With the help of emulators
we can create applications for mobile devices, watches, tablets as well as smart televisions without the
requirements of the actual device.

Android.bluetooth
The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:

 BluetoothAdapter
 BluetoothDevice etc

Bluetooth is a way to send or receive data between two different devices. Android platform includes support
for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.

 Scan for other Bluetooth devices


 Get a list of paired devices
 Connect to other devices through service discovery

LogCat Window
 It is the place where various messages can be printed when an application runs. Suppose, you are
running your application and the program crashes, unfortunately. Then, Logcat Window is going to
help you to debug the output by collecting and viewing all the messages that your emulator throws.
So, this is a very useful component for the app development because this Logcat dumps a lot of system
messages and these messages are actually thrown by the emulator.
 This means, that when you run your app in your emulator, then you will see a lot of messages which
include all the information, all the verbose messages, and all the errors that you are getting in your
application. Suppose, an application of about 10000 lines of code gets an error. So, in that 10000 line
codes, to detect the error Logcat helps by displaying the error messages.

You might also like