ANDROID

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

S.S.S.D.I.I.T – College Android & I Phone B.C.

Mobile Computing
Using

Android and I phone

S.S.S.D.I.I.T College
Junagadh
ANDROID & IPHONE topics:

Intro, Application design, interface design, Database Connectivity, location based service, notification, service
deployment, intro IPHONE.

Developed By:

Ripal Pandya
9427696988

youtube.com/avadhtutor

pandyaripal.blogspot.com

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 1


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Introduction to Android
History of Android
Android founded in palo alto, california, united state in october 2003. By Andy Rubin(Co-
Founder of danger), rich miner(Co- Founder of wildfire communication), nick sears (once VP
at T-Mobile) and Chris white(Headed design and interface development at web TV) to
develop Android.

What is ANDROID:
- It is a open source software platform and operating System for Mobile Device.
- Android is based on Linux kernel.
- Developed by Google and later the Open Handset Alliance(OHA).
- Allow writing manage Code in the Java Language.
- Android has its own machine. i.e: DVM(Dalvik Virtual Machine), which is used for
executing the android application.
- Google purchased the initial developer of the software, android incorporated in
2005.

Features of android:
- Background Wi-Fi location still runs even when Wi-Fi is turned off
- Developer logging and analyzing enhancements
- It is optimized for mobile devices.
- It enables reuse and replacement of components.
- Java support ,media support, multi touch, video calling,multi tasking ,voice based features,
screen capture, camera ,bluetooth,gps,compass and accelerometer,3G

Advantages of Android:
- The ability for anyone to customize the Google Android platform
- It gives you better notification.
- It lets you choose your hardware.
- It has better app market(1,80,000 application)
- A more mature platform
- With the support of many applications, the user can change the screen display.
- With Google chrome you can open many window at once.
- Supports all Google services: Android operating system supports all of Google services
ranging from Gmail to Google reader. all Google services can you have with one operating
system, namely Android.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 2


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Dis- advantages of android:


- Android Market is less control of the manager, sometimes there are malware.
- Wasteful Batteries, This is because the OS is a lot of "process" in the background causing the
battery quickly drains.
- Sometimes slow device company issued an official version of Android your own .
- Extremely inconsistence in design among apps.
- Very unstable and often hang or crash.

Limitation of android:
- Development requirements in
- Java
- Android SDK
- Eclipse IDE (optional)
- Bluetooth limitations:-
- Android doesn't support:
- Bluetooth stereo
- Contacts exchange
- Modem pairing
- Wireless keyboards
- Firefox mobile isn't coming to android because of android limitations
- Apps in Android Market need to be programmed with a custom form of Java
- → Mozilla and the Fennec won't have that
- There are no split or interval times available.
- Small memory size.
- Continuous Internet connection is required

Android Platform Differences:


- Complete
o The designers took a comprehensive approach when they developed the
Android platform.
- Free:
o Android applications are free to develop.
o There are no licensing to develop on the platform.
o No requirement of membership fees.
o No requirement of testing fees.
o No requirement of signing or certification fees.
o Android applications can be distributed and commercialized in a variety of
ways.
- Each Android SDK has had a project name.
- In Android’s case, the SDKs are named alphabetically after sweets.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 3


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- The latest version of Android is code named Jelly Bean and kitkat.
- Android is open Source.

Android Version History:


- Android 1.0:
o Released on September 23, 2008. Codename "Astro"
- Android 1.1:
o Released on February 9, 2009. Codename "Bender"
- Android 1.5:
o Released on April 30, 2009. Codename “Cupcake”
- Android 1.6:
o Released on September 15, 2009. Codename “Donut”
- Android 2.0/ 2.1:
o Released on October 26, 2009. Codename “Eclair”
- Android 2.2:
o Released on May 20, 2010. Codename “Froyo”
- Android 2.3:
o Released on December 6, 2010. Codename “Gingerbread”
- Android 3:
o Released on February 22, 2011. Codename “Honeycomb”
- Android 4.0:
o Released on November 14, 2011. Codename “Ice Cream Sandwich”
- Android 4.1:
o Released on June 27, 2012. Codename “Jelly Bean”
- Android 4.4:
o Released on october 2013. Code name KITKAT

- Android 5.0 Lollipop (API 21) ...


- Android 6.0 Marshmallow (API 23)
- Android 7.0 Nougat (API 24) ...
- Android 8.0 Oreo (API 26) 2.15.1 Android 8.1 Oreo (API 27)

Open Handset Allience:


- The open handset allience (OHA) is a business allience of firm to develop open standard for
mobile devices.
- Devoted to advancing open standards for mobile devices.
- Developed technologies that will significantly lower the cost of developing and distributing
mobile devices and services.
- Open handset Allience included several companies:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 4


S.S.S.D.I.I.T – College Android & I Phone B.C.A

o Samsung, motorola, vodafone, htc, LG, Dell, asus, acer, docomo, nec, sharp, sony
ericsion, toshiba, ebay, google, intel, ARM, sprint etc…

Android Architecture:
The software stack is split into four layer:

- Application layer
- Application framework.
- The libraries and run time.
- The kernel.

Linux kernel:

- The architecture based on LINUX Kernel.


- This layer is core of android Architecture.
- It provides service like power management, Memory Management, Security etc.
- It helps in software or hardware binding for better communication.

Native Libraries:

- Android has its own libraries, its written in C/C++

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 5


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- these library can’t access directly. With the help of application framework, we can access
this library.
- Android Runtime:
o android runtime designed specifically for android to meet the needs for running in
an embedded environment where you have limited battery, limited memory, limited
CPU.
o Davik is the process virtual machine in google’s android operating system. It is
software that runs the apps on android devices.
o Program are commonly written in java and compiled to byte Code.
o The core libarary contains all of the collection classes, utilities, IO, all the utilities and
tools that your come to expected to use.

Application Framework:

- This is all written in java programming language and the application framework is the toolkit
that all application use.
- These application include the once that come with a phone like home application, or the
phone application.
- It includes application written by google and it include apps that will be written you.

These are as follows:-

- Activity manager:-It manages the lifecycle of applications. It enable proper management of


all the activities. All the activities are controlled by activity manager.
- Resource manager:-It provides access to non-code resources such as graphics etc.
- Notification manager:-It enables all applications to display custom alerts in status bar.
- Location manager:- It fires alerts when user enters or leaves a specified geographical
location.
- Package manager:-It is use to retrieve the data about installed packages on device.
- Window manager:-It is use to create views and layouts.
- Telephony manager:-It is use to handle settings of network connection and all information
about services on device.

Application Layer:

- the final layer on top is Applications.


- It includes the home application the contacts application , the browser, and apps.
- It is the most upper layer in android architecture.
- All the applications like camera, Google maps, browser,sms,calendars,contacts are native
applications. These applications works with end user with the help of application framework
to operate.

Android SDK ( Configure and Setting up Android Development Environment)


- Configure your Development Environment:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 6


S.S.S.D.I.I.T – College Android & I Phone B.C.A

To Develop android application, you need to have the following software installation on your
computer:

o Java development Kit(JDK): android is work with Java so install JDK 5 or 6 version
download on http://java.sun.com/javase/download/index.jsp
o Java IDE such as eclipse: eclipse is a tool to developed a application.
o Android SDK (Software Development Kit): tools and Document available on
http://developer.android.com/sdk/
o Android Development tools(ADT):that’s provide plugin for eclipse. Cnfigure and run
android environment using ADT this is available on http://developer.android.com
- Upgrade Android SDK:
o Android SDK upgrade time to time. You can easily upgrade the android SDK and
tools from within eclipse using the android SDK and AVD manager.
- Exploring the Android SDK:
o Understanding the licence agreement.
 Right granted
 SDK usage
 SDK changes and backward compatibility
 Android developer rights, application privacy, Google APIs.

Android Application Design


Anatomy of an android application:

- Android Terminology
- Application Context, Activities,Services, intents
- Receving and Broadcasting Intents.

Android terminology:
- Context: The context is the central command center for an Android application. All
application-specific functionality can be accessed through the context.
- Activity: An Android application is a collection of tasks, each of which is called an Activity.
Each Activity within an application has a unique task or purpose.
- Intent:The Android operating system uses an asynchronous messaging mechanism to match
task requests with the appropriate Activity. Each request is packaged as an Intent.You can
think of each such request as a message stating an intent to do something.
- Service: Tasks that do not require user interaction can be encapsulated in a service.A service
is most useful when the operations are lengthy (offloading time-consuming processing) or
need to be done regularly (such as checking a server for new mail).

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 7


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Context:

- is context of current state of the application/object


- .Its an entity that represents various environment data . Context helps the current activity
to interact with out side android environment like local files, databases, class loaders
associated to the environment, services including system-level services, and more.
- A Context is a handle to the system . It provides services like resolving resources,
obtaining access to databases and preferences, and so on. An android app has activities.
It’s like a handle to the environment your application is currently running in. The activity
object inherits the Context object.
- Different method of Context:

o getApplicationContext(),
o getContext(),
o getBaseContext()
o or this (when in the activity class).
- Example of Context:
o Creating New objects: Creating new views, adapters, listeners
 TextView tv = new TextView(getContext());
 ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),
...);

o Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE,


SharedPreferences:
 context.getSystemService(LAYOUT_INFLATER_SERVICE)

 getApplicationContext().getSharedPreferences(*name*, *mode*);

o Accessing Components Implicitly: Regarding content providers, broadcasts, intent


 getApplicationContext().getContentResolver().query(uri, ...);
Difference between Activity Context and Application Context:

They are both instances of Context, but the application instance is tied to the lifecycle of the
application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to
different information about the application environment.

If you read the docs at getApplicationContext it notes that you should only use this if you need a
context whose lifecycle is separate from the current context.

Activity:

- An activity represents a single screen with a user interface.


- Activity Lifecycle is below:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 8


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Callback Description

onCreate() This is the first callback and called when the activity is first created.

onStart() This callback is called when the activity becomes visible to the user.

onResume() This is called when the user starts interacting with the application.

The paused activity does not receive user input and cannot execute any code and called when
onPause()
the current activity is being paused and the previous activity is being resumed.

onStop() This callback is called when the activity is no longer visible.

onDestroy() This callback is called before the activity is destroyed by the system.

onRestart() This callback is called when the activity restarts after stopping it.

Service:

A service is a component that runs in the background to perform long-running operations without needing to
interact with the user.

A service can essentially take two states:

State Description

A service is started when an application component, such as an activity, starts it by


Started calling startService(). Once started, a service can run in the background indefinitely,
even if the component that started it is destroyed.

A service is bound when an application component binds to it by


callingbindService(). A bound service offers a client-server interface that allows
Bound
components to interact with the service, send requests, get results, and even do so
across processes with interprocess communication (IPC).
Android Service Lifecycle:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 9


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Method of Service:
Callback Description

The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement this
onStartCommand()
method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide
onBind() an interface that clients use to communicate with the service, by returning
anIBinder object. You must always implement this method, but if you don't want to
allow binding, then you should return null.

The system calls this method when all clients have disconnected from a particular
onUnbind()
interface published by the service.

The system calls this method when new clients have connected to the service,
onRebind() after it had previously been notified that all had disconnected in
itsonUnbind(Intent).

The system calls this method when the service is first created
onCreate() usingonStartCommand() or onBind(). This call is required to perform one-time
setup.

The system calls this method when the service is no longer used and is being
onDestroy()
destroyed. Your service should implement this to clean up any resources such as

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 10


S.S.S.D.I.I.T – College Android & I Phone B.C.A

threads, registered listeners, receivers, etc.

Intent:

- An Android Intent is an object carrying an intent


- The intent itself, an Intent object, is a passive data structure holding an abstract description of an
operation to be performed.
- There are separate mechanisms for delivering intents to each type of component - activities, services,
and broadcast receivers.
- Methods of Intent:

S.N. Method & Description

Context.startActivity()
1 The Intent object is passed to this method to launch a new activity or get an existing activity to
do something new.

Context.startService()
2 The Intent object is passed to this method to initiate a service or deliver new instructions to an
ongoing service.

Context.sendBroadcast()
3 The Intent object is passed to this method to deliver the message to all interested broadcast
receivers.
- Intent Object:
o Action:
 This is mandatory part of the Intent object and is a string naming the action to be
performed.
 The action in an Intent object can be set by the setAction() method and read by
getAction().
o Data:
 The URI of the data to be acted on and the MIME type of that data.
 The setData() method specifies data only as a URI, setType() specifies it only as a
MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The
URI is read by getData() and the type by getType().
- Types of intent:
o Explicit Intents:
 These intents designate the target component by its name and they are typically used
for application-internal messages - such as an activity starting a subordinate service
or launching a sister activity.
 For example:

Intent i = new Intent(this, TargetActivity.class);


i.putExtra("Key1", "ABC");
i.putExtra("Key2", "123");

// Starts TargetActivity
startActivity(i);
o Implecit Intents:
 These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For
example:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 11


S.S.S.D.I.I.T – College Android & I Phone B.C.A

// Implicit Intent by specifying a URI


Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
// Starts Implicit Activity
startActivity(i);

Receiving and Broad cast intents:


- Broadcast Receivers simply respond to broadcast messages from other applications or from the system
itself. These messages are sometime called events or intents.

- There are following two important steps to make BroadcastReceiver works for the systen broadcasted
intents:

o Creating the Broadcast Receiver.

o Registering Broadcast Receiver

- Creating the Broadcast Receiver


A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.
o Example:

public class MyReceiver extends BroadcastReceiver {


@Override

public void onReceive(Context context, Intent intent) {

Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();

} }

- Registering BroadCast Receiver:

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 12


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Event Constant Description

Sticky broadcast containing the charging state, level, and


android.intent.action.BATTERY_CHANGED
other information about the battery.

android.intent.action.BATTERY_LOW Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low.

This is broadcast once, after the system has finished


android.intent.action.BOOT_COMPLETED
booting.

android.intent.action.BUG_REPORT Show activity for reporting a bug.

android.intent.action.CALL Perform a call to someone specified by the data.

The user pressed the "call" button to go to the dialer or


android.intent.action.CALL_BUTTON
other appropriate UI for placing a call.

android.intent.action.DATE_CHANGED The date has changed.

android.intent.action.REBOOT Have the device reboot.

Android Manifest File and Common Setting:


What is manifest file:

- Every Android project includes a special file called the Android manifest file.
- The Android system uses this file to determine application configuration settings, which
includes Application’ identity like its name and version.
- Also includes permissions the application requires to run.

- named AndroidManifest.xml, is an XML file that must be included at the top level of any
Android project.

- Android system uses the information in this file to do the following task:

o Install and upgrade the application package


o Display application details to users (name, icon etc.)
o Launch application activities
o Manage Application permissions
o Also other configurations, by acting as service provider or content provider.
- Two way to Edit Android Manifest File:
o Manually Editing the AndroidManifest.XML file.
o Eclipse manifest file resource editor (a feature of the Android ADT plug-in
for Eclipse)

Manualy Editing Manifest File:

Android manifest file is a specially formatted XML file. Generally manifest file
include single <manifest> tag with a single <application> tag.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 13


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- AndroidManifest.xml

Understand Code in Manifest File Step By step:

- This file tells us that application uses the package name com.androidbook.multimedia.
- Application version name is 1.0.
- Application version code is 1.
- Application name are stored in resource string called @string/app_name within the
/res/values/strings.xml resource file.
- The application is debuggable on an Android device. Means it will debugged when it is
running on device.
- The application icon is the graphic file called icon stored within the /res/drawable directory.
- The application has five activities MultimediaMenuActivity, AudioActivity, VideoPlayActivity
etc.
- The application requires following permission to run :-
o Ability to record audio.
o Ability to set wall paper on the device.
o Ability to access the built in camera

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 14


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Managing Application resources in AndroidManifest File:


- Package name: The package name must be defined within the Android manifest file within
the <manifest> tag using package attributes.
o Example:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidbook.multimedia"
android:versionCode="1"
android:versionName="1.0">
- Versioning Your Application:
o There are two different version attributes defined within the <manifest> tag :-
version name and version code
o The version name (anroid:versionName) is a user friendly, developer defined version
attributes.
o The Android operating system uses the version code (android:versionCode) that is a
numeric attribute to manage application upgrades.
- Setting Application Name and Icon:
o Overall application settings are configured with the <application> tag of the Android
Manifest file.
o Set Application Name And Icon Using Following Example:
 <application android:icon=“@drawable/icon”
android:label=“@string/app_name”>
- The Android SDK versions supported by the application
- The Android platform features used by the application
- The Android hardware configurations required by the application
- The screen size and pixel densities supported by application
- Any external libraries that the application links

Intent Filter on manifest File And Permission:

- Intent Filter:
o Set Entry Point Activity for your Application Using a Intent Filter …
o An Activity class can be specify as primary entry point for application using <intent-
filter> tag specify with MAIN as action type and LAUNCHER as category.
<activity android:name=“.AudioActivity”>
<intent-filter> <action android:name=“android.intent.action.MAIN”/>
<category android:name=“android.intent.category.LAUNCHER” />
<intent-filter> </activity>
- Permission:
o Android applications have no permissions by default
o Permission can be set using <uses-permission> tag inside Android Manifest file
o Example:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 15


S.S.S.D.I.I.T – College Android & I Phone B.C.A

 Access Buit in Camera:


<uses-permission android:name=“android.permission.CAMERA” />
 Allow External Device to SD Card:
<uses-permission
android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />

Different Types of Android Manifest Resources:


- Types of Manifest File Resources:
o Manifest
o Application
o Permissions
o Instrumentation
o AndroidManifest.xml

Android Resources:
What is Android Resource:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 16


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- All Android Applications are composed of two things


o Functionality (Code Instructions to perform task)
o Data (One Type of Resources used in application)
- Resources includes strings, images, and icons, audio files, video and other data used by the
application.
- Resources are external files (that is, non – code files) that are used by your code into your
application.

Storing Application Resources:

- Android resource files are stored separately from the java class files in the Android
project.

 Most Common resource types like strings, colors


are stored in XML Files.
 You can also store raw data files such as audio or
video and graphics files such as .png, .jpg as
resources.

Android Resource Directory Hierarchy:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 17


S.S.S.D.I.I.T – College Android & I Phone B.C.A

 All Resources must be stored under the


/res in specially named subdirectories
that must be lowercase.

 Different resource types are stored in


different directories.

 Default resource sub – directories are


generated when you create an Android
Project.

 /res/drawable-*/ contains all graphics


resources.

 /res/layout/ contains all user interface


resources.

 /res/values/ contains all simple data such


as strings, color values, integer, boolean
etc.

Types of Resource in Android:


- many different types of resources – such as strings, graphics, and color schemes – for user
interface design.
- These resources are stored in /res directory under specific XML files.
- All resources filenames must be contains lowercase letters. (which is combination of letters,
numbers and underscores only)

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 18


S.S.S.D.I.I.T – College Android & I Phone B.C.A

How Resource Types Stored in Android Project Resource Directories

Resource Type Required Directory Filename XML Tag

Strings /res/values/ strings.xml (Suggested) <string>

Array of Strings /res/values/ strings.xml (Suggested) <string-array>, <item>

Booleans /res/values/ bools.xml (Suggested) <bool>

Colors /res/values/ colors.xml (Suggested) <color>

Integers /res/values/ integers.xml (Suggested) <integer>

Array of Integers /res/values/ integers.xml (Suggested) <integer-array><item>

Graphics /res/drawable Icon.png, logo.jpg --------

Resource Type Required Directory Filename XML Tag

<set>,<alpha>, <scale>,
fadsequence.xml
Tweened Animations /res/anim/
pinsequence.xml
<translate> <rotate>

Frame by Frame
/res/drawable/ sequence1.xml sequence2.xml <animation-list><item>
Animations

Menus /res/menu/ mainmenu.xml <menu>

sunrahahai.mp3
Raw Files /res/raw/ -----------
Tumhiho.mp3

Layouts /res/layouts/ main.xml help.xml User Interface Control Tag

Styles and Themes /res/values/ styles.xml themes.xml <style>

Storing Different Resource Value Types

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 19


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- The aapt traverses all properly formatted files in the /res directory hierarchy and generates
the class file R.java in the android project /gen directory.

Storing Simple Resource Types such as String, Color

- simple resource value types, such as strings, colors, dimensions, and other primitives are
stored under the /res/values/ directory in XML files.
- To store string and color types value you have to use <resources> tag, and under that you
can use <string> and <color> tag to specify string and color resources respectively.

Android User Interface Design


User Interface Screen Elements
TextView: A TextView displays text to the user and optionally allows them to edit it. A TextView
is a complete text editor, however the basic class is configured to not allow editing.

Property:

Android:id: This is the ID which uniquely identifies the control.

Android:capitalize: If set, specifies that this TextView has a textual input method and should
automatically capitalize what the user types.

o Don't automatically capitalize anything – 0


o Capitalize the first word of each sentence – 1
o Capitalize the first letter of every word – 2
o Capitalize every character - 3

Android:inputType: The type of data being placed in a text field. Phone, Date, Time, Number, Password etc.

Android:Text: Text to display.

Android:textColor: Text color. May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb"

Android:textSize: Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example:
15sp).

Android:textStyle: Style (bold, italic, bolditalic) for the text. You can use or more of the following values
separated by '|'.

- normal – 0, bold – 1, italic - 2

Example:

Activity_main.xml

<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:capitalize="characters"
android:text="@string/hello_world" />

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 20


S.S.S.D.I.I.T – College Android & I Phone B.C.A

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//--- text view---
TextView txtView = (TextView) findViewById(R.id.text_id);
final String Label = txtView.getText().toString();
txtView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"You have clicked the Label : " + Label,
Toast.LENGTH_LONG).show();
}

});
}

Edittext: A EditText is an overlay over TextView that configures itself to be editable. It


is the predefined subclass of TextView that includes rich editing capabilities.

Property:

Android:autotext: If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

Android:text: This is the Text to display.

Android:background: This is a drawable to use as the background.

android:visibility: This controls the initial visibility of the view.

Example:
Activity_main.xml

<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="EditText" android:inputType="text" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="Click Me" />

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {


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

final EditText eText;


final Button btn;

eText = (EditText) findViewById(R.id.edittext);


btn = (Button) findViewById(R.id.button);

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 21


S.S.S.D.I.I.T – College Android & I Phone B.C.A

btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,
Toast.LENGTH_LONG);
msg.show();
msg.show();
}
});
}

Button: A Button is a Push-button which can be pressed, or clicked, by the user to


perform an action.

Property:

android:autoText: If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.

android:text: This is the Text to display.

android:id: This supplies an identifier name for this view,

android:onClick: This is the name of the method in this View's context to invoke when the view is clicked.

Example:
Activity_main.xml

<EditText <EditText
android:id="@+id/edittext" android:id="@+id/edittext"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1" android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/textView1" android:layout_below="@+id/textView1"
android:layout_marginTop="61dp" android:layout_marginTop="61dp"
android:ems="10" android:ems="10"
android:inputType="text" android:inputType="text"
android:text="@string/enter_text1" /> android:text="@string/enter_text1" />

<EditText
android:id="@+id/edittext3" <Button
android:layout_width="fill_parent" android:id="@+id/button1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignLeft="@+id/edittext" android:layout_height="wrap_content"
android:layout_below="@+id/edittext2" android:layout_alignLeft="@+id/textView1"
android:layout_marginTop="14dp" android:layout_below="@+id/edittext3"
android:ems="10" android:layout_marginTop="35dp"
android:inputType="text" android:text="@string/click_button" />
android:text="@string/enter_text3" />

MainActivity.java

public class MainActivity extends Activity {

private EditText edText1,edText2,edText3;


private Button btnProduct;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}

private void addListenerOnButton() {

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 22


S.S.S.D.I.I.T – College Android & I Phone B.C.A

edText1 = (EditText)findViewById(R.id.edittext);
edText2 = (EditText)findViewById(R.id.edittext2);
edText3 = (EditText)findViewById(R.id.edittext3);

btnProduct = (Button)findViewById(R.id.button1);
btnProduct.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
String t1 = edText1.getText().toString();
String t2 = edText2.getText().toString();
String t3 = edText3.getText().toString();

int i1 = Integer.parseInt(t1);
int i2 = Integer.parseInt(t2);
int i3 = Integer.parseInt(t3);

int product = i1*i2*i3;


Toast.makeText(getApplicationContext(),
String.valueOf(product),Toast.LENGTH_LONG).show();
}
});
}

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. Android
provides this functionality through TimePicker class.

Methods of TimePicker:

Sr.No Method & description

is24HourView()
1
This method returns true if this is in 24 hour view else false

isEnabled()
2
This method returns the enabled status for this view

setCurrentHour(Integer currentHour)
3
This method sets the current hour

setCurrentMinute(Integer currentMinute)
4
This method sets the current minute

setEnabled(boolean enabled)
5
This method set the enabled state of this view

setIs24HourView(Boolean is24HourView)
6
This method set whether in 24 hour or AM/PM mode

setOnTimeChangedListener(TimePicker.OnTimeChangedListener
7 onTimeChangedListener)
This method Set the callback that indicates the time has been adjusted by the user

Example:

public class MainActivity extends Activity {

private TimePicker timePicker1;


private TextView time;
private Calendar calendar;
private String format = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
time = (TextView) findViewById(R.id.textView1);
calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
showTime(hour, min);

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 23


S.S.S.D.I.I.T – College Android & I Phone B.C.A

}
public void setTime(View view) {
int hour = timePicker1.getCurrentHour();
int min = timePicker1.getCurrentMinute();
showTime(hour, min);
}
public void showTime(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
time.setText(new StringBuilder().append(hour).append(" : ").append(min)
.append(" ").append(format));
}

Spinner: spinner which allows to select an item from a drop down menu.

Example:
Activity_main.xml
<!-- Spinner Element -->
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"
/>
MainActivity.java
public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);

// Spinner click listener


spinner.setOnItemSelectedListener(this);

// Spinner Drop down elements


List&lt;String&gt; categories = new ArrayList&lt;String&gt;();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");

// Creating adapter for spinner


ArrayAdapter&lt;String&gt; dataAdapter = new ArrayAdapter&lt;String&gt;(this,
android.R.layout.simple_spinner_item, categories);

// Drop down layout style - list view with radio button


dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner


spinner.setAdapter(dataAdapter);

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 24


S.S.S.D.I.I.T – College Android & I Phone B.C.A
}

Android layouts: A layout may contain any type of widgets such as buttons, labels, textboxes, and
so on.

Types of Android Layouts:


 Linear Layout
 Relative layout
 Frame layout
 Absolute Layout
 Table layout
- Linear layout:
o LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
o Attributes of Linear Layout:
 Following are the important attributes specific to LinearLayout:

Attribute Description

android:id This is the ID which uniquely identifies the layout.

This must be a boolean value, either "true" or "false" and prevents the layout
android:baselineAligned
from aligning its children's baselines.

This is drawable to use as a vertical divider between buttons. You use a color
android:divider
value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

This specifies how an object should position its content, on both the X and Y
android:gravity axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.

This specifies the direction of arrangmet and you will use "horizontal" for a
android:orientation
row, "vertical" for a column. The default is horizontal.
 Example: Activity_main.xml File

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


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

<Button android:id="@+id/btnStartService"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/start_service"
<Button android:id="@+id/btnPauseService"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/pause_service"
</LinearLayout>

- Relative layout:
o RelativeLayout is a view group that displays child views in relative positions.
o Relative Layout Attributes:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 25


S.S.S.D.I.I.T – College Android & I Phone B.C.A
o Following are the important attributes specific to RelativeLayout:

Attribute Description

android:id This is the ID which uniquely identifies the layout.

This specifies how an object should position its content, on both the X and Y
android:gravity axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.

android:ignoreGravity This indicates what view should not be affected by gravity.


o Example:

<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" />
<TextView
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
</RelativeLayout>

- Table Layout:
o TableLayout is a view that groups views into rows and columns.
o Following are the important attributes specific to TableLayout:

Attribute Description

android:id This is the ID which uniquely identifies the layout.

This specifies the zero-based index of the columns to collapse. The column
android:collapseColumns
indices must be separated by a comma: 1, 2, 5.

The zero-based index of the columns to shrink. The column indices must be
android:collapseColumns
separated by a comma: 1, 2, 5.

The zero-based index of the columns to stretch. The column indices must
android:stretchColumns
be separated by a comma: 1, 2, 5.
o Example:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="First Name"

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 26


S.S.S.D.I.I.T – College Android & I Phone B.C.A

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>

- Absolute Layout:
o AbsoluteLayout enables you to specify the exact location of its children.
o Following are the important attributes specific to AbsoluteLayout:

Attribute Description

android:id This is the ID which uniquely identifies the layout.

android:layout_x This specifies the x-coordinate of the view.

android:layout_y This specifies the y-coordinate of the view.


o Example:

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

- Frame layout:
Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 27
S.S.S.D.I.I.T – College Android & I Phone B.C.A
o The FrameLayout is a placeholder on screen that you can use to display a single view.
o Following are the important attributes specific to FrameLayout:

Attribute Description

android:id This is the ID which uniquely identifies the layout.

This defines the drawable to draw over the content and possible values
android:foreground may be a color value, in the form of "#rgb", "#argb", "#rrggbb", or
"#aarrggbb".

Defines the gravity to apply to the foreground drawable. The gravity


android:foregroundGravity defaults to fill. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.

Determines whether to measure all children or just those in the VISIBLE


android:measureAllChildren
or INVISIBLE state when measuring. Defaults to false.
o Example:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
Note: Other Layout’s are Grid View and ListView

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 28


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Database Connectivity Using SQLite


Topics of SQLite:

o Using Android Data and Storage API, Managing Data Using SQLite, Content Provider.

What is SQLite:
SQLite is an Open Source database. SQLite supports standard relational database features like SQL
syntax, transactions and prepared statements. The database requires limited memory at runtime
(approx. 250 KByte) which makes it a good candidate from being embedded into other runtimes.

SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in Java)
and REAL (similar to double in Java). All other types must be converted into one of these fields
before getting saved in the database.

SQLite in Android:
SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup
procedure or administration of the database.

If your application creates a database, this database is by default saved in the directory :

DATA/data/APP_NAME/databases/FILENAME .

SQLITE ARCHITECTURE:

 Package of SQLite in Android: android.database.sqlite


 Creating and updating database with SQLiteOpenhelper:
o SQLiteOpenHelper: To create and upgrade a database in your Android application
you create a subclass of the SQLiteOpenHelper class
o Super():In the constructor of your subclass you call the super() method
of SQLiteOpenHelper , specifying the database name and the current database
version.
o In SQLiteOpenHelper class you need to override the following methods to create
and update your database
 onCreate():is called by the framework, if the database is accessed but not
yet created
 onUpgrade():called, if the database version is increased in your application
code. This method allows you to update an existing database schema or to
drop the existing database and recreate it via the onCreate() method.

Note: Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.

 SQLite Database:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 29


S.S.S.D.I.I.T – College Android & I Phone B.C.A

o SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
o More specifically SQLiteDatabase provides

the insert() , update() and delete() methods.

o In addition it provides the execSQL() method, which allows to execute an SQL statement
directly.
o The object ContentValues allows to define key/values. The key represents the table
column identifier and the value represents the content for the table record in this
column. ContentValues can be used for inserts and updates of database entries.

o Queries can be created via the rawQuery() and query() methods or via
the SQLiteQueryBuilder class .
 rawQuery() directly accepts an SQL select statement as input.

Cursor cursor = getReadableDatabase(); rawQuery(“select * from tb1”);

 query() provides a structured interface for specifying the SQL query.

Parameter Comment

String dbName The table name to compile the query against.

String[] A list of which table columns to return. Passing "null" will return all
columnNames columns.

String whereClause Where-clause, i.e. filter for the selection of data, null will select all
data.

String[] selectionArgs You may include ?s in the "whereClause"". These placeholders will get
replaced by the values from the selectionArgs array.

String[] groupBy A filter declaring how to group rows, null will cause the rows to not be
grouped.

String[] having Filter for the groups, null means no filter.

String[] orderBy Table columns which will be used to order the data, null means no ordering.

 SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

 Cursor:

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 30


S.S.S.D.I.I.T – College Android & I Phone B.C.A
 A query returns a Cursor object. A Cursor represents the result of a query
and basically points to one row of the query result. This way Android can
buffer the query results efficiently; as it does not have to load all data into
memory.
 To get the number of elements of the resulting query use
the getCount() method.
 To move between individual data rows, you can use
the moveToFirst() and moveToNext() methods.
The isAfterLast() method allows to check if the end of the query
result has been reached.

Simple Example:

Ex1:

SQLiteDatabase sampleDB = this.openOrCreateDatabase("Testing", MODE_PRIVATE,


null)
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS t1 (LastName VARCHAR, FirstName
VARCHAR,Designation VARCHAR)");
sampleDB.execSQL("INSERT INTO t1 Values ('ripal','pandya','Lacturer')");
sampleDB.close();
Toast.makeText(this, "DB Created!", Toast.LENGTH_LONG).show();

Ex2:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

public static final String TABLE_COMMENTS = "comments";


public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";

private static final String DATABASE_NAME = "commments.db";


private static final int DATABASE_VERSION = 1;

// Database creation sql statement


private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";

public MySQLiteHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 31


S.S.S.D.I.I.T – College Android & I Phone B.C.A

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
onCreate(db);
}

ANDROID DATA STORAGE API:


Application are about functionality and data, we explore various ways you can store, retrieved
and share data with Android.

APPLICATION PREFERENCES:

Android provides a simple preferences system for storing primitive application data at the
Activity level and preferences shared across all of an application’s activities. Preferences are stored
as groups of key/value pairs.The following data types are supported as preference settings:

- Boolean value
- Float value
- Integer value
- Long Value
- String Value

CREATE PRIVATE AND SHARED PREFERENCES:

PRIVATE PREFERENCES:
Individual activities can have their own private preferences.These preferences are for the specific
Activity only and are not shared with other activities within the application.The activity gets only one
group of private preferences.
The following code retrieves the activity’s private preferences:
import android.content.SharedPreferences;
...
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);

SHARED PREFERENCES:
SharedPreferences is an API from Android SDK to store and retrieve
application preferences. SharedPreferences are simply sets of data values that stored persistently.
Persistently which mean data you stored in the SharedPreferences are still exist even if you stop the
application or turn off the device.

Creating shared preferences is similar.The only two differences are that we must name our
preference set and use a different call to get the preference instance:
import android.content.SharedPreferences;

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 32


S.S.S.D.I.I.T – College Android & I Phone B.C.A
...
SharedPreferences settings =
getSharedPreferences(“MyCustomSharedPreferences”, 0);

Mode of Shared Preference:


apply()
It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling

clear()
It will remove all values from the editor

remove(String key)
It will remove the value whose key has been passed as a parameter

putLong(String key, long value)


It will save a long value in a preference editor

putInt(String key, int value)


It will save a integer value in a preference editor

putFloat(String key, float value)


It will save a float value in a preference editor

How to Initialize Share Preference:


SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
How to Store Data in Shared Preference:
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
How to retrieved data From Shared Pereferences:
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Delete/ Clear Shared Preference:
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes

FILE CONCEPT IN ANDROID


Sometimes you might prefer to use traditional file system to store your data. We can use file
concepts using java.io package.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 33


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Mainly Two types of File Data Storage Available in Android:


- Internal Storage
- External Storage
INTERNAL STORAGE:
The first way to save files in your Android Application is to write to the devices internal storage.

EXAMPLE:
Main_Activity.xml

MainActivity.java
public class InternalStoreActivity extends Activity {
/** Called when the activity is first created. */
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextFileName=(EditText)findViewById(R.id.editText1); editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1); readButton=(Button)findViewById(R.id.button2);
saveButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
String data=editTextData.getText().toString(); FileOutputStream fos;
try { fos = openFileOutput(filename, Context.MODE_PRIVATE); fos.write(data.getBytes()); fos.close();
Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
} }); readButton.setOnClickListener(new OnClickListener(){
@Override public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer();
try { BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput(filename))); String inputString;
while ((inputString = inputReader.readLine()) != null) { stringBuffer.append(inputString + "\n"); }
} catch (IOException e) { e.printStackTrace();
}Toast.makeText(getApplicationContext(),stringBuffer.toString(),Toast.LENGTH_LONG).show(); }
}); } }
EXTERNAL STORAGE:
It would be useful to save them to external storage (such as an SD card) because of its larger
capacity, as well as the capability to share the files easily with other users (by removing the SD card
and passing it to somebody else).

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 34


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Example:
MainActivity.xml

AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java
public class ExternalStorageExActivity extends Activity {
/** Called when the activity is first created. */
EditText editTextFileName,editTextData;
Button saveButton,readButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextFileName=(EditText)findViewById(R.id.editText1); editTextData=(EditText)findViewById(R.id.editText2);
saveButton=(Button)findViewById(R.id.button1); readButton=(Button)findViewById(R.id.button2);
saveButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString(); String data=editTextData.getText().toString();
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+filename); myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data); myOutWriter.close(); fOut.close();
Toast.makeText(getApplicationContext(),filename + " saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();} } });
readButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) { String filename=editTextFileName.getText().toString();
StringBuffer stringBuffer = new StringBuffer(); String aDataRow = ""; String aBuffer = "";
try { File myFile = new File("/sdcard/"+filename); FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n"; } myReader.close(); } catch (IOException e) { e.printStackTrace();
} Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show(); } }); } }
CONTENT PROVIDER IN ANDROID

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 35


S.S.S.D.I.I.T – College Android & I Phone B.C.A

- Android using a Content Provider is the recommended way to share data across packages. Think of content
provider as a data store. How it stores its data is not relevant to the application using it;
- What is important is how packages can access the data stored in it using a consistent programming interface.
- A content Provider behaves very much like a database – you can Query it, edit its content, as
well as add or delete content. However, unlike a database, a content provider can use
different way to store its data. The data can be stored in a database, in files, or even over a
network.
Android Ships with many useful content providers, including the following:
- Browsers: Stores data such as browser bookmarks, browser history, and so on.
- CallLog: Store data such as missed calls, call detail and so on.
- Contacts: Stores contact details.
- MediaStore: Stores media files such as audio, video and images.
- Settings: Stores the devices setting and preferences.
HOW TO HANDLE CONTENT PROVIDER:
- Standard prefix for content providers is always content: //.
- Handle Content Provider using Query String.
- Examples of Query String:
o Content://media/internal/images
o Content://call_log/calls
o Content://browser/bookmarks
Predefined Query String Constants of Content Provider:
Besides using the query URI, you can use a list of predefined query string constant in android to specify the URI for the
different data types.
Uri allcontacts = Url.parse(‘content://contacts/people’);
Some examples of predefined query String:
- Browser.BOOKMARKS_URI
- Browser.SEARCH_URI
- CallLog.CONTENT_URI
- MediaStore.Images.Media.INTERNAL_CONTENT_URI
- Setting.CONTENT_URI

EXAMPLE OF CONTENT PROVIDER:


ContentProviderActivity.java
package com.contentProv;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class ContentProvActivity extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 36


S.S.S.D.I.I.T – College Android & I Phone B.C.A
public void onClickAddName(View view) {
// Add a new student record
ContentValues values = new ContentValues();

values.put(StudentsProvider.NAME,
((EditText)findViewById(R.id.txtName)).getText().toString());

values.put(StudentsProvider.GRADE,
((EditText)findViewById(R.id.txtGrade)).getText().toString());

Uri uri = getContentResolver().insert(


StudentsProvider.CONTENT_URI, values);

Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show(); }
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.provider.College/students";
Uri students = Uri.parse(URL);
Cursor c = managedQuery(students, null, null, null, "name");
if (c.moveToFirst()) {
do{ Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
} } }
StudentProvider.java
package com.contentProv;
import java.util.HashMap;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class StudentsProvider extends ContentProvider {


static final String PROVIDER_NAME = "com.example.provider.College";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String GRADE = "grade";
private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
static final int STUDENTS = 1;
static final int STUDENT_ID = 2;
static final UriMatcher uriMatcher;
static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID); }

/**
* Database specific constant declarations
*/
private SQLiteDatabase db;
static final String DATABASE_NAME = "College";
static final String STUDENTS_TABLE_NAME = "students";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 37


S.S.S.D.I.I.T – College Android & I Phone B.C.A
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT NOT NULL, " +
" grade TEXT NOT NULL);";

/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
onCreate(db);
} }
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)){
case STUDENTS:
count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
break;
case STUDENT_ID:
String id = uri.getPathSegments().get(1);
count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
} getContext().getContentResolver().notifyChange(uri, null);
return count; }
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
/**
* Get all student records
*/
case STUDENTS:
return "vnd.android.cursor.dir/vnd.example.students";
/**
* Get a particular student
*/
case STUDENT_ID:
return "vnd.android.cursor.item/vnd.example.students";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri); } }
@Override
public Uri insert(Uri uri, ContentValues values) {
/**
* Add a new student record
*/
long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
/**
* If record is added successfully
*/
if (rowID > 0)
{ Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null); return _uri; }
throw new SQLException("Failed to add a record into " + uri); }
@Override

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 38


S.S.S.D.I.I.T – College Android & I Phone B.C.A
public boolean onCreate(){
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
/**
* Create a write able database which will trigger its
* creation if it doesn't already exist.
*/
db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(STUDENTS_TABLE_NAME);
switch (uriMatcher.match(uri)) { case STUDENTS: qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
break; case STUDENT_ID: qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
break; default:
throw new IllegalArgumentException("Unknown URI " + uri); }
if (sortOrder == null || sortOrder == ""){
/**
* By default sort on student names
*/
sortOrder = NAME; } Cursor c = qb.query(db, projection,selection, selectionArgs, null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
c.setNotificationUri(getContext().getContentResolver(), uri);
return c; }
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)){
case STUDENTS:
count = db.update(STUDENTS_TABLE_NAME, values,
selection, selectionArgs);
break;
case STUDENT_ID:
count = db.update(STUDENTS_TABLE_NAME, values, _ID +
" = " + uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri ); }
getContext().getContentResolver().notifyChange(uri, null); return count; } }

LOCATION BASED SERVICE (LBS)


- GEOCODING LOCATION
- MAPPING LOCATION
WHAT IS GPS?

The Global Positioning System (GPS) is a space-based satellite navigation system that
provides location and time information in all weather conditions, anywhere on or near the
Earth where there is an unobstructed line of sight to four or more GPS satellites.

WHAT IS GEOCODING?
Geocoding (sometimes called forward geocoding) is the process of enriching a description
of a location, most typically a postal address or place name, with geographic
coordinates from spatial reference data such as building polygons, land parcels, street
addresses, ZIP codes (postal codes) and so on. Geocoding facilitates spatial analysis
using Geographic Information Systems and Enterprise Location Intelligence systems.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 39


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Reverse geocoding is the process of enriching geographic coordinates with a description of


the location, most typically a postal address or place name.
A geocoder is a piece of software or a (web) service that implements a geocoding process.

MAPPING APPLICATION IN ANDROID


Android gives your applications access to the location services supported by the device through
classes in theandroid.location package. The central component of the location framework is
the LocationManager system service, which provides APIs to determine location and bearing of the
underlying device (if available).
Once your application has a LocationManager, your application is able to do three things:

 Query for the list of all LocationProviders for the last known user location.
 Register/unregister for periodic updates of the user's current location from a location provider
(specified either by criteria or name).
 Register/unregister for a given Intent to be fired if the device comes within a given proximity
(specified by radius in meters) of a given lat/long.
GOOGLE MAP ANDROID API
- With the Google Maps Android API, you can add maps to your app that are based on Google
Maps data. The API automatically handles access to Google Maps servers, data downloading,
map display, and touch gestures on the map. You can also use API calls to add markers,
polygons and overlays, and to change the user's view of a particular map area.

- The key class in the Google Maps Android API is MapView. A MapView displays a map with
data obtained from the Google Maps service. When the MapView has focus, it will capture
keypresses and touch gestures to pan and zoom the map automatically, including handling
network requests for additional maps tiles. It also provides all of the UI elements necessary
for users to control the map. Your application can also use MapView class methods to
control the map programmatically and draw a number of overlays on top of the map.

LOCATION BASED SERVICES (LBS)


GPS:
The Global Positioning System (GPS) is a space-based satellite navigation system that provides
location and time information in all weather conditions, anywhere on or near the Earth where there
is an unobstructed line of sight to four or more GPS satellites.

The GPS project was developed in 1973 to overcome the


limitations of previous navigation systems,[2] integrating ideas
from several predecessors, including a number of classified
engineering design studies from the 1960s. GPS was created and
realized by theU.S. Department of Defense (DoD) and was
originally run with 24 satellites. It became fully operational in
1995. Bradford Parkinson,Roger L. Easton, and Ivan A. Getting are
credited with inventing it.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 40


S.S.S.D.I.I.T – College Android & I Phone B.C.A

GOOGLE MAP Android API with GEOCODING LOCATION:


Following Code and Steps to Create and Managed GEOCODING LOCATION
Step1: Go to SDK Manager:

Step2: Go to www.code.google.com/apis/console

Step3: Create Finger Print by using the key tool and Debug File

Step4: Generate Key Finger and Key


In the next step you need to run the command on cmd to generate the SHA1 finger print key by
using this keystore. So the command is :

keytool -list -v -keystore "C:\Android\debug.keystore" -alias androiddebugkey -storepass


android -keypass android
After run this command on cmd it will create the SHA1 finger key.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 41


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Step5: In this step you just copy thus SHA1 key from cmd and paste on the Google console of
configure android key for API project with your android project package name.

Step6: Now need to import the Google-play


Google -service_lib
service_lib project in your eclipse. This project is stored
inside the (sdk\extras\google\google_play_services
google_play_services\libproject).

Step 6: So here we start the create the new project name "GoogleMapLocationAPIV2
"GoogleMapLocationAPIV2" and set the
target with Google API and add the Google play service library project with this project. See the
screen shot.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 42


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Example of GEOCODING Location:


Step1: AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.INTERNET" />

Step2: Accessing the Geo Location for Lat and Long

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 43


S.S.S.D.I.I.T – College Android & I Phone B.C.A

return null;
}
}

Step3: Reverse Geocoding to get Location Address

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 44


S.S.S.D.I.I.T – College Android & I Phone B.C.A

bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Step4: Android UI
MainActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity {
Button btnGPSShowLocation;
Button btnShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tvAddress = (TextView) findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(
MyActivity.this);

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


btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 45


S.S.S.D.I.I.T – College Android & I Phone B.C.A

.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
String result = "Latitude: " + gpsLocation.getLatitude() +
" Longitude: " + gpsLocation.getLongitude();
tvAddress.setText(result);
} else {
showSettingsAlert();
}
}
});
btnShowAddress = (Button) findViewById(R.id.btnShowAddress);
btnShowAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}

}
});

}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MyActivity.this);
alertDialog.setTitle("SETTINGS");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MyActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 46


S.S.S.D.I.I.T – College Android & I Phone B.C.A

public void onClick(DialogInterface dialog, int which) {


dialog.cancel();
}
});
alertDialog.show();
}
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
tvAddress.setText(locationAddress);
}
}
}

Android Common API


What is Network API
 Networking on the Android platform is standardized, using a combination of powerful yet
familiar technologies and libraries such as java.net.
 The most common way to transfer data to and from the network is to use HTTP.
 You can use HTTP to encapsulate almost any type of data and to secure the data with SSL
We use Network API Using:
 HttpURLConnection
 HttpURLConnection retrieves some information about the resource referenced by
the URL object, including HTTP status and header information.
 How to Create Object:
 HttpURLConnection http = (HttpURLConnection)url.openConnection();
 Important Methods
 getContentLength();
 getContentType();
 getContent();
 Important Methods of Network API:
 isAvailable();
 isConnected();

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 47


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Example of Network API:


Check WIFI Status:
NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Check Mobile Status:
NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

ANDROID WEB API:


Applications that retrieve and display content from the Web often end up displaying that data on the
screen.

The WebView control uses the WebKit rendering engine to draw HTML content on the
screen.This content could be HTML pages on the Web or it can be locally sourced.

You can add this permission to your application’s Android manifest file as follows:
<uses-permission android:name=”android.permission.INTERNET” />
Examples:
Ex1: Displaying Layout with Web View Control
<WebView
android:id=”@+id/web_holder”
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”/>

Coding:
final WebView wv = (WebView) findViewById(R.id.web_holder);
wv.loadUrl(“http://www.perlgurl.org/”);

Ex2: View Layout in HTML With WebView Control


Create Your own HTML content and display. String strPageTitle = “The Last Words of Oscar
Wilde”; String strPageContent = “<h1>” + strPageTitle + “: </h1>\”Either that wallpaper
goes, or I do.\””; String myHTML = “<html><title>” + strPageTitle +”</title><body>”+
strPageContent +”</body></html>”;

wv.loadData(myHTML, “text/html”, “utf-8”);


Adding Features to WebView
Enabling and disabling zoom controls using the setSupportZoom() and
setBuiltInZoomControls() methods

Enabling and disabling JavaScript using the setJavaScriptEnabled() method

Enabling and disabling mouseovers using the setLightTouchEnabled() method


Configuring font families, text sizes, and other display characteristics

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 48


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Features of WebAPI (WebView):


- Enabling and disabling zoom controls using the setSupportZoom() and
setBuiltInZoomControls() methods
- Enabling and disabling JavaScript using the setJavaScriptEnabled() method
- Enabling and disabling mouseovers using the setLightTouchEnabled() method
- Configuring font families, text sizes, and other display characteristics.

Android TelePhony API


- The Android SDK provides a number of useful utilities for applications to integrate
phone features available on the device.
- Applications might need to place a call or send a text message.
- The TelephonyManager object within the android.telephony package is a great place to
start.
- The READ_PHONE_STATE permission is required to retrieve information such as the call
state, handset phone number, and device identifiers or serial numbers.
Requesting Call State:
- You can use the TelephonyManager object to retrieve the state of the phone and some
information about the phone service itself, such as the phone number of the handset.
- You can request an instance of TelephonyManager using the getSystemService()
method, like this: TelephonyManager telManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
Example of Making and Receive Call
Make Call:
Uri number = Uri.parse(“tel:” +numberEntry.getText().toString());
Intent dial = new Intent(Intent.ACTION_DIAL, number);
startActivity(dial);
Receive Call:
- To enable this within an application, you must implement a broadcast receiver to
process intents with the action Intent.ACTION_ANSWER.

- You can use the CallLog.calls class to determine recent call information, such as
Who called, When they called, Whether it was an incoming or outgoing call
Whether or not anyone answered, The duration of the call

Example of Sending and receiving SMS:


- SMS functionality is provided to applications through the android.telephony package.
- Permission:
<uses-permission android:name=”android.permission.SEND_SMS” />
<uses-permission android:name=”android.permission.RECEIVE_SMS” />
Send SMS:
final SmsManager sms = SmsManager.getDefault();

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 49


S.S.S.D.I.I.T – College Android & I Phone B.C.A

sms.sendTextMessage(“9427696988”, null, “Hi Welcome!”, null, null);


Receive SMS:
- Applications can also receive SMS messages.To do so, your application must register a
BroadcastReceiver to listen for the Intent action associated with receiving an SMS.

- An application listening to SMS in this way doesn’t prevent the message from getting to
other applications.

Notification
Introduction:

Android allows putting notification into the title bar of your application. The user can expand the
notification bar and by selecting the notification the user can trigger another activity.

Types of Notification:
- User Notification
- Status bar Notification
- Customizing Notification
Setting us Notification:
Notifications in Android are represented by the Notification class.
To create notifications you use the NotificationManager class which can be received from
the Context , e.g. an activity or a service, via the getSystemService() method.
Example:

NotificationManager notificationManager = (NotificationManager)


getSystemService(NOTIFICATION_SERVICE);

Notification Property:
- A small icon, set by setSmallIcon()
- A title, set by setContentTitle()
- Detail text, set by setContentText()
Example:
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

NotificationCompat.Builder Class:
Notificationbuild()
Combine all of the options that have been set and return a new Notification object.

NotificationCompat.BuildersetContent(RemoteViewsviews)
Supply a custom RemoteViews to use instead of the standard one.

NotificationCompat.BuildersetContentIntent(PendingIntentintent)
Supply a PendingIntent to send when the notification is clicked.

NotificationCompat.BuildersetContentText(CharSequencetext)
Set the text (second row) of the notification, in a standard notification.

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 50


S.S.S.D.I.I.T – College Android & I Phone B.C.A
NotificationCompat.BuildersetOngoing(booleanongoing)
Set whether this is an ongoing notification.

NotificationCompat.BuildersetWhen(longwhen)
Set the time that the event occurred. Notifications in the panel are sorted by this time.

Example of Notification:

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);

/* Creates an explicit intent for an Activity in your app */


Intent resultIntent = new Intent(this, NotificationView.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationView.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* notificationID allows you to update the notification later on. */
mNotificationManager.notify(notificationID, mBuilder.build());

SERVICES JASON WITH ANDROID


Introduction of JSON:
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is an easier-to-use alternative to XML.
Simple example of JSON:
{"employees":[
{"firstName":"Jay", "lastName":"Pandya"},
{"firstName":"kamal", "lastName":"Patel"},
{"firstName":"janak", "lastName":"Maheta"}
]}
Android Provide Four Different Classes to Manipulate json Data:
- JSONArray,
- JSONObject,
- JSONStringer and
- JSONTokenizer
Json Elements:
- Array():In a JSON file , square bracket ([) represents a JSON array
- Objects({):In a JSON file, curly bracket ({) represents a JSON object
- Key: A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 51


S.S.S.D.I.I.T – College Android & I Phone B.C.A
- Value: Each key has a value that could be string , integer or double e.t.c
JSON Parsing:
For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:
String in;
JSONObject reader = new JSONObject(in);

Deployment of Android Application:


Publishing Android Application:
TYPES OF PUBLISHING
- OFF LINE
- ONLINE
OFFLINE:
Step1: Go to Your Project Explorer
Step2: Right Click on Project  Export Android Application  Next 
Step3: Select Project to Export Next
Step3: KeyStore Selection  Create New KeyStore  Give Location, Password and Confirm
Password  Next
Step4: Key Creation  Enter Alias, password, Confirm Pass, First last name etc…  Next
Step5: Destination APK  Finish

ONLINE:
Step1: Create GOOGLE ACCOUNT
Step2: Login on Google Developer Account
Step3: Bank and Price Detail Pay 25$ on Account Creation

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 52


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Step4: Adding New Application Browse  Select APK

Step5: Select Default Language, Enter Application Title and Description.

Step6: Add Screen Shots and File Detail.

Step7: Publishing the application

______________________________________________________________

Learn All Programming


And
Scripting languages with
youtube.com/avadhtutor/Playlists

Learn all Examples with


pandyaripal.blogspot.com

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 53


S.S.S.D.I.I.T – College Android & I Phone B.C.A

Important Programs for Practical and Company based:


All Tutorial :
https://www.youtube.com/watch?v=i3nymhaPMPc&list=PLkx9f4H3tJMLkB0O4kE2
LfqLTs05A_Oqa

1. Pyramids Using Android Studio:


https://www.youtube.com/watch?v=HByMmkVBfXA&list=PLkx9f4H3tJMLkB0O4kE2LfqLT
s05A_Oqa&index=15

2. Intent (Navigation) :
https://www.youtube.com/watch?v=r3lU5DZ5TDU&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=20

3. Passing Data Between One Page to Another:


https://www.youtube.com/watch?v=ZU8MeIH4QeU&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=21

4. Validations Using Android


https://www.youtube.com/watch?v=-
XkznskzWGc&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=24

5. Android Stylish Buttons


https://www.youtube.com/watch?v=DmzWkiglfUU&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=27

6. SQLIte Inser Data:


https://www.youtube.com/watch?v=b3lOdXYGPLE&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=32

7. Fetch Data Using SQLIte:


https://www.youtube.com/watch?v=b3lOdXYGPLE&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs
05A_Oqa&index=33

8. Share Button:
https://www.youtube.com/watch?v=G3ZBM1iM-
kI&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=36

9. Action bar in Android


https://www.youtube.com/watch?v=V-gKDt-
sIlM&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=40

10 Activity Animation
https://www.youtube.com/watch?v=s-
bQVZswH_g&list=PLkx9f4H3tJMLkB0O4kE2LfqLTs05A_Oqa&index=43

Developed By: Ripal Pandya (94 2 76 96 9 88) Youtube.com/avadhtutor Page 54

You might also like