INDEX. CHAPTER Android Introduction

Size: px
Start display at page:

Download "INDEX. CHAPTER Android Introduction"

Transcription

1 INDEX CHAPTER Android Introduction 1.1 Introduction History of Android Versions of Android System Architecture of Android Installing Android Studio Hello World Program Creating an AVD Running the sample project on AVD CHAPTER Introduction of Building blocks of Android 2.1 Activity Intent and Intent Filters Broadcast receivers Services Content Providers Fragment CHAPTER Folder Structure 3.1 Folder Structure of Project Screen Designing using XML & Business Logic CHAPTER User Interface 4.1 Life cycle-activity Input Controls Layouts

2 4.4 Debugging Input events Navigations Implementing Intent types CHAPTER Adapters 5.1 Adapter Adapter View Types of Adapter Steps to Implement Simple List View/Grid view Date Picker & Time Picker CHAPTER Data Storage 6.1 Introduction to Data Storage Internal & External Storage SQLite Database CHAPTER Menus & Dialogs 7.1 Introduction to menus Option menu Context menu Popup menu Toolbar Alert Dialog Box DialogFragment Steps to Create Dialog Using Dialog Fragment

3 CHAPTER Animation, Threads 8.1 Animations in Android Types of Animations Animation Implementation Introduction to Threads CHAPTER Broadcast Receiver 9.1 BroadCast Receivers Finding Phone Events CHAPTER Content Provider, Service 10.1 Introduction to Content Provider ContentResolver & Content Provider Introduction To Services Types Of Services Service Life Cycle CHAPTER Fragments 11.1 Introduction To Fragment Fragment Life Cycle Building a Flexible UI Fragments Example Types of Fragments

4 11.6 How to use Fragments? CHAPTER Preferences 12.1 Introduction to Preferences To Save And Retrieve Preferences Through Code Common Types of Preferences Steps to Create Settings Preferences CHAPTER GCM Messaging 13.1 Explain Google Cloud Messaging? Explain GCM Service architecture CHAPTER Material Design and Pending Intent 14.1 Introduction to Material Design Recyclerview CardView Creating Lists & Cards Swipe refresh Layout Material Design Colour Customization Toolbar CHAPTER Web Services and Client Server 15.1 Anatomy of Client - Server Introduction To Web Services

5 15.3 Formats to Exchange Data XML Format Types of XML Parsing JSON Format Types of JSON Parsing CHAPTER Google Maps using Google Play Services CHAPTER Deployment

6 CHAPTER-1 Android Introduction 1.1 Introduction to Android What is Android Before learning all topics of android, it is required to know what is android. Android is a software package and linux based operating system for mobile devices such as tablet computers and smartphones. It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly used to write the android code even though other languages can be used. The goal of android project is to create a successful real-world product that improves the mobile experience for end users. There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc which is covered in next page. What is Open Handset Alliance (OHA) It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc. It was established on 5th November, 2007, led by Google. It is committed to advance open standards, provide services and deploy handsets using the Android Plateform. Features of Android After learning what is android, let's see the features of android. The important features of android are given below: 1) It is open-source. 2) Anyone can customize the Android Platform. 6

7 3) There are a lot of mobile applications that can be chosen by the consumer. 4) It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc. It provides support for messaging services(sms and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc. Categories of Android applications There are many android applications in the market. The top categories are: o o o o o o o o o Entertainment Tools Communication Productivity Personalization Music and Audio Social Media and Video Travel and Local etc. 1.2 History of Android The history and versions of android are interesting to know. The code names of android ranges from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, honeycomb, IceCreamSandwitch, JellyBean, Kitkat and Lollipop. Let's understand the android history in a sequence. 1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in October, ) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of Google Incorporation. 3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears. 4) Originally intended for camera but shifted to smart phones later because of low market for camera only. 5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots. 6) In 2007, Google announces the development of android OS. 7) In 2008, HTC launched the first android mobile. 7

8 1.3 Android Versions, Codename and API Let's see the android versions, codenames and API Level provided by Google. S.NO Code Name Alpha Beta Cupcake Donut Eclair Froyo Ginger bread Honey comb Ice- cream Sandwitch Jellybean Kitkat Lollipop Marshmallow Nougat Version Number Api Level Android 1.1 Android 1.1 Version was released on 9 Feb, Android 1.5 Cupcake Android 1.5 Cupcake was released on 30 April, 2009 Which was totally based on Linux kernel Android 1.5 was the first release officially use a codename based on a dessert item which is known as Cupcake. 8

9 3. Android 1.6 SDK Donut Android 1.6 Donut was released on Sep 15, 2009 Which was based on Linux kernel Android 2.0 SDK codenamed Eclair Android 2.0 Codenamed Eclair was released on Oct 26, 2009 Which was based on Linux kernel Android 2.2 Froyo Android 2.2 Froyo was released on May 20, 2010 Which was based on Linux kernel

10 6. Android 2.3/2.3.7 Gingerbread Android 2.3 Gingerbread SDK was released on Dec 6,2010 Which was based on Linux kernel Android 3.0/3.2 Honeycomb Android 3.0 Honeycomb was released on Feb 22, 2011 Which was based on Linux kernel This first device using this version was Motorola Xoom tablet, was lunched on 24 Feb, Android 4.0 Ice Cream Sandwich Android 4.0 Ice Cream Sanwich was released on Oct 19, 2011 Which was based on Linux kernel Google s Gabe Cohen Started this Android 4.0 Version with theoretically compatible which production on any Android 2.3.x device. 10

11 9. Android 4.1 Jelly Bean Android 4.1 Jelly Bean was announce on June 27, 2012 at the Google I/O conference by Google Which was based on Linux kernel This Android 4.1 Jelly Bean was released to the Android Open Source Project on July 9, The first Android 4.1 Jelly Bean device is Nexus 7 tablet which was released on July 13, Android 4.4 Kitkat Android 4.4 Kitkat was announced on Sep 3, 2013 by Google. This Android 4.4 was optimised to run on a huge range of smartphone then oldest Android Version, Having 512 MB RAM 11. Android 5.0/5.1 Lollipop Android 5.0 Lollipop was released on Nov 12,

12 12. Android 6.0 Marshmallow Android 6.0 Marshmallow was released on May 28, 2015 during Google I/O. 13. Android 7.0 Nougat Android 7.0 Nougat is the latest version of Android which will be release in the month of August or September If you really Want to know full details of Android Nougat then visit Wikipedia to know more about this version. 1.4 System Architecture of Android android architecture or Android software stack is categorized into five parts: linux kernel native libraries (middleware), Android Runtime Application Framework Applications 12

13 Let's see the android architecture first. 1) Linux kernel It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers, power management, memory management, device management and resource access. 2) Native Libraries On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc. The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing and recording audio and video formats. 3) Android Runtime In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast performance. 4) Android Framework 13

14 On the top of Native libraries and android runtime, there is android framework. Android framework includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It provides a lot of classes and interfaces for android application development. 5) Applications On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries. Android runtime and native libraries are using linux kernal. 1.5 Installing Android Studio Step 1 - System Requirements You will be delighted, to know that you can start your Android application development on either of the following operating systems Microsoft Windows 10/8/7/Vista/2003 (32 or 64-bit) Mac OS X or higher, up to 10.9 (Mavericks) GNOME or KDE desktop Second point is that all the required tools to develop Android applications are open source and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming. Java JDK5 or later version Java Runtime Environment (JRE) 6 Android Studio Step 2 - Setup Android Studio 14

15 Overview Android Studio is the official IDE for android application development.it works based on IntelliJ IDEA, You can download the latest version of android studio from Android Studio 2.2 Download, If you are new to installing Android Studio on windows,you will find a file, which is named as android-studio-bundle windows.exe.so just download and run on windows machine according to android studio wizard guideline. If you are installing Android Studio on Mac or Linux, You can download the latest version from Android Studio Mac Download,or Android Studio Linux Download, check the instructions provided along with the downloaded file for Mac OS and Linux. This tutorial will consider that you are going to setup your environment on Windows machine having Windows 8.1 operating system. Installation So let's launch Android Studio.exe,Make sure before launch Android Studio, Our Machine should required installed Java JDK. To install Java JDK,take a references of Android environment setup Once you launched Android Studio, its time to mention JDK7 path or later version in android studio installer. 15

16 Below the image initiating JDK to android SDK Need to check the components, which are required to create applications, below the image has selected Android Studio, Android SDK, Android Virtual Machine and performance(intel chip). 16

17 Need to specify the location of local machine path for Android studio and Android SDK, below the image has taken default location of windows 8.1 x64 bit architecture. Need to specify the ram space for Android emulator by default it would take 512MB of local machine RAM. At final stage, it would extract SDK packages into our local machine, it would take a while time to finish the task and would take 2626MB of Hard disk space. 17

18 AndroidManifest.xml It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE. Android Virtual Device (AVD) It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices. Android Emulator Android Emulator is used to run, debug and test the android application. If you don't have the real device, it can be the best way to run, debug and test the application. It uses an open source processor emulator technology called QEMU. The emulator tool enables you to start the emulator from the command line. You need to write:emulator -avd <AVD NAME> In case of Andriod Studio, you can create AVD by Window menu > AVD Manager > New. After done all above steps perfectly, you must get finish button and it gonna be open android studio project with Welcome to android studio message as shown below 18

19 You can start your application development by calling start a new android studio project. in a new installation frame should ask Application name, package information and location of the project. After entered application name, it going to be called select the form factors your application runs on, here need to specify Minimum SDK, in our tutorial, I have declared as API23: Android 6.0(Mashmallow) 19

20 The next level of installation should contain selecting the activity to mobile, it specifies the default layout for Applications At the final stage it going to be open development tool to write the application code. 20

21 1.6 Hello Word Example Before Writing a Hello word code, you must know about XML tags.to write hello word code, you should redirect to App>res>layout>Activity_main.xml To show hello word, we need to call text view with layout ( about text view and layout, you must take references at Relative Layout and Text View ). <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_height="match_parent" 21

22 tools:context=".mainactivity"> <TextView android:layout_width="550dp" android:layout_height="wrap_content"/> </RelativeLayout> Need to run the program by clicking Run>Run App or else need to call shift+f10key. Finally, result should be placed at Virtual devices as shown below 22

23 1.7 Creating an AVD (Android Virtual Device) To test your Android applications, you will need a virtual Android device. So before we start writing our code, let us create an Android virtual device. Launch Android AVD Manager Clicking AVD_Manager icon as shown below After Click on a virtual device icon, it going to be shown by default virtual devices which are present on your SDK, or else need to create a virtual device by clicking Create new Virtual device button 23

24 If your AVD is created successfully it means your environment is ready for Android application development. If you like, you can close this window using top-right cross button. Better you re-start your machine and once you are done with this last step, you are ready to proceed for your first Android example but before that we will see few more important concepts related to Android Application Development. 1.8 Running the sample project on AVD 24

25 CHAPTER-2 Android Core Building Blocks An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc. The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml. 2.1 Activity An activity represents a single screen with a user interface just like window or frame of Java. Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program within an Activity starting with a call on oncreate() callback method. There is a sequence of callback methods that start up an activity Activity is a Java code that supports a screen or UI. In other words, building block of the user interface is the activity.activity class is a pre-defined class in Android and every application which has UI must inherit it to create window. Generally one android application has multiple activities to which user interacts, like send SMS, take a photo etc. We can have Activities of different sizes like activity that fills the screen, activity that shows up as notification etc. 25

26 There might be multiple activities in an application Activity Life Cycle Methods All activities in your Android apps are represented by an activity class. These activity classes are subclasses of android.app.activity. The Activity class contains a set of methods that corresponds to the life cycle states an activity can be in. These methods are: oncreate() onstart() onrestart() onresume() onpause() onstop() ondestroy() 2.2 Intent and Intent Filters Intent Intent is used to invoke components.an Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways. An intent can contain data via a Bundle. This data can be used by the receiving component. It is mainly used to: o o o o o o Start the service Launch an activity Display a web page Display a list of contacts Broadcast a message Dial a phone call etc. For example, you may write the following code to view the webpage. 26

27 There are three fundamental use cases: Starting an activity An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startactivity(). The Intent describes the activity to start and carries any necessary data. If you want to receive a result from the activity when it finishes, call startactivityforresult(). Your activity receives the result as a separate Intent object in your activity's onactivityresult() callback. For more information, see the Activities guide. Starting a service A Service is a component that performs operations in the background without a user interface. With Android 5.0 (API level 21) and later, you can start a service with JobScheduler. For more information about JobScheduler, see its API-reference documentation. For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of theservice class. You can start a service to perform a one-time operation (such as downloading a file) by passing an Intent to startservice(). The Intent describes the service to start and carries any necessary data. If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent to bindservice(). For more information, see the Services guide. Delivering a broadcast A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to sendbroadcast() or sendorderedbroadcast(). Intent types There are two types of intents: Explicit intents specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you can start a new activity in response to a user action or start a service to download a file in the background. use explicit intents to: start a new activity start an activity to get a result 27

28 start a service broadcast an intent start a new activity from within a broadcast receiver Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. use implicit intents to: use other app s components to: send an pick a contact from the contacts list make a phone call 2.3 Broadcast Receivers A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event. Imagine an event like external power being connected/disconnected from the device, screen turning on/off, battery getting low or picture captured. All these events originate from the system. Infact apps themselves can also initiate broadcasts for example the SMS app broadcasting that an SMS has being received and let other apps know about this event so that they can trigger some action. It is intended to do minimal amount of work and can delegate hardcore jobs to Services. It receives an Intent object. A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object. Following are some of the important system wide generated intents. android.intent.action.battery_low : Indicates low battery condition on the device. 28

29 android.intent.action.boot_completed : This is broadcast once, after the system has finished booting android.intent.action.call : To perform a call to someone specified by the data android.intent.action.date_changed : The date has changed android.intent.action.reboot : Have the device reboot android.net.conn.connectivity_change : The mobile network or wifi connection is changed(or reset) 2.4 Services Service is a background process that can run for a long time.there are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device. A service is a application component used to perform long running tasks in background. A service doesn t have any user interface and neither can directly communicate to an activity. A service can run in the background indefinitely, even if component that started the service is destroyed. Usually a service always performs a single operation and stops itself once intended task is complete. A service runs in the main thread of the application instance. It doesn t create its own thread. If your service is going to do any long running blocking operation, it might cause Application Not Responding (ANR). And hence, you should create a new thread within the service. A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, Service is the alternative. 2.5 Content Provider Content Providers are used to share data between the applications. 29

30 Content providers are Android s central mechanism that enables you to access data of other applications mostly information stored in databases or flat files. As such content providers are one of Android s central component types to support the modular approach common to Android. Without content providers accessing data of other apps would be a mess. Content providers support the four basic operations, normally called CRUD-operations. CRUD is the acronym for create, read, update and delete. With content providers those objects simply represent data most often a record (tuple) of a database but they could also be a photo on your SD-card or a video on the web. Android provides some standard content providers to access contacts, media files, preferences and so on. I am going to show you how to use these content providers in the second part of this tutorial. 2.6 Fragment: A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities). A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button. When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity. 30

31 CHAPTER-3 Android Studio Folder Structure: Android application development is never been easy due to its raw nature and rapid growth and changes to platform. If we cast our memories back a few years, Eclipse was the only IDE used for android development. Eclipse is developed and maintained by open source alliance. Due to its open source and free nature, it always failed to match its all time competitor platform IDE like XCode. But now android development looks very promising with the introduction of Android Studio IDE. Android Studio is an IDE based on IntelliJ IDEA that is used for android application development. The initial developer preview was released on 15th may This tool has more options that will enable developers to speed up application development. In the later section of this tutorial we will understand the Android Studio project structure in context to traditional eclipse based project structure. Gradle Based Build System Android Studio is an IDE based on IntelliJ IDEA that uses gradle build system. In eclipse, you can create only one build at a time. Which means, first create debug build and later you can create a release build by signing with your keystore. 31

32 Android Studio projects are setup to build both a debug and a release version of the application. The debug version is signed with the developer key store key which is created automatically (Same as eclipse debug builds). The release is not signed during the build, this needs to happen after. Android Studio, make it easy to create several variants of an application, either for multiapk distribution or for different flavors of an application. This means, you can have different builds for debug, release or may be different variant build from the same code. Eclipse ADT plugin, always generate single R.java file but, Android Studio supports multiple. The generated R.java is located in the debug folder. You can change your build variant between debug and release and accordingly it will create the R.java file in selected debug or release directory. Change the build type configuration here from the bottom left corner in your android Studio. 32

33 3.1 Android Studio Project Structure 1. Main Project This would be entire project context. Whatever you do in IntelliJ IDEA, you do that in the context of a project. A project is an organizational unit that represents a complete software solution. A project in Android Studio is like a workspace in Eclipse. In android Studio a project, can contain multiple modules. A module in Android Studio is like a project in Eclipse. In the above screenshot LoginAuthenticator is the name of my project This means that, in theory it is possible to build multiple apps within the same project. From my personal experience, creating multiple apps within the same project doesn t works well. So, I recommend not to make your hands dirty trying the same thing. Instead, It is a better idea to create single app per single project. 33

34 2. idea Eclipse uses project.properties file for project specific metadata. Here in android studio, this.idea does the same thing. This means the project specific metadata is stored by Android Studio. 3. Project Module (app) This is the actual project folder where your application code resides. The application folder has following sub directories a. build: This has all the complete output of the make process i.e. classes.dex, compiled classes and resources, etc. In the Android Studio GUI, only a few folders are shown. The important part is that your R.java is found here under build/source/r/<build variant>/<package>/r.java b. libs : This is a commonly seen folder in eclipse land too, which optionally can hold the libraries or.jar files. c. src: The src folder can have both application code and android unit test script. You will find two folders named androidtest and main correspond to src folder. The main folder contains two subfolders java and res. The java folder contains all the java codes and res contains drawables, layouts, etc. 4. gradle This is where the gradle build system s jar wrapper i.e. this jar is how AS communicates with gradle installed in Windows (the OS in my case). 34

35 5. External Libraries This is not actually a folder but a place where Referenced Libraries and information on targeted platform SDK is shown. 3.2 Screen Designing using XML and Business Logic Open android studio and start a new window then create a new Activity then we get xml along with.java file and now implement your design with xml, implement your logic using.java file and run it on emulator to check the output. Example: activity_main.xml Now implement your logic in MainActivity.java file. 35

36 activity_second.xml Now click on run button you get a screen as shown below. 36

37 Now click on ok, you will get emulator screen. now click on click button you will get another screen with a message as shown below. 37

38 38

39 CHAPTER-4 User Interface 4.1 Activity life cycle: An activity represents a single screen with a user interface just like window or frame of Java.Android activity is the subclass of ContextThemeWrapper class. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on oncreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below. Activity life cycle diagram 39

40 The Activity class defines the following call backs i.e. events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Activity Call Back's are shown below: Sr.No 1 Callback & Description oncreate() This is the first callback and called when the activity is first created. onstart() 2 This callback is called when the activity becomes visible to the user. onresume() 3 This is called when the user starts interacting with the application. onpause() 4 The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. onstop() 5 This callback is called when the activity is no longer visible. ondestroy() 6 7 This callback is called before the activity is destroyed by the system. onrestart() 40

41 This callback is called when the activity restarts after stopping it. 4.2 Input Controls Input Controls are the interactive components in your app's user interface. Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons and many more. UI ELEMENTS A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the user interface. Android UI Controls: There are number of UI controls provided by Android that allow you to build the graphical user interface for your app. Sr.No. 1 UI Control & Description TextView This control is used to display text to the user. 2 EditText EditText is a predefined subclass of TextView that includes rich editing capabilities. 3 AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing. 41

42 4 Button A push-button that can be pressed, or clicked, by the user to perform an action. 5 ImageButton An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user. 6 CheckBox An on/off switch that can be toggled by the user. You should use check box when presenting users with a group of selectable options that are not mutually exclusive. 7 ToggleButton An on/off button with a light indicator. 8 RadioButton The RadioButton has two states: either checked or unchecked. 9 RadioGroup A RadioGroup is used to group together one or more RadioButtonsss. 10 ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a task in the background. 11 Spinner A drop-down list that allows users to select one value from a set. 12 TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode. 13 DatePicker The DatePicker view enables users to select a date of the day. 42

43 4.3 Layouts The basic building block for user interface is a View object which is created from the View class and occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components like buttons, text fields, etc. The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and define their layout properties. At third level we have different layouts which are subclasses of ViewGroup class and a typical layout defines the visual structure for an Android user interface and can be created either at run time using View/ViewGroup objects or you can declare your layout using simple XML file main_layout.xml which is located in the res/layout folder of your project. Android Layout Types There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different view, look and feel. Sr.No 1 Layout & Description Linear Layout LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. 2 Relative Layout RelativeLayout is a view group that displays child views in relative positions. 3 Table Layout TableLayout is a view that groups views into rows and columns. 4 Absolute Layout AbsoluteLayout enables you to specify the exact location of its children. 5 Frame Layout The FrameLayout is a placeholder on screen that you can use to display 43

44 a single view. 6 List View ListView is a view group that displays a list of scrollable items. 7 Grid View GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. Linear Layout: LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify the layout direction with the android:orientation attribute. All children of a LinearLayout are stacked one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row high (the height of the tallest child, plus padding). A LinearLayout respects margins between children and the gravity (right, center, or left alignment) of each child. Relative Layout: RelativeLayout is a view group that displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center). 44

45 A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout. Table Layout: TableLayout is a ViewGroup that displays child View elements in rows and columns. TableLayout positions its children into rows and columns. TableLayout containers do not display border lines for their rows, columns, or cells. The table will have as many columns as the row with the most cells. A table can leave cells empty. Cells can span multiple columns, as they can in HTML. You can span columns by using the span field in the TableRow.LayoutParams class. 45

46 TableRow objects are the child views of a TableLayout (each TableRow defines a single row in the table). Each row has zero or more cells, each of which is defined by any kind of other View. So, the cells of a row may be composed of a variety of View objects, like ImageView or TextView objects. A cell may also be a ViewGroup object (for example, you can nest another TableLayout as a cell). Absolute Layout: An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning Frame Layout: FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute. ListView: ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list. For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter. 46

47 Grid View: GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter. Layout Attributes Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be applied to all the layouts: Sr.No 1 Attribute & Description android:id This is the ID which uniquely identifies the view. 2 android:layout_width This is the width of the layout. 3 android:layout_height 47

48 This is the height of the layout 4 android:layout_margintop This is the extra space on the top side of the layout. 5 android:layout_marginbottom This is the extra space on the bottom side of the layout. 6 android:layout_marginleft This is the extra space on the left side of the layout. 7 android:layout_marginright This is the extra space on the right side of the layout. 8 android:layout_gravity This specifies how child Views are positioned. 9 android:layout_weight This specifies how much of the extra space in the layout should be allocated to the View. 10 android:layout_x This specifies the x-coordinate of the layout. 11 android:layout_y This specifies the y-coordinate of the layout. 12 android:layout_width This is the width of the layout. 13 android:layout_width 48

49 This is the width of the layout. 14 android:paddingleft This is the left padding filled for the layout. 15 android:paddingright This is the right padding filled for the layout. 16 android:paddingtop This is the top padding filled for the layout. 17 android:paddingbottom This is the bottom padding filled for the layout. 4.4 Debugging Android Studio includes a debugger that enables you to debug apps running on the Android Emulator or a connected Android device. With the Android Studio debugger, you can do the following: Select a device to debug your app on. Set breakpoints in your Java and C/C++ code. Examine variables and evaluate expressions at runtime. Capture screenshots and videos of your app. Before you start debugging your app, make sure you're using a build variant that sets the debuggable build type property to true, such as the "debug" build variant. To change the build variant Android Studio uses, select Build > Select Build Variant in the menu bar (or click Build Variants in the windows bar), and then select a build variant from the dropdown menu. Similarly, if your app depends on a library module that you also want to debug, you need to configure the library module to publish a debuggable build variant, such as the "debug" variant. To start debugging, click Debug in the toolbar. Android Studio builds an APK, signs it with a debug key, installs it on your selected device, then runs it and opens the Debug window 49

50 If no devices appear in the Select Deployment Target window after you click Debug, then you need to either connect a device or click Create New Emulator to setup the Android Emulator. Figure 1. The Debugger window, showing the current thread and the object tree for a variable. If your app is already running on a connected device or emulator, you can start debugging as follows: 1. Click Attach debugger to Android process. 2. In the Choose Process dialog, select the process you want to attach the debugger to. By default, the debugger shows the device and app process for the current project, as well as any connected hardware devices or virtual devices on your computer. Select Show all processes to show all processes on all devices; the display includes any services that your app created as well as system processes, for example. From the Debugger menu, you can select a different debug type. By default, Android Studio uses the Auto debug type to select the best debugger option for you, based on whether your project includes Java or C/C++ code. 3. Click OK. The Debug window appears. In this case, notice the two tabs to the right of the Debug window title: one tab is for debugging native code and the other for Java code, as indicated by -java. 50

51 1. Separate debugging sessions have separate tabs and different port numbers, which are displayed in parentheses in the tab. To end a debugging session, click the tab for the session, and then click Terminate 2.. Note: The Android Studio debugger and garbage collector are loosely integrated. The Android virtual machine guarantees that any object the debugger is aware of is not garbage collected until after the debugger disconnects. This can result in a buildup of objects over time while the debugger is connected. For example, if the debugger sees a running thread, the associated Thread object is not garbage collected even after the thread terminates. Use the system log The system log shows system messages while you debug your app. These messages include information from apps running on the device. If you want to use the system log to debug your app, make sure your code writes log messages and prints the stack trace for exceptions while your app is in the development phase. Write log messages in your code To write log messages in your code, use the Log class. Log messages help you understand the execution flow by collecting the system debug output while you interact with your app. Log messages can tell you what part of your application failed. For more information about logging, see Reading and Writing Logs. The following example shows how you might add log messages to determine if previous state information is available when your activity starts: 51

52 import android.util.log; public class MyActivity extends Activity { private static final String TAG = Public void oncreate(bundle savedinstancestate) { if (savedinstancestate!= null) { Log.d(TAG, "oncreate() Restoring previous state"); /* restore state */ else { Log.d(TAG, "oncreate() No saved state available"); /* initialize app */ During development, your code can also catch exceptions and write the stack trace to the system log: void someothermethod() { try { catch (SomeException e) { Log.d(TAG, "someothermethod()", e); 52

53 View the system log Both the Android DDMS (Dalvik Debug Monitor Server) and the Android Monitor windows show logs from the system and any particular app process. To view the system log on the Android DDMS tool window: 1. Start your app as described in Run your App in Debug Mode. 2. Click Android Monitor. 3. If the system log is empty in the Logcat view, click Restart. Figure 2. The system log in the Android DDMS tool window. The Android DDMS tool window gives you access to some DDMS features from Android Studio. For more information about DDMS, see Using DDMS. The system log shows messages from Android services and other Android apps. To filter the log messages to view only the ones you are interested in, use the tools in the Android DDMS window: To show only log messages for a particular process, select the process in the Devices view and then click Only Show Logcat from Selected Process. If the Devices view is not available, click Restore Devices View on the right of the Android DDMS tool window. This button is only visible when you hide the Devices window. To filter log messages by log level, select a level from the Log Level drop-down on the top of the Android DDMS window. To show only log messages that contain a particular string, enter the string in the search box and press Enter. 53

54 Work with breakpoints Android Studio supports several types of breakpoints that trigger different debugging actions. The most common type is a line breakpoint that pauses the execution of your app at a specified line of code. While paused, you can examine variables, evaluate expressions, then continue execution line by line to determine the causes of runtime errors. To add a line breakpoint, proceed as follows: Locate the line of code where you want to pause execution, then either click the left gutter along that line of code or place the caret on the line and press Control+F8 (on Mac, Command+F8). If your app is already running, you don't need to update it to add the breakpoint just click Attach debugger to Android proccess clicking Debug. Otherwise, start debugging by. 3. Figure 3. A red dot appears next to the line when you set a breakpoint. When your code execution reaches the breakpoint, Android Studio pauses execution of your app. You can then use the tools in the Debugger tab to identify the state of the app: To examine the object tree for a variable, expand it in the Variables view. If the Variables view is not visible, click Restore Variables View To evaluate an expression at the current execution point, click Evaluate Expression.. To advance to the next line in the code (without entering a method), click Step Over. To advance to the first line inside a method call, click Step Into. To advance to the next line outside the current method, click Step Out To continue running the app normally, click Resume Program.. If your project uses any native code, by default, the Auto debug type attaches both the Java debugger and LLDB to your app as two separate processes, so you can switch between inspecting Java and C/C++ breakpoints without restarting your app or changing settings. 54

55 When Android Studio deploys your app to your target device, the Debug window opens with a tab, or debug session view, for each debugger process, as shown in figure 4. Figure 4. Debugging native code using LLDB. 1. Android Studio automatically switches to the <your-module> tab when LLDB debugger encounters a breakpoint in your C/C++ code. The Frames, Variables, and Watches panes are also available and work exactly as they would if you were debugging Java code. Although the Threads pane is not available in the LLDB session view, you can access your app processes using the drop-down list in the Frames pane. You can learn more about these panes in the sections about how to Debug Window Frames and Inspect Variables. 2. Android Studio automatically switches to the <your-module> java tab when the Java debugger encounters a breakpoint in your Java code. 3. While debugging with LLDB, you can use the LLDB terminal in the LLDB session view to pass command line options to LLDB. If you have certain commands that you would like LLDB to execute each time you start debugging your app, either just before or just after the debugger attaches to your app process, you can add those commands to your debug configuration. While debugging C/C++ code, you can also set special types of breakpoints, called watchpoints, that can suspend your app process when your app interacts with a particular block of memory. To learn more, read the section about how to add watchpoints. View and configure breakpoints To view all the breakpoints and configure breakpoint settings, click View Breakpoints on the left side of the Debug window. The Breakpoints window appears, as shown in figure 5. 55

56 Figure 5. The Breakpoints window lists all the current breakpoints and includes behavior settings for each. The Breakpoints window lets you enable or disable each breakpoint from the list on the left. If a breakpoint is disabled, Android Studio does not pause your app when it hits that breakpoint. Select a breakpoint from the list to configure its settings. You can configure a breakpoint to be disabled at first and have the system enable it after a different breakpoint is hit. You can also configure whether a breakpoint should be disabled after it is hit. To set a breakpoint for any exception, select Exception Breakpoints in the list of breakpoints. Inspect variables To add a variable or expression to the Watches list, follow these steps: 1. Begin debugging. 2. In the Watches pane, click Add 3.. In the text box that appears, type the name of the variable or expression you want to watch and then press Enter. To remove an item from the Watches list, select the item and then click Remove You can reorder the elements in the Watches list by selecting an item and then clicking Up or Down. 56.

57 Figure 6. The Variables and Watches panes in the Debugger window. Add watchpoints While debugging C/C++ code, you can set special types of breakpoints, called watchpoints, that can suspend your app process when your app interacts with a particular block of memory. For example, if you set two pointers to a block of memory and assign a watchpoint to it, using either pointer to access that block of memory triggers the watchpoint. In Android Studio, you can create a watchpoint during runtime by selecting a specific variable, but LLDB assigns the watchpoint to only the block of memory the system allocates to that variable, not the variable itself. This is different from adding a variable to the Watches pane, which enables you to observe the value of a variable but doesn t allow you to suspend your app process when the system reads or changes its value in memory. In order to set a watchpoint, you must meet the following requirements: Your target physical device or emulator uses an x86 or x86_64 CPU. If your device uses an ARM CPU, then you must align the boundary of your variable s address in memory to either 4 bytes for 32-bit processors, or 8 bytes for 64-bit processors. You can align a variable in your native code by specifying attribute ((aligned(num_bytes))) in the variable deceleration, as shown below: // For a 64-bit ARM processor int my_counter attribute ((aligned(8))); You have assigned three or fewer watchpoints already. Android Studio only supports up to four watchpoints on x86 or x86_64 target devices. Other devices may support fewer watchpoints. If you meet the requirements above, you can add a watchpoint as follows: 1. While your app is suspended on a breakpoint, navigate to the Variables pane in your LLDB session view. 57

58 2. Right-click on a variable that occupies the block of memory you want to track and select Add Watchpoint. A dialog to configure your watchpoint appears, as shown in figure 7. Figure 7. Adding a watchpoint to a variable in memory. 3. Configure your watchpoint with the following options: Enabled: You can deselect this option if you want to tell Android Studio to ignore the watchpoint for the time being. Android Studio still saves your watchpoint so you can access it later in your debug session. Suspend: By default, the Android system suspends your app process when it accesses a block of memory you assign to a watchpoint. You can deselect this option if you don t want this behavior this reveals additional options you can use to customize behavior when the system interacts with your watchpoint: Log message to console and Remove [the watchpoint] when hit. Access Type: Select whether your app should trigger your watchpoint when it tries to Read or Write to the block of memory the system allocates to the variable. To trigger your watchpoint on either a read or write, select Any. 4. Click Done. To view all your watchpoints and configure watchpoint settings, click View Breakpoints on the left side of the Debug window. The Breakpoints dialog appears, as shown in figure 8. 58

59 Figure 8. The Breakpoints dialogue lists your current watchpoints and includes behavior settings for each. After you add your watchpoint, click Resume Program on the left side of the Debug window to resume your app process. By default, if your app tries to access a block of memory that you have set a watchpoint to, the Android system suspends your app process and a watchpoint icon ( executed last, as shown in figure 9. ) appears next to the line of code that your app Figure 9. Android Studio indicates the line of code that your app executes just before triggering a watchpoint. 59

60 Capture screenshots and videos Android Studio enables you to capture a screenshot or a short video of the device screen while your app is running. Screenshots and videos are useful as promotional materials for your app, and you can also attach them to bug reports that you send to your development team. To take a screenshot of your app: 1. Start your app as described in Run your App in Debug Mode. 2. Click Android Monitor 3. Click Screen Capture. on the left. 4. Optional: To add a device frame around your screenshot, click Frame screenshot. 5. Click Save. To take a video recording of your app: 1. Start your app as described in Run your App in Debug Mode. 2. Click Android Monitor 3. Click Screen Record. on the left. 4. Click Start Recording. 5. Interact with your app. 6. Click Stop Recording. 7. Enter a file name for the recording and click OK. 4.5 Input Events Events are useful way to collect data about a user's interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out(fifo) basis. you can capture these events in your program and take appropriate action as per requirements. There are following three concepts related to Android Event Management Event Listeners An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI. 60

61 Event Listeners Registration Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Event Handlers When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event. Event Listeners & Event Handlers Event Handler Event Listener & Description OnClickListener() onclick() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onclick() event handler to handle such event. OnLongClickListener() onlongclick() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onlongclick() event handler to handle such event. OnFocusChangeListener() onfocuschange() This is called when the widget looses its focus ie. user goes away from the view item. You will use onfocuschange() event handler to handle such event. OnFocusChangeListener() onkey() ontouch() This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onkey() event handler to handle such event. OnTouchListener() This is called when the user presses the key, releases 61

62 the key, or any movement gesture on the screen. You will use ontouch() event handler to handle such event. OnMenuItemClickListener() onmenuitemclick() This is called when the user selects a menu item. You will use onmenuitemclick() event handler to handle such event. oncreatecontextmenuitemlistener() oncreatecontextmenu() This is called when the context menu is being built(as the result of a sustained "long click) There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps. Event Listeners Registration Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation. Using an Anonymous Inner Class Activity class implements the Listener interface. Using Layout file activity_main.xml to specify event handler directly. Below section will provide you detailed examples on all the three scenarios Touch Mode Users can interact with their devices by using hardware keys or buttons or touching the screen.touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.you can check if the device is in touch mode by calling the View class s isintouchmode() method. Focus 62

63 A view or widget is usually highlighted or displays a flashing cursor when it s in focus. This indicates that it s ready to accept input from the user. isfocusable() it returns true or false isfocusableintouchmode() checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode) android:foucsup="@=id/button_l" ontouchevent() public boolean ontouchevent(motionevent event){ switch(event.getaction()){ case TOUCH_DOWN: Toast.makeText(this,"you have clicked down Touch button",toast.lenth_long).show(); break(); case TOUCH_UP: Toast.makeText(this,"you have clicked up touch button",toast.lenth_long).show(); break; case TOUCH_MOVE: Toast.makeText(this,"you have clicked move touch button"toast.lenth_long).show(); break; return super.ontouchevent(event) ; 4.6 Navigation: 63

64 In this chapter, we will see that how you can provide navigation forward and backward between an application. We will first look at how to provide up navigation in an application. Providing Up Navigation The up navigation will allow our application to move to previous activity from the next activity. It can be done like this. To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity. You can do it by specifying parentactivityname attribute in an activity. Its syntax is given below android:parentactivityname = "com.example.test.mainactivity" After that you need to call setdisplayhomeasupenabled method of getactionbar() in the oncreate method of the activity. This will enable the back button in the top action bar. getactionbar().setdisplayhomeasupenabled(true); The last thing you need to do is to override onoptionsitemselected method. when the user presses it, your activity receives a call to onoptionsitemselected(). The ID for the action is android.r.id.home.its syntax is given below public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case android.r.id.home: NavUtils.navigateUpFromSameTask(this); return true; 64

65 Handling device back button Since you have enabled your back button to navigate within your application, you might want to put the application close function in the device back button. It can be done by overriding onbackpressed and then calling movetasktoback and finish method. Its syntax is given public void onbackpressed() { movetasktoback(true); MainActivity2.this.finish(); Apart from this setdisplayhomeasupenabled method, there are other methods available in ActionBar API class. They are listed below Sr.No 1 Method & description addtab(actionbar.tab tab, boolean setselected) This method adds a tab for use in tabbed navigation mode 2 getselectedtab() This method returns the currently selected tab if in tabbed navigation mode and there is at least one tab present 3 hide() This method hide the ActionBar if it is currently showing 4 removealltabs() 65

66 This method remove all tabs from the action bar and deselect the current tab 5 selecttab(actionbar.tab tab) This method select the specified tab Example The below example demonstrates the use of Navigation. It creates a basic application that allows you to navigate within your application. To experiment with this example, you need to run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/mainactivity.java file to add Activity code. 3 Create a new activity with the name of second_main.java and edit it to add activity code. 4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 5 Modify layout XML file res/layout/second.xml add any GUI component if required. 6 Modify AndroidManifest.xml to add necessary code. 7 Run the application and choose a running android device and install the application on it and verify the results. 4.7 Implementing intent types 66

67 An Android Intent is an abstract description of an operation to be performed. It can be used with startactivity to launch an Activity, broadcastintent to send it to any interested BroadcastReceiver components, and startservice(intent) or bindservice(intent, ServiceConnection, int) to communicate with a background Service. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. For example, let's assume that you have an Activity that needs to launch an client and sends an using your Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your data. Intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); .putextra(intent.extra_ , recipients); .putextra(intent.extra_subject, subject.gettext().tostring()); .putextra(intent.extra_text, body.gettext().tostring()); startactivity(intent.createchooser( , "Choose an client from...")); Above syntax is calling startactivity method to start an activity and result should be as shown below 67

68 For example, assume that you have an Activity that needs to open URL in a web browser on your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity. String q = "tutorialspoint"; Intent intent = new Intent(Intent.ACTION_WEB_SEARCH ); intent.putextra(searchmanager.query, q); startactivity(intent); Above example will search as tutorialspoint on android search engine and it gives the result of tutorialspoint in your an activity There are separate mechanisms for delivering intents to each type of component activities, services, and broadcast receivers. Sr.No 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. 68

69 Intent Objects An Intent object is a bundle of information which is used by the component that receives the intent as well as information used by the Android system. An Intent object can contain the following components based on what it is communicating or going to perform Action This is mandatory part of the Intent object and is a string naming the action to be performed or, in the case of broadcast intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is structured. The Intent class defines a number of action constants corresponding to different intents. The action in an Intent object can be set by the setaction() method and read by getaction(). Data Adds a data specification to an intent filter. The specification can be just a data type (the mimetype attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts These attributes that specify the URL format are optional, but also mutually dependent If a scheme is not specified for the intent filter, all the other URI attributes are ignored. If a host is not specified for the filter, the port attribute and all the path attributes are ignored. 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(). Some examples of action/data pairs are Sr.No. 1 Action/Data Pair & Description ACTION_VIEW content://contacts/people/1 Display information about the person whose identifier is "1". 2 ACTION_DIAL content://contacts/people/1 69

70 Display the phone dialer with the person filled in. ACTION_VIEW tel:123 3 Display the phone dialer with the given number filled in. ACTION_DIAL tel:123 4 Display the phone dialer with the given number filled in. ACTION_EDIT content://contacts/people/1 5 Edit information about the person whose identifier is "1". ACTION_VIEW content://contacts/people/ 6 Display a list of people, which the user can browse through. ACTION_SET_WALLPAPER 7 Show settings for choosing wallpaper ACTION_SYNC 8 It going to be synchronous the data,constant Value is android.intent.action.sync ACTION_SYSTEM_TUTORIAL 9 It will start the platform-defined tutorial(default tutorial or start up tutorial) ACTION_TIMEZONE_CHANGED 10 It intimates when time zone has changed 11 ACTION_UNINSTALL_PACKAGE 70

71 It is used to run default uninstaller Category The category is an optional part of Intent object and it's a string containing additional information about the kind of component that should handle the intent. The addcategory() method places a category in an Intent object, removecategory() deletes a category previously added, and getcategories() gets the set of all categories currently in the object. 71

72 CHAPTER-5 Adapter 5.1Adapter: An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set. Known Indirect Subclasses: ArrayAdapter<T>, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, Reso urcecursoradapter, SimpleAdapter,SimpleCursorAdapter, SpinnerAdapter, ThemedSpinner Adapter, WrapperListAdapter Why Android Adapter? Without Android Adapter, to implement the ListView functionality, you will need to: Create a TextView within a ScrollView group. Then you will have to implement pagination concept for the contents of the TextView. You will also have to write additional code to identify the click event on a particular row in the TextView. You may be asking why we need Pagination. Imagine that you are creating an application that needs to display all your s and the user will be able to scroll through them. I get around 100 s on a daily basis and even if we consider 10 s per day, the data is going to be extremely huge. If you do not implement pagination, you will have major performance issues in retrieving all that data and showing it on the mobile screen. Thank God, we have adapters in Android and adapter views! 72

73 Below is a conceptual diagram which shows the high level working of the Android Adapter Let us now understand the internal working of an Android Adapter and how it acts as a data pump to the adapter view. Adapters call the getview() method which returns a view for each item within the adapter view. The layout format and the corresponding data for an item within the adapter view is set in the getview() method. Now, it will be a performance nightmare if getview() returns a new View every time it is called. Creating a new view is very expensive in Android as you will need to loop through the view hierarchy (using the find ViewbyID () method) and then inflate the view to finally display it on the screen. It also puts a lot of pressure on the garbage collector. That is because when the user is scrolling through the list, if a new view is created; the old view (since it is not recycled) is not referenced and becomes a candidate to be picked up by the garbage collector. So what Android does is that it recycles the views and reuses the view that goes out of focus. Below is a visual representation of this recycle process: 73

74 In the above figure, let us assume we are displaying the months in a year in a ListView. To begin with, the months January till May are shown in the screen. When you scroll the view, 5the month January goes out of the display area of the mobile screen. As soon as the January view goes out of the screen, the Adapter View (ListView in this case) sends the view to something called a recycler.so when you scroll up, the getview () method is called to get the next view (which is June). This method getview() has a parameter called convertview which points to the unused view in the recycler. Through the convertview, the Adapter tries to get hold of the unused view and reuse it to display the new view (which is June in this case). 5.2 Adapter view An AdapterView is a view whose children are determined by an Adapter.In Android Adapters are bridge between the Adapter View (e.g. ListView, GridView) and underlying data for that view. The Adapter is also responsible for making a View for each item in the result set. Android separates the responsibilities of showing data into list controls and adapters. The Adapter is responsible for creating child views used to represent each item and providing access to the underlying data.in Android List controls that supports Adapter binding extend the android.widget.adapterview class. ListView, GridView, Spinner and Gallery extends the AdapterView. 74

75 As you can see in diagram, the AdapterView class is inherited form ViewGroup class and ListView, GridView and Spinner classes are derived from AdapterView class. The Adapter extend the BaseAdapter class. It manages the data for an AdapterView and provides the child view for it. Android allows you to create custom adaptor for your application by extending class with BaseAdapter. 5.3 Types of Adapters In android commonly used adapters are: 1. Array Adapter 2. Base Adapter Now we explain these two adapters in detail using List View/Grid View: 5.4 Steps To Implement Simple List View/Grid View 75

76 ListView: List of scrollable items can be displayed in Android using ListView. It helps you to displaying the data in the form of a scrollable list. Users can then select any list item by clicking on it. ListView is default scrollable so we do not need to use scroll View or anything else with ListView. ListView is widely used in android applications. A very common example of ListView is your phone contact book, where you have a list of your contacts displayed in a ListView and if you click on it then user information is displayed. Adapter: To fill the data in a ListView we simply use adapters. List items are automatically inserted to a list using an Adapter that pulls the content from a source such as an arraylist, array or database. ListView in Android Studio: Listview is present inside Containers. From there you can drag and drop on virtual mobile screen to create it. Alternatively you can also XML code to create it. Here is Android ListView XML Code: <ListView xmlns:android=" xmlns:tools=" android:id="@+id/simplelistview" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context="abhiandroid.com.listexample.mainactivity"> </ListView> Listview look in Design: 76

77 Attributes of ListView: Let s see some different attributes of ListView which will be used while designing a custom list: 1. id: id is used to uniquely identify a ListView. Below is the id attribute s example code with explanation included. <!-- Id of a list view uniquely identify it--> <ListView android:id="@+id/simplelistview" android:layout_width="fill_parent" android:layout_height="wrap_content" /> 2. divider: This is a drawable or color to draw between different list items. Below is the divider example code with explanation included, where we draw red color divider between different views. <!--Divider code in ListView--> 77

78 <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="#f00" android:dividerheight="1dp" /> 3. dividerheight: This specify the height of the divider between list items. This could be in dp(density pixel),sp(scale independent pixel) or px(pixel). In above example of divider we also set the divider height 1dp between the list items. The height should be in dp, sp or px. 4. listselector: listselector property is used to set the selector of the listview. It is generally orange or Sky blue color mostly but you can also define your custom color or an image as a list selector as per your design. Below is listselector example code with explanation includes, where list selector color is green, when you select any list item then that item s background color is green. <!-- List Selector Code in ListView --> <ListView android:id="@+id/simplelistview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="#f00" android:dividerheight="1dp" android:listselector="#0f0"/> <!--list selector in green color--> 78

79 Adapters Use in ListView: An adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and sends the data to adapter view then view can takes the data from the adapter view and shows the data on different views like as list view, grid view, spinner etc. ListView is a subclass of AdapterView and it can be populated by binding to an Adapter, which retrieves the data from an external source and creates a View that represents each data entry. 1. Array Adapter: Whenever you have a list of single items which is backed by an array, you can use ArrayAdapter. For instance, list of phone contacts, countries or names. Important Note: By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in list items, please avoid ArrayAdapter and use custom adapters. Below is Array Adapter code: ArrayAdapter adapter = ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray); new Example of list view using Array Adapter: In this example, we display a list of countries by using simple array adapter. Below is the final output we will create: Create a new project List example and activity Main Activity. Here we will create a ListView in LinearLayout. 79

80 <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.coderefer.simplelistview.countryactivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> </RelativeLayout> Create a new activity name Listview and below is the code of activity_listview.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context="com.coderefer.simplelistview.countryactivity"> <ImageView 80

81 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> </RelativeLayout> In third step we will use custom adapter to display the country names in UI by coding MainActivity.java. Below is the code of MainActivity.java Important Note: Make sure flag images are stored in drawable folder present inside res folder with correct naming. packagecom.example.user.listview; importandroid.content.intent; importandroid.os.bundle; import android.support.v7.app.appcompatactivity; importandroid.view.menu; importandroid.view.menuitem; importandroid.view.view; importandroid.widget.adapterview; importandroid.widget.arrayadapter; importandroid.widget.listview; importandroid.widget.toast; public class MainActivity extends AppCompatActivity { ListViewmListView; String[] Countries = new String[]{"India", "Australia", "Newzealand", "Indonesia", "China", "Russia", "Japan", "South Korea"; int[] FlagId = new int[]{r.drawable.india, R.drawable.australia, R.drawable.newzealand,R.drawable.indonesia, R.drawable.china, R.drawable.russia, R.drawable.southafrika; 81

82 @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mlistview = (ListView) findviewbyid(r.id.list); ArrayAdapter<String>countryAdapter = android.r.layout.simple_list_item_1, Countries); new ArrayAdapter<String>(this, mlistview.setadapter(countryadapter); mlistview.setonitemclicklistener(new AdapterView.OnItemClickListener() { public void onitemclick(adapterview<?> parent, View view, int position, long id) { intitemposition = position; String itemvalue = (String) mlistview.getitematposition(position); Intent intent = new Intent(getApplicationContext(), CountryActivity.class); intent.putextra("flag", FlagId[position]); startactivity(intent); ); Now create another class Custom Adapter which will extend BaseAdapter. Below is the code of CustomAdapter.java packagecom.example.user.listview; importandroid.content.intent; import android.support.v7.app.actionbaractivity; import android.support.v7.app.appcompatactivity; importandroid.os.bundle; importandroid.view.menu; importandroid.view.menuitem; importandroid.widget.imageview; 82

83 public class CountryActivity extends ActionBarActivity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_country); ImageViewimageView = (ImageView) findviewbyid(r.id.ivcountryflag); Intent i = getintent(); intflagid = i.getintextra("flag", 0); imageview.setimageresource(flagid); Output: Now run the App in Emulator and it will show you name of countries along with flags. Below is the output screen: ListView consists of country names, we can scroll down the listview and view flag of a particular country by selecting any name in the list. 83

84 GridView: In android GridView is a view group that display items in two dimensional scrolling grid (rows and columns), the grid items are not necessarily predetermined but they are automatically inserted to the layout using a ListAdapter. Users can then select any grid item by clicking on it. GridView is default scrollable so we don t need to use ScrollView or anything else with GridView. GridView is widely used in android applications. An example of GridView is your default Gallery, where you have number of images displayed using grid. Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use adapter and grid items are automatically inserted to a GridView using an Adapter which pulls the content from a source such as an arraylist, array or database. You can read full Adapter tutorial here. GridView in Android Studio: Gridview is present inside Containers. From there you can drag and drop on virtual mobile screen to create it. Alternatively you can also XML code to create it. 84

85 Basic GridView code in XML: <GridView android:layout_width="fill_parent" android:layout_height="wrap_content" android:numcolumns="3"/> Attributes of GridView: Let s see different attributes of GridView which will be used while designing a custom grid view: 1.id: id is used to uniquely identify a GridView.Below is the id attribute s example code with explanation included in which we don t specify the number of columns in a row that s why the GridView behaves like a ListView. Below is the id attribute example code for Gridview: <GridView android:id="@+id/simplegridview" android:layout_width="fill_parent" android:layout_height="wrap_content" /> 2.numColumns: numcolumn define how many columns to show. It may be a integer value, such as 5 or auto_fit. auto_fit is used to display as many columns as possible to fill the available space on the screen. Important Note: If we don t specify numcolumn property in GridView it behaves like a ListView with singlechoice. Below is the numcolumns example code where we define 4 columns to show in the screen. <!-- numcolumns example code --> <GridView android:id="@+id/simplegridview" android:layout_width="fill_parent" 85

86 android:layout_height="wrap_content" android:numcolumns="4"/> <!-- numcolumns set to 4--> 3. horizontalspacing: horizontalspacing property is used to define the default horizontal spacing between columns. This could be in pixel (px), densitypixel (dp) or scale independent pixel (sp). Below is the horizontalspacing example code with explanation included where horizontal spacing between grid items is 50 dp. <!--Horizontal space example code in grid view-->> <GridView android:layout_width="fill_parent" android:layout_height="wrap_content" android:numcolumns="3" android:horizontalspacing="50dp"/> <!--50dp horizontal space between grid items--> 4.verticalSpacing: verticalspacing property used to define the default vertical spacing between rows. This should be in px, dp or sp. Below is the verticalspacing example code with explanation included, where vertical spacing between grid items is 50dp. <!-- Vertical space between grid items code --> <GridView android:layout_width="fill_parent" android:layout_height="wrap_content" android:numcolumns="3" 86

87 android:verticalspacing="50dp"/> <!--50dp vertical space set between grid items--> 5.columnWidth: columnwidth property specifies the fixed width of each column. This could be in px, dp or sp. Below is the columnwidth example code. Here column width is 80dp and selected item s background color is green which shows the actual width of a grid item. Important Note: In the below code we also used listselector property which define color for selected item. Also to see the output of columnwidth using listselector we need to use Adapter which is our next topic. The below code is not sufficient to show you the output. <!--columnwidth in Grid view code--> <GridView android:id="@+id/simplegridview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numcolumns="3" android:columnwidth="80dp" android:listselector="#0f0"/> <!--define green color for selected item--> GridView Example Using Adapters in Android Studio: An adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and sends the data to adapter view, then view can takes the data from the adapter view and shows the data on different views like as list view, grid view, spinner etc. GridView and ListView both are subclasses of AdapterView and it can be populated by binding to an Adapter, which retrieves the data from an external source and creates a View that represents each data entry. In android commonly used adapters which fill data in GridView: 1. Array Adapter 87

88 2. Base Adapter 3. Custom Array Adapter Now we explain these adapters in detail: 1. Avoid Array Adapter To Fill Data In GridView: Whenever you have a list of single items which is backed by an array, you can use ArrayAdapter. For instance, list of phone contacts, countries or names. By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in grid items, please avoid ArrayAdapter and use custom adapters. ArrayAdapter adapter = ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray); new 2. GridView Using Base Adapter in Android Base Adapter is a common base class of a general implementation of an Adapter that can be used in GridView. Whenever you need a customized grid view you create your own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying custom grid items. ArrayAdapter is also an implementation of BaseAdapter. You can read BaseAdapter tutorial here. Example of GridView using Base Adapter in Android Studio: Below is the example of GridView in Android, in which we show the Android logo s in the form of Grids. In this example firstly we create an int type array for logo images and then call the Adapter to set the data in the GridView. In this we create a CustomAdapter by extending BaseAdapter in it. At Last we implement setonitemclicklistener event on GridView and on click of any item we send that item to another Activity and show the logo image in full size. 88

89 Create a new Android project in Android Studio and fill all the required details. Open activity_main.xml <?xml version="1.0" encoding="utf-8"?> <GridViewxmlns:android=" android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:columnwidth="90dp" android:numcolumns="auto_fit" android:verticalspacing="10dp" android:horizontalspacing="10dp" android:stretchmode="columnwidth" android:gravity="center" /> 89

90 Create class (ImageAdapter) that extends BaseAdapter. packagecom.example.user.gridview; importandroid.content.context; importandroid.view.view; importandroid.view.viewgroup; importandroid.widget.baseadapter; importandroid.widget.gridview; importandroid.widget.imageview; public class ImageAdapter extends BaseAdapter { private Context mcontext; public ImageAdapter(Context c) { mcontext = c; publicintgetcount() { returnmthumbids.length; public Object getitem(int position) { return null; public long getitemid(int position) { return public View getview(int position, View convertview, ViewGroup parent) { ImageViewimageView; if (convertview == null) { imageview = new ImageView(mContext); 90

91 imageview.setlayoutparams(new GridView.LayoutParams(85, 85)); imageview.setscaletype(imageview.scaletype.center_crop); imageview.setpadding(8, 8, 8, 8); else { imageview = (ImageView) convertview; imageview.setimageresource(mthumbids[position]); returnimageview; private Integer[] mthumbids = { R.drawable.a1, R.drawable.a2, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a1, R.drawable.a2, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a1, R.drawable.a7, R.drawable.a7, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7 ; Now open MainActivity.java in this step firstly we get the reference of GridView and then create anint type array for logos. After that we call the Adapter and pass the array in it. At Last we implement setonitemclicklistener event on GridView packagecom.example.user.gridview; 91

92 import android.support.v7.app.appcompatactivity; importandroid.os.bundle; importandroid.view.view; importandroid.widget.adapterview; importandroid.widget.gridview; importandroid.widget.toast; public class MainActivity extends AppCompatActivity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); GridViewgridview = (GridView) findviewbyid(r.id.gridview); gridview.setadapter(new ImageAdapter(this)); gridview.setonitemclicklistener(new AdapterView.OnItemClickListener() public void onitemclick(adapterview<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show(); ); 92

93 Output: Now run the App and you will see different images in GridView. 5.5 Date Picker & Time Picker DatePicker: In Android, DatePicker is a widget used to select a date. It allows to select date by day, month and year in your custom UI (user interface). If we need to show this view as a dialog then we have to use a DatePickerDialog class. For selecting time Android also provides timepicker to select time. DatePicker code in XML: <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datepickermode="spinner"/> 93

94 Methods of Date Picker Let s discuss some common methods of a datepicker which are used to configure a DatePicker in our application. 1. setspinnersshown(boolean shown): This method is used to set whether the spinner of the date picker in shown or not. In this method you have to set a Boolean value either true or false. True indicates spinner is shown, false value indicates spinner is not shown. Default value for this function is true. Below we show the use of setspinnershown() function by setting false value. DatePickersimpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker simpledatepicker.setspinnersshown(false); // set false value for the spinner shown function 2. getdayofmonth(): This method is used to get the selected day of the month from a date picker. This method returns an integer value. Below we get the selected day of the month from a date picker. /*Add in Oncreate() funtion after setcontentview()*/ DatePickersimpleDatePicker = (DatePicker) findviewbyid(r.id.simpledatepicker); // initiate a date picker int day = simpledatepicker.getdayofmonth(); // get the selected day of the month 3. getmonth(): This method is used to get the selected month from a date picker. This method returns an integer value. Below we get the selected month from a date picker. DatePickersimpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker int month = simpledatepicker.getmonth(); // get the selected month 4. getyear(): This method is used to get the selected year from a date picker. This method returns an integer value. Below code is used to get the selected year from a date picker. 94

95 DatePickersimpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker int year = simpledatepicker.getyear(); // get the selected year 5. getfirstdayofweek(): This method is used to get the first day of the week. This method returns an integer value. Below code is used to get the first day of the week. DatePickersimpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker intfirstday=simpledatepicker.getfirstdayofweek(); // get the first day of the week Attributes of Date Picker: Now let s we discuss some important attributes that helps us to configure a DatePicker in your XML file (layout). 1. id: id is an attribute used to uniquely identify a date picker. <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 2. datepickermode: This attribute is used to set the Date Picker in mode either spinner or calendar. Default mode is calendar but this mode is not used after api level 21, so from api level 21 you have to set the mode to spinner. Below is an example code in which we set the mode to spinner for a date picker. <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datepickermode="spinner" /><!-- spinner mode of a date picker --> 95

96 3. background: background attribute is used to set the background of a date picker. We can set a color or a drawable image in the background. Below we set the red color for the background of a date picker. <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datepickermode="spinner"android:background="#f00"/><!-background of the date picker --> red color for the Setting background of DatePicker In Java Class: DatePicker simpledatepicker=(datepicker)findviewbyid(r.id.simpledatepicker); // initiate a date picker simpledatepicker.setbackgroundcolor(color.red); // red color for the background of a date picker 4. padding: padding attribute is used to set the padding from left, right, top or bottom for a date picker. paddingright: set the padding from the right side of the date picker. paddingleft: set the padding from the left side of the date picker. paddingtop: set the padding from the top side of the date picker. paddingbottom: set the padding from the bottom side of the date picker. Padding: set the padding from the all sides of the date picker. Below code of padding attribute set the 40dp padding from all the sides of the date picker. <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:datepickermode="spinner" android:padding="40dp"/><!-- 40dp padding from all the sides of a date picker --> 96

97 DatePicker Example Create a new project. Open xml file and add the code for displaying edittext which will be used to display the date of datepicker. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context="com.example.user.datepicker.mainactivity"> <DatePicker android:id="@+id/simpledatepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#150" android:datepickermode="spinner" /> <Button android:id="@+id/submitbutton" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_below="@+id/simpledatepicker" android:layout_centerhorizontal="true" android:layout_margintop="50dp" android:background="#150" 97

98 android:text="submit" android:textcolor="#fff" android:textsize="20sp" android:textstyle="bold" /> </RelativeLayout> Activity class: Open MainActivity where we add the code to initiate the edittext to display date (day of month, month and year) from a date picker. packagecom.example.user.datepicker; import android.support.v7.app.appcompatactivity; importandroid.os.bundle; importandroid.view.view; importandroid.widget.button; importandroid.widget.datepicker; importandroid.widget.toast; public class MainActivity extends AppCompatActivity { DatePickersimpleDatePicker; Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); simpledatepicker = (DatePicker) findviewbyid(r.id.simpledatepicker); submit = (Button) findviewbyid(r.id.submitbutton); submit.setonclicklistener(new View.OnClickListener() public void onclick(view v) { 98

99 String day = "Day = " + simpledatepicker.getdayofmonth(); String month = "Month = " + (simpledatepicker.getmonth() + 1); String year = "Year = " + simpledatepicker.getyear(); Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); day + "\n" + month + "\n" + year, ); Output: Time Picker In Android, TimePicker is a widget used for selecting the time of the day in either AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and clock format. If we need to show this view as a Dialog then we have to use a TimePickerDialog class. TimePicker code: 99

100 <TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:timepickermode="spinner"/> Methods of Time Picker Let s discuss some common methods of a time picker, which are used to configure a time picker in our application. 1. setcurrenthour(integer currenthour): This method is used to set the current hours in a time picker. sethour(integer hour): setcurrenthour() method was deprecated in API level 23. From api level 23 we have to use sethour(integer hour). In this method there is only one parameter of integer type which is used to set the value for hours. Below we set the 5 value for the current hours. TimePicker simpletimepicker=(timepicker)findviewbyid(r.id.simpletimepicker); initiate a time picker // // set the value for current hours simpletimepicker.setcurrenthour(5); // before api level 23 simpletimepicker.sethour(5); // from api level setcurrentminute(integer currentminute): This method is used to set the current minutes in a time picker. setminute(integer minute): setcurrentminute() method was deprecated in API level 23. From api level 23 we have to use setminute(integer minute). In this method there is only one parameter of integer type which set the value for minutes. Below we set the 35 value for the current minutes. TimePicker simpletimepicker=(timepicker)findviewbyid(r.id.simpletimepicker); initiate a time picker // set the value for current hours simpletimepicker.setcurrentminute(35); // before api level //

101 simpletimepicker.setminute(35); // from api level getcurrenthour(): This method is used to get the current hours from a time picker. getcurrenthour(): getcurrenthour() method was deprecated in API level 23. From api level 23 you have to use gethour(). This method returns an integer value. Below we get the value of hours from a timepicker set by user. TimePickersimpleTimePicker initiate a time = (TimePicker)findViewById(R.id.simpleTimePicker); // pickerint hours =simpletimepicker.getcurrenthour(); // before api level 23 int hours =simpletimepicker.gethour(); // after api level getcurrentminute(): This method is used to get the current minutes from a time picker. getminute(): getcurrentminute() method was deprecated in API level 23. From api level 23 we have to use getminute(). This method returns an integer value. Below we get the value of minutes from a time picker. TimePickersimpleTimePicker initiate a time picker = (TimePicker)findViewById(R.id.simpleTimePicker); // int minutes = simpletimepicker.getcurrentminute(); // before api level 23 int minutes = simpletimepicker.getminute(); // after api level setis24hourview(boolean is24hourview): This method is used to set the mode of the Time picker either 24 hour mode or AM/PM mode. In this method we set a Boolean value either true or false. True value indicate 24 hour mode and false value indicate AM/PM mode. Below we set the current mode of the time picker. TimePickersimpleTimePicker initiate a time picker = (TimePicker)findViewById(R.id.simpleTimePicker); simpletimepicker.setis24hourview(true); // set 24 hours mode for the time picker 6. is24hourview(): 101 //

102 This method is used to check the current mode of the time picker. This method returns true if its 24 hour mode or false if AM/PM mode is set. Below we get the current mode of the time picker: TimePickersimpleTimePicker initiate a time picker = (TimePicker)findViewById(R.id.simpleTimePicker); // Boolean mode=simpletimepicker.is24hourview(); // check the current mode of the time picker 7.setOnTimeChangedListener(TimePicker.OnTimeChangedListeneronTimeChangedLi stener): This method is used to set the callback that indicates the time has been adjusted by the user. ontimechanged(timepicker view, int hourofday, int minute) is an override function of this listener in which we have three parameters first is for TimePicker, second for getting hour of the day and last is for getting the minutes after changing the time of the time picker. Below we show the use of on time changed listener of a time picker. TimePickersimpleTimePicker initiate a time picker = (TimePicker)findViewById(R.id.simpleTimePicker); // simpletimepicker.setontimechangedlistener(new TimePicker.OnTimeChangedListener() public void ontimechanged(timepicker view, inthourofday, int minute) { ); Attributes of TimePicker Now let s we discuss about the attributes that helps us to configure a time picker in your xml file (layout). 1. id: id is an attribute used to uniquely identify a time picker. <TimePicker android:id="@+id/simpletimepicker" android:layout_width="wrap_content" 102

103 android:layout_height="wrap_content"/><!-- id of a time picker --> 2. TimePickerMode: time picker mode is an attribute of time picker used to set the mode either spinner or clock. Default mode is clock but this mode is no longer used after API level 21, so from API level 21 you have to set the mode to spinner. Below we set the mode to spinner. <TimePicker android:id="@+id/simpletimepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:timepickermode="spinner" /><!-- time picker mode of a time picker --> 3. background: background attribute is used to set the background of a time picker. We can set a color or a drawable image in the background. We can also set the background color programmatically means in java class. Below we set the orange color for the background of a time picker. <TimePicker android:id="@+id/simpletimepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:timepickermode="spinner" android:background="#f88f00" /><!-- orange background color for the time picker --> Time Picker Example Create a new project. Open activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android=" xmlns:tools=" 103

104 android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.user.timepickersample.mainactivity"> <TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_margintop="50dp" android:background="#090" android:padding="20dp" android:timepickermode="spinner" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:text="time Is ::" android:textcolor="#090" android:textsize="20sp" android:textstyle="bold" /> </RelativeLayout> 104

105 Activity class: Open MainActivity where we add the code to initiate the time picker and a text view to display time of time picker and then we performsetontimechangedlistener(). packagecom.example.user.timepickersample; import android.support.v7.app.appcompatactivity; importandroid.os.bundle; importandroid.widget.textview; importandroid.widget.timepicker; importandroid.widget.toast; public class MainActivity extends AppCompatActivity { TextView time; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); time = (TextView) findviewbyid(r.id.time); simpletimepicker = (TimePicker) findviewbyid(r.id.simpletimepicker); simpletimepicker.setis24hourview(false); simpletimepicker.setontimechangedlistener(new TimePicker.OnTimeChangedListener() public void ontimechanged(timepicker view, inthourofday, int minute) { // display a toast with changed values of time picker Toast.makeText(getApplicationContext(), Toast.LENGTH_SHORT).show(); hourofday + " " + minute, time.settext("time is :: " + hourofday + " : " + minute); // set the current time in text view ); 105

106 Output: Now run the App in AVD and you will see TimePicker on the screen. Change the time and it will be displayed as Toast and also in TextView. 106

107 CHAPTER-6 Data Storage 6.1 Introduction to Data Storage Data Store: Virtually every non-trivial application will have to store data in one way or another. This data can be of different forms, such as user settings, application settings, user data, images, or a cache of data fetched from the internet. Some apps might generate data that ultimately belongs to the user, and so, would prefer to store the data (perhaps documents or media) in a public place that the user can access at any time, using other apps. Other apps might want to store data, but do not want this data to be read by other apps (or even the user). The Android platform provides developers with multiple ways to store data, with each method having its advantages and disadvantages. For this article, we ll discuss the different data storage techniques available to Android developers, along with sample code to get you started, or to refresh your memory. Ways to store data There are basically four different ways to store data in an Android app: 1. Shared Preferences You should use this to save primitive data in key-value pairs. You have a key, which must be a String, and the corresponding value for that key, which can be one of: Boolean, float, int, long or string. Internally, the Android platform stores an app s Shared Preferences in an xml file in a private directory. An app can have multiple Shared Preferences files. Ideally, you will want to use Shared preferences to store application preferences. 2. Internal Storage There are lots of situations where you might want to persist data but Shared Preferences is too limiting. You may want to persist Java objects, or images. Or your data logically needs to be persisted using the familiar filesystem hierarchy. The Internal Storage data storage method is specifically for those situations where you need to store data to the device filesystem, but you do not want any other app (even the user) to read this data. Data stored using the Internal Storage 107

108 method is completely private to your application, and are deleted from the device when your app is uninstalled. 3. External Storage Conversely, there are other instances where you might want the user to view the files and data saved by your app, if they wish. To save (and/or read) files to the device s external storage, your app must request for the WRITE_EXTERNAL_STORAGE permission. If you only want to read from the External Storage without READ_EXTERNAL_STORAGEpermission. The writing,request for the WRITE_EXTERNAL_STORAGE permission grants both read/write access. However, beginning with Android 4.4, you can actually write to a private external storage folder without requesting WRITE_EXTERNAL_STORAGE. The private folder can be read by other applications and by the user, however, data stored in these folders are not scanned by the media scanner. This app_private folder is located in the Android/data directory, and is also deleted when your app is uninstalled. Beginning with Android 7.0, apps can request for access to a particular directory, rather than requesting for access to the entire external storage. This way, your app can, for example, request access to either the pictures directory only, or the documents directory. 4. SQLite database Finally, Android provides support for apps to use SQLite databases for data storage. Databases created are app specific, and are available to any class within the app, but not to outside applications. It goes without saying, that before you decide to use an SQLite database for data storage in your app, you should have some SQL knowledge. Using Shared Preferences To store data using shared preferences, you must first get a SharedPreferences object. There are two Context methods that can be used to retrieve a SharedPreferences object. SELECT ALL 108

109 SharedPreferences sharedpreferences = getpreferences (MODE_PRIVATE); For when your app will have a single preferences file, and SELECT ALL SharedPreferences sharedpreferences = getsharedpreferences (filenamestring, MODE_PRIVATE); For when your app could have multiple preferences files, or if you prefer to name your SharedPreferences instance. On getting the SharedPreferences object, you then access its Editor using the edit() method. To actually add a value, use the Editor s putxxx() method, where XXX is one of Boolean, String, Float, Long, Int or String Set. You can also remove a key-value preference pair with remove(). Finally, make sure to call the Editor s commit() method after putting or removing values. If you don t call commit, you changes will not be persisted. SELECT ALL SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putstring(keystring, valuestring); editor.commit(); For our sample app, we allow the user specify a SharedPreferences filename. If the user specifies a name, we request for the SharedPreferences having that name, if not, we request for the default Shared Preference object. JAVASCRIPTSELECT ALL 109

110 String filenamestring = sharedpreferencesbinding.filenameeditview.gettext().tostring(); SharedPreferences sharedpreferences; if(filenamestring.isempty()) { sharedpreferences = getpreferences(mode_private); else { sharedpreferences = getsharedpreferences(filenamestring, MODE_PRIVATE); Note that there is no method to get a list of all SharedPreferences files stored by your app. If you are going to store more than one SharedPreferences file, you should either have a static list, or be able to get the SharedPreferences name. On the other hand, you could save your SharedPreferences names in the default SharedPreferences file. To store user preferences, consider using a PreferenceActivity or PreferenceFragment, although they both use Shared Preferences to manage the user preference. 6.2 Internal & External Storage Internal Storage The Internal Storage is similar to saving to any other file system. You can get references to File objects, and you can store data of virtually any type using a FileOutputStream. The uniqueness of Internal Storage is simply that it s contents can be accessed by your app only. To get access to your internal file directory, use the Context getfilesdir() method. To create (or access) a directory within this internal file directory, use the getdir(directoryname, Context.MODE_XXX) method. The getdir() method returns a reference to a File object representing the specified directory, creating it first, if it doesn t exist. JAVASELECT ALL 110

111 File directory; if (filename.isempty()) { directory = getfilesdir(); else { directory = getdir(filename, MODE_PRIVATE); File[] files = directory.listfiles(); In the sample above, if the user specified filename is empty, we get the base internal storage directory. If the user specifies a name, we get the named directory, creating first if needed. To read files, use your preferred file reading method. For our sample, we read the complete file using a Scanner objects. To read a file that s directly within your internal storage directory (not in any subdirectory), you can use the openfileinput(filename) method. JAVASCRIPTSELECT ALL FileInputStreamfis = openfileinput(filename); Scanner scanner = newscanner(fis); scanner.usedelimiter("\\z"); String content = scanner.next(); scanner.close(); 111

112 Similarly, to access a file for writing that s directly within the Internal Storage directory, use the openfileoutput(filename) method. To save files, we use the FileOutputStream write. SELECT ALL FileOutputStreamfos = openfileoutput(filename, Context.MODE_PRIVATE); fos.write(internalstoragebinding.savefileedittext.gettext().tostring().getbytes()); fos.close(); You can see from the image above, that the filepath is in a folder that s not accessible by the device s file manager or any other apps (except for rooted devices). External Storage Using External Storage is identical to using Internal Storage and other filesystems. The difference here is that external storage devices can be removable drives, and the contents can be read by any and all apps. Since external storage can be removed and/or shared (mounted) with a computer or 112

113 in one of several other states, before writing to an external storage, your app should check for media availability. JAVASELECT ALL /* Checks if external storage is available for read and write */ Public boolean isexternalstoragewritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; return false; /* Checks if external storage is available to at least read */ Public boolean isexternalstoragereadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; return false; 113

114 Android has default folders for different types of data, such as PICTURES, MUSIC, RINGTONES and DOCUMENTS among others. For a complete list check out the Environmentapi. You should endeavour to store data in these directories if possible, depending on the data your app generates. For the snippet below, we save to either DOCUMENTS, PICTURES or MOVIES directory. JAVASELECT ALL /* Get one of DOCUMENTS, PICTURES or MOVIES * There are many others, including RINGTONES, ALARMS, MUSIC, etc which we ignore */ private String getdirectorytype() { intcheckedbutton = externalstoragebinding.filetypegroup.getcheckedradiobuttonid(); if (checkedbutton == externalstoragebinding.documentbutton.getid()) return Environment.DIRECTORY_DOCUMENTS; if (checkedbutton == externalstoragebinding.picturebutton.getid()) return Environment.DIRECTORY_PICTURES; return Environment.DIRECTORY_MOVIES; Files saved to the external storage can either be saved in a private space, which is deleted when the app is uninstalled, or in a public space, which is accessible to all files, and scanned by the media scanner. JAVASELECT ALL 114

115 /* Choose either a private folder (getexternalfilesdir()) * or public folder (getexternalstoragepublicdirectory()) */ private File gettargetfolder() { intcheckedbutton = externalstoragebinding.privateorpublicgroup.getcheckedradiobuttonid(); if (checkedbutton == externalstoragebinding.privatebutton.getid()) return getexternalfilesdir(getdirectorytype()); else return Environment.getExternalStoragePublicDirectory(getDirectoryType()); 115

116 It is entirely possible that some of the default directories have not been created on the user s device. It is a good idea to call mkdirs() before attempting to create (or save to) the final target file. SELECT ALL File targetfolder = gettargetfolder(); targetfolder.mkdirs(); At this point, you can write to (or read from) the file using your favorite File write/read methods. 6.3 SQLite database Android provides complete support for SQLite databases. The recommended way of creating SQLite databases is to subclass the SQLiteOpenHelper class, and override the oncreate() method. For this sample, we simply create a single table. Public class SampleSQLiteDBHelper extends SQLiteOpenHelper{ Private static final int DATABASE_VERSION = 2; Public static final String DATABASE_NAME = "sample_database"; Public static final String PERSON_TABLE_NAME = "person"; Public static final String PERSON_COLUMN_ID = "_id"; Public static final String PERSON_COLUMN_NAME = "name"; Public static final String PERSON_COLUMN_AGE = "age"; Public static final String PERSON_COLUMN_GENDER = "gender"; 116

117 Public SampleSQLiteDBHelper(Context context) { super(context, DATABASE_NAME, null, Public void oncreate(sqlitedatabasesqlitedatabase) { sqlitedatabase.execsql("create TABLE " + PERSON_TABLE_NAME + " (" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PERSON_COLUMN_NAME + " TEXT, " + PERSON_COLUMN_AGE + " INT UNSIGNED, " + PERSON_COLUMN_GENDER + " TEXT" + Public void onupgrade(sqlitedatabasesqlitedatabase, int i, int i1) { sqlitedatabase.execsql("drop TABLE IF EXISTS " + PERSON_TABLE_NAME); oncreate(sqlitedatabase); To add data: JAVASELECT ALL 117

118 Private void savetodb() { SQLiteDatabase database = newsamplesqlitedbhelper(this).getwritabledatabase(); ContentValues values = newcontentvalues(); values.put(samplesqlitedbhelper.person_column_name, activitybinding.nameedittext.gettext().tostring()); values.put(samplesqlitedbhelper.person_column_age, activitybinding.ageedittext.gettext().tostring()); values.put(samplesqlitedbhelper.person_column_gender, activitybinding.genderedittext.gettext().tostring()); longnewrowid = database.insert(samplesqlitedbhelper.person_table_name, null, values); Toast.makeText(this, "The new Row Id is " + newrowid, Toast.LENGTH_LONG).show(); To read data: JAVASCRIPTSELECT ALL Private void readfromdb() { String name = activitybinding.nameedittext.gettext().tostring(); String gender = activitybinding.genderedittext.gettext().tostring(); String age = activitybinding.ageedittext.gettext().tostring(); if(age.isempty()) 118

119 age = "0"; SQLiteDatabase database = newsamplesqlitedbhelper(this).getreadabledatabase(); String[] projection = { SampleSQLiteDBHelper.PERSON_COLUMN_ID, SampleSQLiteDBHelper.PERSON_COLUMN_NAME, SampleSQLiteDBHelper.PERSON_COLUMN_AGE, SampleSQLiteDBHelper.PERSON_COLUMN_GENDER ; String selection = SampleSQLiteDBHelper.PERSON_COLUMN_NAME + " like? and " + SampleSQLiteDBHelper.PERSON_COLUMN_AGE + " >?and " + SampleSQLiteDBHelper.PERSON_COLUMN_GENDER + " like?"; String[] selectionargs = {"%" + name + "%", age, "%" + gender + "%"; Cursor cursor = database.query( SampleSQLiteDBHelper.PERSON_TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionargs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups 119

120 null// don't sort ); Log.d("TAG", "The total cursor count is " + cursor.getcount()); activitybinding.recycleview.setadapter(newmyrecyclerviewcursoradapter(this, cursor)); Output: SQLite storage offers the power and speed of a full featured relational database to your app. If you intend to store data that needs to be queried, you should consider using the SQLite storage option. Watch out for our upcoming in-depth article on using sqlite storage in an android app. 120

121 CHAPTER-7 Menus & Dialogs 7.1 Introduction to Menus: Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to provide a dedicated Menu button. With this change, Android apps should migrate away from a dependence on the traditional 6-item menu panel and instead provide an app bar to present common user actions. Options menu The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose ," and "Settings." Context menu A context menu is that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame. Popup menu A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It's good for providing an overflow of actions that relate to specific content or to provide options for a second part of a command. Actions in a popup menu should not directly affect the corresponding content that's what contextual actions are for. Rather, the popup menu is for extended actions that relate to regions of content in your activity. Defining a Menu in XML For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You can then inflate the menu resource (load it as a menu object) in your activity or fragment. 121

122 Using a menu resource is a good practice for a few reasons: It's easier to visualize the menu structure in XML. It separates the content for the menu from your application's behavioural code. It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resource framework. To define the menu, create an XML file inside your projects res/menu/ directory and build the menu with the following elements: 7.2 Creating an Options Menu: The options menu is where you should include actions and other options that are relevant to the current activity context, such as "Search," "Compose ," and "Settings." Where the items in your options menu appear on the screen depends on the version for which you've developed your application. If you've developed your application for Android 2.3.x (API level 10) or lower, the contents of your options menu appear at the bottom of the screen when the user presses the menu button. If you've developed your application for Android 3.0(API level 10) and higher, items from the options menu are available in the app bar. Option Menu Example Let see the sample option menu example that contains four menu items. menu_main.xml It contains four items as show below. Menu_main.xml created automatically inside the res/menu directory, we need to add <item> under<menu> to describe id, icon and title. <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android=" <item android:id="@+id/item1" android:title="item 1"/> <item android:id="@+id/item2" android:title="item 2"/> <item android:id="@+id/item3" android:title="item 3"/> <item android:title="communicate"> <menu> <item android:id="@+id/nav_share" android:icon="@drawable/ic_menu_share" android:title="share" /> <item 122

123 android:title="send" /> </menu> </item> </menu> Note: We can create option menu with in an item. Activity class: This class displays the content of menu.xml file and performs event handling on clicking the menu items. When the user selects an item from the options menu (including action items in the app bar), the system calls your activity's onoptionsitemselected()method. This method passes the menu item selected. You can identify the item by calling getitemid(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method. You can match this ID against known menu items to perform the appropriate action. import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.view.view; import android.support.design.widget.navigationview; import android.support.v4.view.gravitycompat; import android.support.v4.widget.drawerlayout; import android.support.v7.app.actionbardrawertoggle; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.menu; import android.view.menuitem; import android.widget.toast; public class MainActivity extends AppCompatActivity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); Toolbar toolbar = (Toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); FloatingActionButton fab = (FloatingActionButton) findviewbyid(r.id.fab); fab.setonclicklistener(new View.OnClickListener() 123

124 public void onclick(view view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); ); DrawerLayout drawer = (DrawerLayout) findviewbyid(r.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setdrawerlistener(toggle); public void onbackpressed() { DrawerLayout drawer = (DrawerLayout) findviewbyid(r.id.drawer_layout); if (drawer.isdraweropen(gravitycompat.start)) { drawer.closedrawer(gravitycompat.start); else { public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return public boolean onoptionsitemselected(menuitem item) { int id = item.getitemid(); switch (item.getitemid()) { case R.id.item1: Toast.makeText(getApplicationContext(),"item1 selected",toast.length_long).show(); return true; case R.id.item2: Toast.makeText(getApplicationContext(),"item2 selected ",Toast.LENGTH_LONG).show(); return true; case R.id.item3: Toast.makeText(getApplicationContext(),"item3 selected ",Toast.LENGTH_LONG).show(); return true; Case R.id.Communicate: Toast.makeText(getApplicationContext(),"item4 selected ", Toast. LENGTH_LONG ).show(); return true; default: return super.onoptionsitemselected(item); 124

125 Output: Click Here we need to select menu item, based on selection it will perform action. Let s suppose we got selected item1 immediately it displays toast message like item1 selected. 125

126 We have menu item communicate if we select this we get again an option menu as shown below fig. 7.3 Creating Contextual Menus: A contextual menu offers actions that affect a specific item or context frame in the UI. You can provide a context menu for any view, but they are most often used for items in a ListView, GridView, or other view collections in which the user can perform direct actions on each item. There are two ways to provide contextual actions: In a floating context menu. A menu appears as a floating list of menu items (similar to a dialog) when the user performs a long-click (press and hold) on a view that declares support for a context menu. Users can perform a contextual action on one item at a time. 126

127 In the contextual action mode. This mode is a system implementation ofactionmode that displays a contextual action bar at the top of the screen with action items that affect the selected item(s). When this mode is active, users can perform an action on multiple items at once (if your app allows it). Note: The contextual action mode is available on Android 3.0 (API level 11) and higher and is the preferred technique for displaying contextual actions when available. If your app supports versions lower than 3.0 then you should fall back to a floating context menu on those devices. Context Menu Example Let's see the simple example of context menu in android. activity_main.xml Drag one list view from the pallete, now the xml file will look like this: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.coign.cmsample.mainactivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/textview" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_margintop="123dp" android:id="@+id/lv" /> </RelativeLayout> Activity class: The below class is used to Register the View to which the context menu should be associated by calling registerforcontextmenu(), Implement the oncreatecontextmenu() and to Implement oncontextitemselected(). package com.example.coign.cmsample; import android.support.v7.app.appcompatactivity; import android.os.bundle; 127

128 import android.widget.listview; import android.widget.toast; import android.widget.arrayadapter; import android.view.contextmenu; import android.view.contextmenu.contextmenuinfo; import android.view.menuitem; import android.view.view; public class MainActivity extends AppCompatActivity { ListView listview1; String protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); listview1=(listview)findviewbyid(r.id.lv); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts); listview1.setadapter(adapter); // Register the ListView for Context menu public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuinfo) { super.oncreatecontextmenu(menu, v, menuinfo); menu.setheadertitle("select The Action"); menu.add(0, v.getid(), 0, "Call"); menu.add(0, v.getid(), 0, public boolean oncontextitemselected(menuitem item){ if(item.gettitle()=="call"){ Toast.makeText(getApplicationContext(),"calling code",toast.length_long).show(); else if(item.gettitle()=="sms"){ Toast.makeText(getApplicationContext(),"sending sms code",toast.length_long).show(); else{ return false; return true; package com.example.coign.cmsample; 128

129 import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.widget.listview; import android.widget.toast; import android.widget.arrayadapter; import android.view.contextmenu; import android.view.contextmenu.contextmenuinfo; import android.view.menuitem; import android.view.view; public class MainActivity extends AppCompatActivity { ListView listview1; String protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); listview1=(listview)findviewbyid(r.id.lv); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts); listview1.setadapter(adapter); // Register the ListView for Context menu public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuinfo) { super.oncreatecontextmenu(menu, v, menuinfo); menu.setheadertitle("select The Action"); menu.add(0, v.getid(), 0, "Call"); menu.add(0, v.getid(), 0, public boolean oncontextitemselected(menuitem item){ if(item.gettitle()=="call"){ Toast.makeText(getApplicationContext(),"calling code",toast.length_long).show(); else if(item.gettitle()=="sms"){ Toast.makeText(getApplicationContext(),"sending sms code",toast.length_long).show(); else{ return false; return true; 129

130 In some cases in which the contextual actions provide common action items, you might want to add a checkbox or a similar UI element that allows users to select items, because they might not discover the long-click behaviour. When a user selects the checkbox, you can invoke the contextual action mode by setting the respective list item to the checked state with setitemchecked(). Output: When we perform a long-click (press and hold) on a view we will get a context menu. 130

131 Now we can select call or sms corresponding code will execute. 7.4 Creating a Popup Menu: A Popup Menu is a modal menu anchored to a View. It appears below the anchor view if there is room, or above the view otherwise. It's useful for: Providing an overflow-style menu for actions that relate to specific content (such as Gmail's headers, shown in figure 4). 131

132 Note: This is not the same as a context menu, which is generally for actions that affect selected content. For actions that affect selected content, use the contextual action mode or floating context menu. Providing a second part of a command sentence (such as a button marked "Add" that produces a popup menu with different "Add" options). Providing a drop-down similar to Spinner that does not retain a persistent selection. Note: PopupMenu is available with API level 11 and higher. Popup Menu Example Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. Let's see how to create popup menu in android. activity_main.xml It contains only one button. <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.coordinatorlayout xmlns:android=" xmlns:app=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" tools:context="com.example.coign.popmenu.mainactivity"> <android.support.design.widget.appbarlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/apptheme.appbaroverlay"> <android.support.v7.widget.toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionbarsize" android:background="?attr/colorprimary" app:popuptheme="@style/apptheme.popupoverlay" /> </android.support.design.widget.appbarlayout> <include layout="@layout/content_main" /> 132

133 <android.support.design.widget.floatingactionbutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom end" /> </android.support.design.widget.coordinatorlayout> popup_menu.xml It contains three items as show below. It is created inside the res/menu directory. <menu xmlns:android=" xmlns:app=" xmlns:tools=" tools:context="com.example.coign.popmenu.mainactivity"> <item android:title="one"/> <item android:title="two"/><item android:title="three"/> </menu> Activity class It displays the popup menu on button click. To perform an action when the user selects a menu item, you must implement the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by 133

134 calling setonmenuitemclicklistener(). When the user selects an item, the system calls the onmenuitemclick() callback in your interface. File: MainActivity.java package com.example.coign.popmenu; import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.view; import android.view.menu; import android.view.menuitem; import android.view.view.onclicklistener; import android.widget.button; import android.widget.popupmenu; import android.widget.toast; public class MainActivity extends AppCompatActivity { Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); Toolbar toolbar = (Toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); button1 = (Button) findviewbyid(r.id.button); button1.setonclicklistener(new OnClickListener() public void onclick(view v) { //Creating the instance of PopupMenu PopupMenu popup = new PopupMenu(MainActivity.this, button1); //Inflating the Popup using xml file popup.getmenuinflater().inflate(r.menu.menu_main, popup.getmenu()); //registering popup with OnMenuItemClickListener popup.setonmenuitemclicklistener(new PopupMenu.OnMenuItemClickListener() { public boolean onmenuitemclick(menuitem item) { Toast.makeText(MainActivity.this,"You Clicked : " + item.gettitle(),toast.length_short).show(); return true; ); popup.show();//showing popup menu );//closing the setonclicklistener method 134

135 FloatingActionButton fab = (FloatingActionButton) findviewbyid(r.id.fab); fab.setonclicklistener(new View.OnClickListener() public void onclick(view view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); ); Save the file and run your project. If everything works for you, the project will appear like this in your device. When we perform a long-click (press and hold) on a view we will get a popupmenu. 135

136 Based on our selection of popup menu outputs as follows. 7.5 Toolbar: A Toolbar is a generalization of action bars for use within application layouts. While an action bar is traditionally part of an Activity's opaque window decor controlled by the framework, a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. An application may choose to designate a Toolbar as the action bar for an Activity using the setactionbar () method. Toolbar supports a more focused feature set than ActionBar. From start to end, a toolbar may contain a combination of the following optional elements: 136

137 A navigation button. This may be an Up arrow, navigation menu toggle, close, collapse, done or another glyph of the apps choosing. This button should always be used to access other navigational destinations within the container of the Toolbar and its signified content or otherwise leave the current context signified by the Toolbar. The navigation button is vertically aligned within the Toolbar's minimum height, if set. A branded logo image. This may extend to the height of the bar and can be arbitrarily wide. A title and subtitle. The title should be a signpost for the Toolbar's current position in the navigation hierarchy and the content contained there. The subtitle, if present should indicate any extended information about the current content. If an app uses a logo image it should strongly consider omitting a title and subtitle. One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view's Toolbar.LayoutParams indicates a Gravity value of CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured. An action menu. The menu of actions will pin to the end of the Toolbar offering a few frequent, important or typical actions along with an optional overflow menu for additional actions. Action buttons are vertically aligned within the Toolbar's minimum height, if set. In modern Android UIs developers should lean more on a visually distinct color scheme for toolbars than on their application icon. The use of application icon plus title as a standard layout is discouraged on API 21 devices and newer. We are going to change our parent theme for our application to Theme.AppCompat.Light.NoActionBar in our project styles.xml file location in the resource folder. NoActionBar implies that our theme will not have any ActionBar. That will give so the room so that we can replace the ActionBar with the ToolBar ViewGroup. We are going to add color resources in colors.xml file. If you don t have this file in your resources folder, kind creates it. In Material Design, there are three important colors necessary for app design. 1. Color Primary The primary color of your application. This color will form the background color for our ToolBar. 2. Color Primary Dark The dark version of the primary color is usually use for the status bar. This will afford a slight distinction between the StatusBar and ToolBar 3. Accent Color Accent colors are colors that are used for emphasis in a color scheme. These color resources areadded to the style which will be used in our app. The colors.xml code snippet is shown below. <?xml version="1.0" encoding="utf-8"?> <resources> <color name="color_primary">#2196f3</color> 137

138 <color name="color_primary_dark">#1976d2</color> <color name="accent_color">#536dfe</color> </resources> The corresponding styles.xml file code is as shown. <resources> <!-- Base application theme. --> Vc <style name="apptheme" parent="theme.appcompat.light.noactionbar"> <!-- Customize your theme here. --> <item <item <item </style> </resources> The strings.xml resources that holds reference to our application string resources is as shown below. <resources> <string name="app_name">android Toolbar</string> <string name="action_settings">settings</string> <string name="action_refresh">settings</string> <string name="action_new">settings</string> <string name="logo_desc">app logo</string> </resources> 138

139 Now, let s focus our attention on how to create our ToolBar ViewGroup. Since the ToolBar is in the support library, open your activity_main.xml file and add the following code to your layout file. <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <android.support.v7.widget.toolbar android:id="@+id/toolbar" android:minheight="?attr/actionbarsize" android:background="@color/color_primary" android:layout_width="match_parent" android:layout_height="64dp"> </android.support.v7.widget.toolbar> </RelativeLayout> We will ahead over to our MainActivity.java file to instantiate an object of the ToolBar. This is done with the Activity class method findviewbyid(int resourcesid). The resources ID is the corresponding Id of the ToolBar. Once we have an instance of the ToolBar, we will call the setsupportactionbar (top Toolbar) and pass our ToolBar object to it. The complete code for the class is shown below. Note that we have add our app logo brand by calling toptoolbar.setlogo(r.drawable.logo) with and image resources id. package coign.com.androidtoolbarexample; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.menu; import android.view.menuitem; 139

140 import android.support.v7.widget.toolbar; import android.widget.toast; publicclassmainactivityextendsactionbaractivity ProtectedvoidonCreate(Bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); settitle(null); Toolbar toptoolbar = (Toolbar)findViewById(R.id.toolbar); setsupportactionbar(toptoolbar); toptoolbar.setlogo(r.drawable.logo); PublicbooleanonCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.menu_main, menu); PublicbooleanonOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getitemid(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { returntrue; if(id == R.id.action_refresh){ Toast.makeText(MainActivity.this, "Refresh App", Toast.LENGTH_LONG).show(); if(id == R.id.action_new){ Toast.makeText(MainActivity.this, "Create Text", Toast.LENGTH_LONG).show(); Returnsuper.onOptionsItemSelected(item); Finally, we added some action view in our Toolbar by updating our project menu_main.xml file. The update version of the file is as shown. <menu xmlns:android=" 140

141 xmlns:app=" xmlns:tools=" tools:context=".mainactivity"> <item android:orderincategory="100" app:showasaction="never" /> <item android:orderincategory="200" app:showasaction="ifroom" /> <item android:orderincategory="300" app:showasaction="ifroom" /> </menu> Save the file and run your project. If everything works for you, the project will appear like this in your device. 141

142 Toolbar 7.6 Alert Dialog Box: A Dialog is small window that prompts the user to a decision or enter additional information. Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog. In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below. AlertDialog. Builder alertdialogbuilder =newalertdialog. Builder (this); Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class. Its syntax is alertdialogbuilder.setpositivebutton(charsequence text, DialogInterface.OnClickListener listener) alertdialogbuilder.setnegativebutton(charsequence text, DialogInterface.OnClickListener listener) 142

143 Apart from this, you can use other functions provided by the builder class to customize the alert dialog. Understand the basic structure of an AlertDialog. An AlertDialog is when the Android app uses the Android system to put up important information for a user to read. An AlertDialog can also be used to warn or ask the user to change an important setting. It will contain three components of the dialog box. A title is optional but can be useful to put in a simple message or question. This can also contain an icon The content area which can display a message, list or other custom layout functions. Action buttons that are used for the user to send a response to the AlertDialog box. Can be a positive button, a negative button or a neutral button. You can only have one of each type and up to three buttons on a given alert dialog. Decide on the purpose of the AlertDialog. What is the purpose of the AlertDialog box? What are the options going to be for the user? Is it possible that the user would ignore this process otherwise? Write down what the user will be prompted for and note their choices and what they do. If the writing seems unclear for the user, they may not understand the purpose of the AlertDialog box. Android AlertDialog is composed of three regions: title, content area and action buttons. AlertDialog Example Let's see a simple example of android alert dialog. activity_main.xml You can have multiple components here we are having only a textview. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.user.alertdialog.mainactivity"> <TextView 143

144 android:text="textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> </RelativeLayout> strings.xml Optionally, you can store the dialog message and title in the strings.xml file. <resources> <string name="app_name">alertdialog</string> <string name="hello_world">hello world!</string> <string name="menu_settings">settings</string> <string name="dialog_message">welcome to Alert Dialog</string> <string name="dialog_title"> Alert Dialog</string> </resources> Activity class: import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.os.bundle; import android.app.activity; import android.app.alertdialog; import android.content.dialoginterface; public class MainActivity extends AppCompatActivity 144

145 protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setmessage("do you want to close this application?").setcancelable(false).setpositivebutton("yes", new DialogInterface.OnClickListener() public void onclick(dialoginterface dialog, int id) { finish(); ).setnegativebutton("no", new DialogInterface.OnClickListener() public void onclick(dialoginterface dialog, int id) { dialog.cancel(); ); AlertDialog alert = builder.create(); alert.settitle("alertdialogexample"); alert.show(); setcontentview(r.layout.activity_main); { Output : 145

146 7.7 DialogFragment: We will learn how to implement a Dialog Fragment in your Android application. A Dialog Fragment is a fragment that displays a dialog window, floating on top of its activity s window. This fragment contains a Dialog object, which it displays as appropriate, based on the fragment s state. Alternatively, you can create an entirely custom dialog, such as an AlertDialog, with its own content. We will create buttons that will show a DialogFragment and a custom Alert DialogFragment. MainActivity.java package com.example.user.dialogfragment1; import android.os.bundle; import android.support.v4.app.dialogfragment; import android.support.v4.app.fragmentactivity; import android.support.v4.app.fragmentmanager; import android.support.v7.app.alertdialog; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; public class MainActivity extends FragmentActivity { FragmentManager fm = protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final Button dfragbutton=(button) findviewbyid(r.id.dfragbutton); final Button alertdfragbutton=(button)findviewbyid(r.id.alertdfragbutton); 146

147 dfragbutton.setonclicklistener(new View.OnClickListener() public void onclick(view arg0) { DFragment dfragment=new DFragment(); dfragment.show(fm,"dialog Fragment"); ); alertdfragbutton.setonclicklistener(new View.OnClickListener() public void onclick(view arg0) { AlertDFragment alertdfragment=new AlertDFragment(); alertdfragment.show(fm, "Alert Dialog Fragment"); ); In this activity, we have created two buttons that will show different dialog fragments. The first button will show a simple DialogFragment and another with a custom Alert DialogFragment. Next, create an XML graphical layout for the MainActivity. Go to res > layout > Right Click on layout > New > Android XML File activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.user.dialogfragment1.mainactivity"> <Button 147

148 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" /> </RelativeLayout> Next, create a fragment. Go to File > New > Class and name it DFragment.java. Select your package. DFragment.java package com.example.user.dialogfragment1; import android.support.v4.app.dialogfragment; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import java.util.zip.inflater; public class DFragment extends DialogFragment { 148

149 @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { View rootview = inflater.inflate(r.layout.dialogfragment, container, false); getdialog().settitle("dialogfragment Tutorial "); // Do something else return rootview; Next, create an XML graphical layout for the DialogFragment. Go to res > layout > Right Click on layout > New > Android XML File Name your new XML file dialogfragment.xml. dialogfragment.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" android:padding="10dp" android:text="@string/welcome" /> </RelativeLayout> 7.8 steps to create Dialog Using Dialog Fragment 149

150 create another fragment. Go to File > New > Class and name it AlertDFragment.java. Select your package. Open your AlertDFragment.java. AlertDFragment.java package com.example.user.dialogfragment1; import android.app.dialog; import android.content.dialoginterface; import android.os.bundle; import android.support.annotation.nonnull; import android.support.v4.app.dialogfragment; import android.support.v7.app.alertdialog; public class AlertDFragment extends public Dialog oncreatedialog(bundle savedinstancestate) { return new AlertDialog.Builder(getActivity()) // Set Dialog Icon.setIcon(R.drawable.desert) // Set Dialog Title.setTitle("Alert DialogFragment") // Set Dialog Message.setMessage("Alert DialogFragment Tutorial").setPositiveButton("ok", new DialogInterface.OnClickListener() public void onclick(dialoginterface dialog, int which) { 150

151 ).setnegativebutton("cancel", new DialogInterface.OnClickListener() public void onclick(dialoginterface dialog, int which) { ).create(); In this fragment, we have created custom alert DialogFragment that consist of two buttons, a positive and negative. We have prepared a sample alert dialog icon for this tutorial. Insert your downloaded sample alert dialog icon into your res > drawable-hdpi. Sample Alert Dialog Icon Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code. strings.xml <resources> <string name="app_name">dialogfragment Tutorial</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> <string name="welcome">this is a DialogFragment.</string> <string name="dialogfragment">open DialogFragment</string> <string name="alertdialogfragment">open Alert DialogFragment</string> </resources> Output: 151

152 Now we have two options if we click open DialogFragment next step as follows. If we click openalertdialogfragment next step as follows. 152

153 Here cancel and ok are positive and negative Buttons and corresponding code will execute when we select cancel or ok. CHAPTER Animations in Android Android Animation Android Animation is used to give the UI a rich look and feel. Animations in android apps can be performed through XML or android code. In this android animation tutorial we ll go with XML codes for adding animations into our application. 8.2 Types of Animations Animation in android apps is the process of creating motion and shape change. The basic ways of animation are shown below: 1. Fade In Animation 2. Fade Out Animation 3. Cross Fading Animation 4. Blink Animation 153

154 5. Zoom In Animation 6. Zoom Out Animation 7. Rotate Animation 8. Move Animation 9. Slide Up Animation 10. Slide Down Animation 11. Bounce Animation 12. Sequential Animation 13. Together Animation Android Animation Example XML We create a resource directory under the res folder names anim to keep all the xml files containing the animation logic. Following is a sample xml file showing an android animation code logic. Sample_animation.xml <?xml version="1.0" encoding="utf-8"?> <scale xmlns:android=" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:duration="300" android:fillafter="true" android:fromxscale="0.0" android:fromyscale="0.0" android:toxscale="1.0" android:toyscale="1.0" /> android:interpolator : It is the rate of change in animation. We can define our own interpolators using the time as the constraint. In the above xml code an inbuilt interpolator is assigned android:duration : Duration of the animation in which the animation should complete. It is 300ms here. This is generally the ideal duration to show the transition on the screen. 154

155 The start and end of the animation are set using: android:fromtransformation android:totransformation TRANSFORMATION : is the transformation that we want to specify. In our case we start with an x and y scale of 0 and end with an x and y scale of 1 android:fillafter : property specifies whether the view should be visible or hidden at the end of the animation. We ve set it visible in the above code. If it sets to false, the element changes to its previous state after the animation android:startoffset : It is the waiting time before an animation starts. This property is mainly used to perform multiple animations in a sequential manner android:repeatmode : This is useful when you want the animation to be repeat android:repeatcount : This defines number of repetitions on animation. If we set this value to infinite then animation will repeat infinite times Loading Animation when UI widget is clicked Our aim is to show an animation when any widget(lets say TextView) is clicked. For that we need to use the Animation Class. The xml file that contains the animation logic is loaded using AnimationUtils class by calling the loadanimation() function. The below snippet shows this implementation. Animationanimation; animation=animationutils.loadanimation(getapplicationcontext(), R.anim.sample_animation); To start the animation we need to call the startanimation() function on the UI element as shown in the snippet below: sampletextview.startanimation(animation); Here we perform the animation on a textview component by passing the type of Animation as the parameter. 155

156 Setting the Animation Listeners This is only needed if we wish to listen to events like start, end or repeat. For this the activity must implement AnimationListener and the following methods need to overridden. onanimationstart : This will be triggered once the animation started onanimationend : This will be triggered once the animation is over onanimationrepeat : This will be triggered if the animation repeats Android Animation Project Structure As you can see, we ve included the xml of all the major types of animations covered above. Android Animation Examples XML Code Here I am providing sample code for most of the common android animations. Fade In Animation fade_in.xml 156

157 <setxmlns:android=" android:fillafter="true"> <alpha android:duration="1000" android:fromalpha="0.0" android:toalpha="1.0"/> </set> Here alpha references the opacity of an object. An object with lower alpha values is more transparent, while an object with higher alpha values is less transparent, more opaque. Fade in animation is nothing but increasing alpha value from 0 to 1. Fade Out Animation fade_out.xml <setxmlns:android=" android:fillafter="true"> <alpha android:duration="1000" android:fromalpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:toalpha="0.0"/> </set> 157

158 Fade out android animation is exactly opposite to fade in, where we need to decrease the alpha value from 1 to 0. Cross Fading Animation Cross fading is performing fade in animation on one TextView while other TextView is fading out. This can be done by using fade_in.xml and fade_out.xml on the two TextViews. The code will be discussed in the MainActivity.java Blink Animation blink.xml <setxmlns:android=" <alphaandroid:fromalpha="0.0" android:toalpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="600" android:repeatmode="reverse" android:repeatcount="infinite"/> </set> Here fade in and fade out are performed infinitely in reverse mode each time. Zoom In Animation zoom_in.xml <setxmlns:android=" android:fillafter="true"> <scale 158

159 xmlns:android=" android:duration="1000" android:fromxscale="1" android:fromyscale="1" android:pivotx="50%" android:pivoty="50%" android:toxscale="3" android:toyscale="3"> </scale> </set> We use pivotx="50%" andpivoty="50%" to perform zoom from the center of the element. Zoom Out Animation zoom_out.xml <setxmlns:android=" android:fillafter="true"> <scale xmlns:android=" android:duration="1000" android:fromxscale="1.0" android:fromyscale="1.0" android:pivotx="50%" android:pivoty="50%" android:toxscale="0.5" android:toyscale="0.5"> 159

160 </scale> </set> Notice that android:from and android:to are opposite inzoom_in.xml andzoom_out.xml. Rotate Animation rotate.xml <set xmlns:android=" <rotate android:fromdegrees="0" android:todegrees="360" android:pivotx="50%" android:pivoty="50%" android:duration="600" android:repeatmode="restart" android:repeatcount="infinite" </set> A from/todegrees tag is used here to specify the degrees and a cyclic interpolator is used. Move Animation move.xml <set xmlns:android=" 160

161 android:fillafter="true"> <translate android:fromxdelta="0%p" android:toxdelta="75%p" android:duration="800"/> </set> Slide Up Animation slide_up.xml <setxmlns:android=" android:fillafter="true"> <scale android:duration="500" android:fromxscale="1.0" android:fromyscale="1.0" android:toxscale="1.0" android:toyscale="0.0"/> </set> It s achieved by setting android:fromyscale= 1.0 and android:toyscale= 0.0 inside the scale tag. Slide Down Animation slide_down.xml 161

162 <setxmlns:android=" android:fillafter="true"> <scale android:duration="500" android:fromxscale="1.0" android:fromyscale="0.0" android:toxscale="1.0" android:toyscale="1.0"/> </set> This is just the opposite of slide_up.xml. Bounce Animation bounce.xml <setxmlns:android=" android:fillafter="true" <scale android:duration="500" android:fromxscale="1.0" android:fromyscale="0.0" android:toxscale="1.0" android:toyscale="1.0"/> 162

163 </set> Here bounce interpolator is used to complete the animation in bouncing fashion. Sequential Animation sequential.xml <setxmlns:android=" android:fillafter="true" <!-- Move --> <translate android:duration="800" android:fillafter="true" android:fromxdelta="0%p" android:startoffset="300" android:toxdelta="75%p"/> <translate android:duration="800" android:fillafter="true" android:fromydelta="0%p" android:startoffset="1100" android:toydelta="70%p"/> <translate android:duration="800" android:fillafter="true" 163

164 android:fromxdelta="0%p" android:startoffset="1900" android:toxdelta="-75%p"/> <translate android:duration="800" android:fillafter="true" android:fromydelta="0%p" android:startoffset="2700" android:toydelta="-70%p"/> <!-- Rotate 360 degrees --> <rotate android:duration="1000" android:fromdegrees="0" android:pivotx="50%" android:pivoty="50%" android:startoffset="3800" android:repeatcount="infinite" android:repeatmode="restart" android:todegrees="360"/> </set> Here a different android:startoffset is used from the transitions to keep them sequential. Together Animation together.xml <setxmlns:android=" 164

165 android:fillafter="true" <!-- Move --> <scale xmlns:android=" android:duration="4000" android:fromxscale="1" android:fromyscale="1" android:pivotx="50%" android:pivoty="50%" android:toxscale="4" android:toyscale="4"> </scale> <!-- Rotate 180 degrees --> <rotate android:duration="500" android:fromdegrees="0" android:pivotx="50%" android:pivoty="50%" android:repeatcount="infinite" android:repeatmode="restart" android:todegrees="360"/> </set> Here android:startoffset is removed to let them happen simultaneously. 8.3 Animation Implementation 165

166 The activity_main.xml layout consists of a ScrollView and RelativeLayout (we ll discuss this in a later tutorial) in which every animation type is invoked on the text using their respective buttons. The xml file is shown below : activity_main.xml <ScrollViewxmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btnfadein" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="fade In" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="fade In" android:id="@+id/txt_fade_in" android:layout_alignbottom="@+id/btnfadein" 166

167 /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="fade Out" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="cross Fade" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="cross Fade In" 167

168 android:visibility="gone" android:layout_gravity="center_horizontal" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="blink" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="zoom In" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" 168

169 android:text="blink" android:layout_gravity="center_horizontal" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="zoom Out" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="rotate" /> <Button android:layout_width="wrap_content" 169

170 android:layout_height="wrap_content" android:layout_margin="5dp" android:text="move" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="slide Up" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="fade Out" android:layout_gravity="center_horizontal" /> <Button 170

171 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="slide Down" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="bounce" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="sequential Animation" /> <Button 171

172 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="together Animation" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="cross Fade Out" android:layout_gravity="center_horizontal" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="zoom In" 172

173 /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="zoom Out" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="rotate" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" 173

174 android:textappearance="?android:attr/textappearancemedium" android:text="move" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="slide Up" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="slide Down" 174

175 /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="bounce" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="sequential" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" 175

176 android:text="together" /> </RelativeLayout> </ScrollView> To sum up, a RelativeLayout, as the name suggests the arrangement of UI Components is relative to each other. The MainActivity.java file contains the onclick Listeners for every button related to its animation type. It s source code is given below. packagecom.journaldev.animations; importandroid.app.activity; importandroid.content.intent; importandroid.os.bundle; importandroid.view.view; importandroid.view.animation.animation; importandroid.view.animation.animationutils; importandroid.widget.button; importandroid.widget.textview; public class MainActivity extends Activity { 176

177 Button btnfadein, btnfadeout, btncrossfade, btnblink, btnzoomin, btnzoomout, btnrotate, btnmove, btnslideup, btnslidedown, btnbounce, btnsequential, btntogether; Animation animfadein,animfadeout,animblink,animzoomin,animzoomout,animrotate, animmove,animslideup,animslidedown,animbounce,animsequential,animtogether,anim CrossFadeIn,animCrossFadeOut; TextView txtfadein,txtfadeout,txtblink,txtzoomin,txtzoomout,txtrotate,txtmove,txtslideup, protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); btnfadein = (Button) findviewbyid(r.id.btnfadein); btnfadeout = (Button) findviewbyid(r.id.btnfadeout); btncrossfade = (Button) findviewbyid(r.id.btncrossfade); btnblink = (Button) findviewbyid(r.id.btnblink); btnzoomin = (Button) findviewbyid(r.id.btnzoomin); btnzoomout = (Button) findviewbyid(r.id.btnzoomout); btnrotate = (Button) findviewbyid(r.id.btnrotate); btnmove = (Button) findviewbyid(r.id.btnmove); btnslideup = (Button) findviewbyid(r.id.btnslideup); btnslidedown = (Button) findviewbyid(r.id.btnslidedown); 177

178 btnbounce = (Button) findviewbyid(r.id.btnbounce); btnsequential = (Button) findviewbyid(r.id.btnsequential); btntogether = (Button) findviewbyid(r.id.btntogether); txtfadein=(textview)findviewbyid(r.id.txt_fade_in); txtfadeout=(textview)findviewbyid(r.id.txt_fade_out); txtblink=(textview)findviewbyid(r.id.txt_blink); txtzoomin=(textview)findviewbyid(r.id.txt_zoom_in); txtzoomout=(textview)findviewbyid(r.id.txt_zoom_out); txtrotate=(textview)findviewbyid(r.id.txt_rotate); txtmove=(textview)findviewbyid(r.id.txt_move); txtslideup=(textview)findviewbyid(r.id.txt_slide_up); txtslidedown=(textview)findviewbyid(r.id.txt_slide_down); txtbounce=(textview)findviewbyid(r.id.txt_bounce); txtseq=(textview)findviewbyid(r.id.txt_seq); txttog=(textview)findviewbyid(r.id.txt_tog); txtin=(textview)findviewbyid(r.id.txt_in); txtout=(textview)findviewbyid(r.id.txt_out); animfadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in); animfadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in); // fade in btnfadein.setonclicklistener(new View.OnClickListener() 178

179 public void onclick(view v) { txtfadein.setvisibility(view.visible); txtfadein.startanimation(animfadein); ); animfadeout = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out); // fade out btnfadeout.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtfadeout.setvisibility(view.visible); txtfadeout.startanimation(animfadeout); ); animcrossfadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in); animcrossfadeout = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out); // cross fade btncrossfade.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtout.setvisibility(view.visible); // start fade in animation 179

180 txtout.startanimation(animcrossfadein); // start fade out animation txtin.startanimation(animcrossfadeout); ); animblink = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink); // blink btnblink.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtblink.setvisibility(view.visible); txtblink.startanimation(animblink); ); animzoomin = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_in); // Zoom In btnzoomin.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtzoomin.setvisibility(view.visible); txtzoomin.startanimation(animzoomin); 180

181 ); animzoomout = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_out); // Zoom Out btnzoomout.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtzoomout.setvisibility(view.visible); txtzoomout.startanimation(animzoomout); ); animrotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate); // Rotate btnrotate.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtrotate.startanimation(animrotate); ); animmove = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move); // Move btnmove.setonclicklistener(new View.OnClickListener() 181

182 public void onclick(view v) { txtmove.startanimation(animmove); ); animslideup = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up); // Slide Up btnslideup.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtslideup.startanimation(animslideup); ); animslidedown = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down); // Slide Down btnslidedown.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtslidedown.startanimation(animslidedown); ); animbounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce); // Slide Down 182

183 btnbounce.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtbounce.startanimation(animbounce); ); animsequential = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.sequential); // Sequential btnsequential.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txtseq.startanimation(animsequential); ); animtogether = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.together); // Together btntogether.setonclicklistener(new View.OnClickListener() public void onclick(view v) { txttog.startanimation(animtogether); ); 183

184 As discussed before each textview animation is started by invoking the respective animation object in which the animation logic is loaded by AnimationUtils.loadAnimation() method. The crossfade animation consists of two TextViews in which one fades out and the other fades in. Below image showing all the animations in our application. Output: The together animation is seen in the image above. Note that this animation when run on an emulator won t be smooth, so it s recommended to run the application on a normal device. 184

185 8.4 Introduction to Threads Threads have been an essential part of computer science and a versatile tool for programmers for decades. Most modern operating systems support threads, and Android is no exception. Android s support for threads enables programmers to split their programs into multiple units that execute commands and instructions in parallel. A thread is the smallest unit of processing that can be scheduled by an operating system. Your app s main process (or program) can be broken into threads, which can then be scheduled simultaneously by the operating system. This method helps the programmer take care of longer processes in a separate thread, so that the main thread (in which the UI is running) remains quick and responsive to the user. Main Thread and Background Threads Whenever we create an activity, it runs by default in the main thread of your application. All the commands issued by the Android operation system (like onclick, oncreate, etc.) are sent to and processed by this main thread. But, if you include all of your processing logic in the main thread, your application might not be too busy to respond to the messages sent by the Android operating system. This might even make your application completely unresponsive, which would prompt Android to display the warning of application not responding and shut down your app by force. To prevent this problem, it s good practice to perform all the tasks that might take a long time in a separate background thread rather than in the main thread. This would leave the main thread free to remain responsive to the user input sent by the Android operating system. One notable downside to this method is that the UI cannot be updated from the background thread, it has to be updated from the main thread. But, with a little planning ahead, this issue can be easily remedied. Create a Splash UI Application: Android splash screen are normally used to show user some kind of progress before the app loads completely. Some people uses splash screen just to show case their app / company logo 185

186 for a couple of second. Unfortunately in android we don t have any inbuilt mechanism to show splash screen compared to ios. In this tutorial we are going to learn how to implement splash screen in your android application Android Splash Screen Using Timer create a new project in Eclipse by navigation to File => New Android => Application Project and fill required details. For Splash Screen we are creating a separate activity. Create a new class in your package and name it as SplashScreen.java Open your your AndroidManifest.xml file and make your splash screen activity as Launcher activity. AndroidManifest.xml <?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android=" package="info.androidhive.androidsplashscreentimer" android:versioncode="1" android:versionname="1.0"> <uses-sdk android:minsdkversion="8" android:targetsdkversion="17"/> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" 186

187 <!-- Splash screen --> <activity android:name="info.androidhive.androidsplashscreentimer.splashscreen" android:screenorientation="portrait" <intent-filter> <actionandroid:name="android.intent.action.main"/> <categoryandroid:name="android.intent.category.launcher"/> </intent-filter> </activity> <!-- Main activity --> <activity android:name="info.androidhive.androidsplashscreentimer.mainactivity" </activity> </application> </manifest> 4. Create a layout file for splash screen underres => layout folder. I named the layout file asactivity_splash.xml. This layout normally contains your app logo or company logo. activity_splash.xml 187

188 <?xmlversion="1.0"encoding="utf-8"?> <RelativeLayoutxmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginbottom="10dp" android:textsize="12dp" android:textcolor="#454545" android:gravity="center_horizontal" android:layout_alignparentbottom="true" android:text=" </RelativeLayout> 188

189 5. Add the following code insplashscreen.java activity. In this following code a handler is used to wait for specific time and once the timer is out we launched main activity. SplashScreen.java packageinfo.androidhive.androidsplashscreentimer; importandroid.app.activity; importandroid.content.intent; importandroid.os.bundle; importandroid.os.handler; publicclasssplashscreen extendsactivity { // Splash screen timer privatestaticintsplash_time_out = ProtectedvoidonCreate(Bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_splash); newhandler().postdelayed(newrunnable() { /* * Showing splash screen with a timer. This will be useful when you * want to show case your app logo / company Publicvoidrun() { // This method will be executed once the timer is over 189

190 // Start your app main activity Intent i = newintent(splashscreen.this, MainActivity.class); startactivity(i); // close this activity finish();, SPLASH_TIME_OUT); Run the application, you will see the splash screen for 3 sec and then your main activity will be launched. CHAPTER Broadcast Receiver A broadcast receiver is an Android component which allows registering and listening for device orientation changes like sms received, phone call received/pick/cut, battery status changed,the Wi-Fi came on. Android operating system and even other applications time to time broadcast messages about things that are happening like sms received, phone call received/pick/cut, battery status changed, the Wi-Fi came on. With the help of broadcast receiver you will catch Android operating system specific events and then you can code your application for that event. Where we use: Example: We want when any call will come then we will save call details in our SQLite database. How to do: We will define a broadcast receiver which listens to telephone state changes. If 190

191 the phone receives a phone call then our receiver will be notified and save call data to SQLite database. How to create broadcast receiver: There are two way to register and create a broadcast receiver First Way: Register broadcast receiver Via the AndroidManifest.xml file. <receiver android:name="incomingcall"> <intent-filter> <action android:name="android.intent.action.phone_state" /> </intent-filter> </receiver> When android.intent.action.phone_state Event will fire ( call received/pick/end ), then onreceive method in IncomingCall.java file will automatically call. Now Create IncomingCall.java file // Reciever class which extends BroadcastReceiver public class IncomingCall extends BroadcastReceiver { public void onreceive(context context, Intent intent) { // Phone call state change then this method will automaticaly called Second Way: Register broadcast receiver Via dynamically ( Run time ) // Create reciever object private BroadcastReceiverthe_receiver = new IncomingCall(); // Set When broadcast event will fire. private IntentFilter filter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED); // Register new broadcast receiver 191

192 this.registerreceiver(the_receiver, filter); // Reciever class which extends BroadcastReceiver public class IncomingCall extends BroadcastReceiver { public void onreceive(context context, Intent intent) { // Phone call state change then this method will automaticaly called Create Custom events and broadcast receiver: Define Broadcast Receiver in AndroidManifest.xml file to a Custom action. Custom action - define any user specific name event will broadcast with that name. <receiver android:name="myreceiver" > <intent-filter> <action android:name="ax.androidexample.mybroadcast" /> </intent-filter> </receiver> Create recieverclass : // Reciever class which extends BroadcastReceiver public class MyReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { // Phone call state change then this method will automaticaly called Send Broadcast event : Create new intent and broadcast it Intent intent = new Intent(); intent.setaction("ax.androidexample.mybroadcast"); 192

193 sendbroadcast(intent); 9.2 Phone Events: There are several system generated events defined as final static fields in the Intent class. The following table lists a few important system events. Sr.No Event Constant & Description android.intent.action.battery_changed 1 Sticky broadcast containing the charging state, level, and other information about the battery. android.intent.action.battery_low 2 Indicates low battery condition on the device. android.intent.action.battery_okay 3 Indicates the battery is now okay after being low. android.intent.action.boot_completed 4 This is broadcast once, after the system has finished booting. android.intent.action.bug_report 5 Show activity for reporting a bug. android.intent.action.call 6 7 Perform a call to someone specified by the data. android.intent.action.call_button 193

194 The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. android.intent.action.date_changed 8 The date has changed. android.intent.action.reboot 9 Have the device reboot. What are we going to develop? A simple application which displays the % of charge available in your devices battery. Progress bar will be used to display the % of battery. Project Structure Create new android project [File >> New >> Android Project] with project name broadcast Click next and select target android device version Click next and enter package name com.example.coign.broadcast Click finish Layout XML: In the res/layout folder, we will create a simple layout for our application which has a text view to display the % of Battery in words and Progress bar to display the % of Battery graphically. activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" 194

195 android:orientation="vertical" > <TextView android:layout_margintop="40dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="20dip" android:layout_gravity="center" android:minwidth="200dip" android:minheight="100dip" android:max="100" style="?android:attr/progressbarstylehorizontal"/> </LinearLayout> As we are done with layout, let us turn towards application logic. MainActivity.java package com.example.coign.broadcast; importandroid.content.broadcastreceiver; importandroid.content.context; importandroid.content.intent; importandroid.content.intentfilter; import android.support.v7.app.appcompatactivity; importandroid.os.bundle; importandroid.widget.progressbar; importandroid.widget.textview; public class MainActivity extends AppCompatActivity { privatebroadcastreceiverbr=new BroadcastReceiver() 195

196 public void onreceive(context c, Intent i) { int level=i.getintextra("level",0); ProgressBarpb=(ProgressBar)findViewById(R.id.progressbar); pb.setprogress(level); TextViewtv=(TextView)findViewById(R.id.textfield); tv.settext("battery Level" + Integer.toString(level) + "%"); protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); registerreceiver(br,newintentfilter(intent.action_battery_changed)); OUTPUT: Let us test the application: Right click on the project >> Run as >> Android application >> choose emulator or device 196

197 CHAPTER Introduction to Content Provider A content provider manages access to a central repository of data. You implement a provider as one or more classes in an Android application, along with elements in the manifest file. One of your classes implements a subclass ContentProvider, which is the 197

198 interface between your provider and other applications. Although content providers are meant to make data available to other applications, you may of course have activities in your application that allow the user to query and modify the data managed by your provider. Implementing the ContentProvider Class The ContentProvider instance manages access to a structured set of data by handling requests from other applications. All forms of access eventually call ContentResolver, which then calls a concrete method of ContentProvider to get access. Required methods The abstract class ContentProvider defines six abstract methods that you must implement as part of your own concrete subclass. All of these methods except oncreate() are called by a client application that is attempting to access your content provider: query() Retrieve data from your provider. Use the arguments to select the table to query, the rows and columns to return, and the sort order of the result. Return the data as a Cursor object. insert() Insert a new row into your provider. Use the arguments to select the destination table and to get the column values to use. Return a content URI for the newly-inserted row. update() Update existing rows in your provider. Use the arguments to select the table and rows to update and to get the updated column values. Return the number of rows updated. delete() Delete rows from your provider. Use the arguments to select the table and the rows to delete. Return the number of rows deleted. gettype() Return the MIME type corresponding to a content URI. This method is described in more detail in the section Implementing Content Provider MIME Types. oncreate() Initialize your provider. The Android system calls this method immediately after it creates your provider. Notice that your provider is not created until 198

199 a ContentResolver object tries to access it.notice that these methods have the same signature as the identically-named ContentResolver methods.your implementation of these methods should account for the following: All of these methods except oncreate() can be called by multiple threads at once, so they must be thread-safe. To learn more about multiple threads, see the topic Processes and Threads. Avoid doing lengthy operations in oncreate(). Defer initialization tasks until they are actually needed. The section Implementing the oncreate()method discusses this in more detail. Although you must implement these methods, your code does not have to do anything except return the expected data type. For example, you may want to prevent other applications from inserting data into some tables. To do this, you can ignore the c Intents and Data Access Intents Applications can access a content provider indirectly with an Intent. The application does not call any of the methods of ContentResolver orcontentprovider. Instead, it sends an intent that starts an activity, which is often part of the provider's own application. The destination activity is in charge of retrieving and displaying the data in its UI. Depending on the action in the intent, the destination activity may also prompt the user to make modifications to the provider's data. An intent may also contain "extras" data that the destination activity displays in the UI; the user then has the option of changing this data before using it to modify the data in the provider. You may want to use intent access to help ensure data integrity. Your provider may depend on having data inserted, updated, and deleted according to strictly defined business logic. If this is the case, allowing other applications to directly modify your data may lead to invalid data. If you want developers to use intent access, be sure to document it thoroughly. Explain to them why intent access using your own application's UI is better than trying to modify the data with their code. Handling an incoming intent that wishes to modify your provider's data is no different from handling other intents. You can learn more about using intents by reading the topic Intents and Intent Filters Content Resolver Who is the ContentResolver In any given Android device there could be more than one app that is shipped with Content Provider. Lets say you build your app with Content Provider and I build my app with Content Provider and a user install both of our app. The user also install eighteen other apps that is shipped with Content Provider. That makes twenty apps with Content Provider as the 199

200 interface for their data access. If three of these apps have set their export flag to false that makes seventeen of those apps as potentially callable from other apps. If another developer wants to develop an app that will call into any of those seventeen apps, how does this developer know what end point to call? The answer is through the manifest, each of those apps that have data that is potentially accessible by other apps must publish a URI in their manifest that contains a unique Authority in the device. Example for Content Provider: <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <GridView android:id="@+id/gridview1" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:verticalspacing="10dp" android:horizontalspacing="10dp" android:columnwidth="90dp" android:stretchmode="columnwidth" android:gravity="center" android:numcolumns="2" android:layout_centervertical="true" android:layout_alignparentleft="true" android:layout_alignparentstart="true"> 200

201 </GridView> </RelativeLayout> MainActivity.java package com.example.coign.contentsdcard; import android.content.context; import android.database.cursor; import android.net.uri; import android.provider.mediastore; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.widget.gridview; import android.widget.imageview; public class MainActivity extends AppCompatActivity { // Cursor used to access the results from querying for images on the SD card. private Cursor cursor; // Column index for the Thumbnails Image IDs. private int 201

202 protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Set up an array of the Thumbnail Image ID column we want String[] projection = {MediaStore.Images.Thumbnails._ID; // Create the cursor pointing to the SDCard cursor managedquery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, // Which columns to return null, // Return all rows null, MediaStore.Images.Thumbnails.IMAGE_ID); // Get the column index of the Thumbnails Image ID columnindex = cursor.getcolumnindexorthrow(mediastore.images.thumbnails._id); GridView sdcardimages = (GridView) findviewbyid(r.id.gridview1); sdcardimages.setadapter(new ImageAdapter(this)); // Image adapter to link images to the gridview private class ImageAdapter extends BaseAdapter { private Context context; public ImageAdapter(Context localcontext) { context = localcontext; 202 =

203 public int getcount() { return cursor.getcount(); public Object getitem(int position) { return position; public long getitemid(int position) { return position; public View getview(int position, View convertview, ViewGroup parent) { ImageView picturesview; if (convertview == null) { picturesview = new ImageView(context); // Move cursor to current position cursor.movetoposition(position); // Get the current value for the requested column int imageid = cursor.getint(columnindex); // Set the content of the image based on the provided URI picturesview.setimageuri(uri.withappendedpath( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageid)); picturesview.setscaletype(imageview.scaletype.fit_xy); picturesview.setpadding(10, 10, 10, 10); picturesview.setlayoutparams(new GridView.LayoutParams(100, 100)); 203

204 else { picturesview = (ImageView)convertView; return picturesview; OUTPUT: 10.3 Introduction To Services 204

205 A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them for resource management. The only reason Android will stop a Service prematurely is to provide additional resources for a foreground component usually an Activity. When this happens, your Service can be configured to restart automatically 10.4 Types Of Services These are the two different types of services: 1.Started 2.Bound 1) Started Service: A service is started when an application component, such as an activity, starts it by calling startservice(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. 2) BoundService: A service is bound when an application component binds to it by calling bindservice(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC) Life Cycle Of Service 205

206 Fig: Service Life Cycle A service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on the left shows the life cycle when the service is created with startservice() and the diagram on the right shows the life cycle when the service is created with bindservice(): To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines various callback methods and the most important are given below. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. Callbacks and their Description: 206

207 1.onStartCommand() 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 method, it is your responsibility to stop the service when its work is done, by calling stopself() or stopservice() methods. 2. onbind() 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 an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don't want to allow binding, then you should return null. 3. onunbind() The system calls this method when all clients have disconnected from a particular interface published by the service. 4. onrebind() The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onunbind(intent). 5. oncreate() The system calls this method when the service is first created using onstartcommand() or onbind(). This call is required to perform one-time set-up. 6. ondestroy() The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. Example code for Service: To declare your service, add a <service> element as a child of the <application> element. Here is an example: <manifest... > 207

208 ... <application... > <serviceandroid:name=".exampleservice"/>... </application> </manifest> Note: we can never call onstartcommand() directly. For example, an activity can start the service using an explicit intent with startservice(), as shown below. Intent intent =newintent(this,helloservice.class); startservice(intent); The startservice() method returns immediately, and the Android system calls the service's onstartcommand() method. If the service is not already running, the system first calls oncreate(), and then it calls onstartcommand(). A service must be stopped itself by calling stopself() method, once it is finishes execution. However, you can also stop a service yourself by calling stopservice() method. A call to stopservice method will call ondestroy() callback in your service. How to write code in Android Studio: open android studio and create new project from file options, now give a name to your application and then name your java file. now your application window will be opened with java and xml file now start writing service code as shown in the sample code. activity_service.xml: 208

209 In this we should drag and drop a button which is available under widgets in the design layout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start Service" android:textcolor="#ffffff" android:background="#000000" android:id="@+id/button" android:layout_margintop="134dp" android:layout_alignparenttop="true" 209

210 android:layout_centerhorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="stop Service" android:textcolor="#ffffff" android:background="#000000" android:layout_margintop="132dp" android:layout_centerhorizontal="true" /> </RelativeLayout> MainActivity.java: In this we give the action which we drag and drop in our xml file i.e., activity_service.xml package com.example.sreya.sampleservice; import android.app.activity; import android.content.intent; import android.media.mediaplayer; 210

211 import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.button; public class MainActivity extends Activity { Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_service); bn1=(button)findviewbyid(r.id.button); bn2=(button)findviewbyid(r.id.button2); bn1.setonclicklistener(new View.OnClickListener() public void onclick(view v) { Intent i= new Intent(MainActivity.this,MyService.class); startservice(i); 211

212 ); bn2.setonclicklistener(new View.OnClickListener() public void onclick(view v) { Intent i= new Intent(MainActivity.this,MyService.class); stopservice(i); ); MyService.java In this we write code to service to run the media player Package com.example.sreya.sampleservice; import android.app.service; import android.content.intent; import android.media.mediaplayer; import android.os.ibinder; import android.support.annotation.nullable; import android.support.v7.app.appcompatactivity; import android.os.bundle; 212

213 import android.widget.toast; public class MyService extends Service { public IBinder onbind(intent intent) { return public int onstartcommand(intent intent, int flags, int startid) { mp=mediaplayer.create(myservice.this,r.raw.song); mp.start(); Toast.makeText(getApplicationContext(),"service started",toast.length_long).show(); return super.onstartcommand(intent, flags, startid); 213

214 @Override public void ondestroy() { mp.stop(); Toast.makeText(getApplicationContext(),"service stopped",toast.length_long).show(); super.ondestroy(); Output: whenever the code was executed successfully the output screen is displayed as shown below. 214

215 whenever the START SERVICE button was clicked and the output is displayed as shown below: whenever the STOP SERVICE button was clicked and the output is displayed as shown below: 215

216 CHAPTER-11 Fragment 11.1 Introduction to Fragment Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. A fragment is an independent Android component which can be used by an activity. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. A fragment runs in the context of an activity, but has its own life cycle and typically its own user interface. It is also possible to define fragments without an user interface, i.e., headless fragments. Android devices exists in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smart phone. As it is possible to dynamically add and remove fragments from an activity. The usage of fragments allows to design very flexible user interfaces. 216

217 The typical example is a list of items in an activity. On a tablet you see the details immediately on the same screen on the right hand side if you click on item. On a smart phone you jump to a new detail screen. This is depicted in the following graphic. Figure 1. An example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design. You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity Fragment Lifecycle Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle. 217

218 FIGURE: FRAGMENT LIFECYCLE Here is the list of methods which you can to override in your fragment class onattach() The fragment instance is associated with an activity instance.the fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work. oncreate() The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed. oncreateview() 218

219 The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI. onactivitycreated() The onactivitycreated() is called after the oncreateview() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findviewbyid() method. example. In this method you can instantiate objects which require a Context object onstart() The onstart() method is called once the fragment gets visible. onresume() Fragment becomes active onpause() The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session. onstop() Fragment going to be stopped by calling onstop() ondestroyview() Fragment view will destroy after call this method ondestroy() ondestroy() called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform Building a Flexible UI 219

220 When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset device it might be appropriate to display just one fragment at a time for a single-pane user interface. Conversely, you may want to set fragments side-by-side on a tablet which has a wider screen size to display more information to the user. Figure 1. Two fragments, displayed in different configurations for the same activity on different screen sizes. On a large screen, both fragments fit side by side, but on a handset device, only one fragment fits at a time so the fragments must replace each other as the user navigates How to use Fragments? This involves number of simple steps to create Fragments. First of all decide how many fragments you want to use in an activity. For example let's we want to use two fragments to handle landscape and portrait modes of the device. Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments. Finally modify activity file to define the actual logic of replacing fragments based on your requirement. 11.5Types of Fragments Basically fragments are divided as three stages as shown below. Single frame fragments Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view. List fragments fragments having special list view is called as list fragment 220

221 Fragments transaction Using with fragment transaction. we can move one fragment to another fragment. sample code for fragment: To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activity like this: FragmentManager fragmentmanager = getfragmentmanager(); FragmentTransaction fragmenttransaction = fragmentmanager.begintransaction(); You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example: ExampleFragment fragment = new ExampleFragment(); fragmenttransaction.add(r.id.fragment_container, fragment); fragmenttransaction.commit(); The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add. Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect Fragment Example: Create a new application using fragments open android studio and create new project from file options, now give a name to your application and then name your java file. now your application window will be opened with java and xml file now start writing service code as shown in the sample code. activity_main.xml: <RelativeLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" > 221

222 <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="fragment1" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="99dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="fragment2" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> </RelativeLayout> activity.fragment1.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ffffff" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" First Fragment" android:textsize="20dp" android:layout_gravity="center" android:textcolor="#000000" /> </LinearLayout> activity_fragment2.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 222

223 android:background="#000000" android:gravity="center" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="second Fragment" android:textsize="20dp" android:textcolor="#ffffff"/> </LinearLayout> MainActivity.java: package com.example.sreya.samplefragment; import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.view; import android.widget.button; public class MainActivity extends Activity { Button protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); bn1=(button)findviewbyid(r.id.button); bn2=(button)findviewbyid(r.id.button2); bn1.setonclicklistener(new View.OnClickListener() public void onclick(view v) { Intent i=new Intent(getApplicationContext(),Fragment1.class); startactivity(i); ); bn2.setonclicklistener(new View.OnClickListener() public void onclick(view v) { Intent i=new Intent(getApplicationContext(),Fragment2.class); startactivity(i); ); 223

224 Fragment1.java: package com.example.sreya.samplefragment; import android.app.activity; import android.os.bundle; public class Fragment1 extends Activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_fragment1); Fragment2.java: package com.example.sreya.samplefragment; import android.app.activity; import android.os.bundle; public class Fragment2 extends protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_fragment2); Output: Whenever code was executed the output is displayed as shown below 224

225 whenever the first button(fragment1) was clicked the output was displayed as shown below. whenever the second button(fragment2) was clicked the output is displayed as shown below. 225

226 CHAPTER-12 Preferences 226

227 12.1 Introduction to Preferences Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key, value pair. In order to use shared preferences, you have to call a method getsharedpreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences. SharedPreferences sharedpreferences Context.MODE_PRIVATE); = getsharedpreferences(mypreferences, You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax is Editor editor = sharedpreferences.edit(); editor.putstring("key", "value"); editor.commit(); Using Preferences In Android there are three different types of preferences used 1. Activity-level Preferences 2. Application-level Preferences 3. Sharing preferences across Applications Activity-level Preferences Here Preferences can be retrieved only by a single activity To save preferences those are accessed only from a single activity SharedPreferencessharedpref=getpreferences(Context.MODE_PRIVATE); SharedPreferences.EditorsharedEditor=sharedpref.edit(); sharededitor.putstring("username","robot"); sharededitor.commit(); 227

228 SharedPreferences object can be retrieved by calling getpreferences(int mode) method which takes an integer value as parameter,given below are the different modes available in Preferences API Context.MODE_PRIVATE Using this mode allows the created file only accessible by applications with the same userid. Access is provided within the same Activity only. Context.MODE_WORLD_READABLE Using this mode allows the created file readable from other applications. Context.MODE_WORLD_WRITABLE Using this mode allows other applications to write to the file. getpreferences(int mode) returns an instance of SharedPreferences.Editor and write the preference value with sharededitor.putstring(string key, String value) method. Then we call sharededitor.commit() to save the preferences to the file. Commit returns a boolean indicating the result of saving, true if successful and false if failed. Now to read the saved Preference value use sharedpref.getstring(string key,string defaultvalue) to return the value stored with specific key or default value if not found. SharedPreferences sharedpref=getperences(context.mode_private); String username=sharedpref.getstring("username","enter name"); Application-level Preferences Here Preferences can be shared and retrieved among all activities within the application To save preferences that can be accessed from all activities in the application Sharing preferences across Applications Here Preferences can be shared and retrieved through all applications on the device Preferences can be stored in one application and read them in another application and assume that both applications are in different package. For reading the value from other applications in different packages is as below try{ Context context=createpackagecontext("com.pref.shared",0); SharedPreferences sharedpref=context.getsharedpreferences ("myappcontext",context.mode_private); String username=sharedpref.getstring("username","name"); txt.settext(username); 228

229 catch (NameNotFoundException e) { Log.e("error",e.toString()); Creating Preferences Activities In Android saving preferences can be done by creating activities that extend PreferenceActivity. PreferenceActivity is an activity that displays a set of built-in preferences related widgets that are defined in xml file. In this case it is not required to save and load the data in code every time, the OS does that for developer. The preferences widgets that android provide are CheckBoxPreference Using this mode allows the created file only accessible by applications with the same userid. Access is provided within the same Activity only. EditTextPreference Using this mode allows the created file readable from other applications. ListPreference Using this mode allows other applications to write to the file. RingtonePreference Displays a list of existing ringtones in the system 12.2 To Save And Retrieve Preferences Through Code: Step 1 : Select File -> New -> Project ->Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here. Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code : <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" 229

230 tools:context="com.akhilarao.sharedpreferences.mainactivity"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="15dp" android:hint="id" android:padding="11dp" android:ems="10" android:inputtype="number" > <requestfocus /> </EditText> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_margintop="20dp" android:hint="name" android:padding="11dp" android:ems="10" android:inputtype="textpersonname" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_margintop="20dp" android:padding="11dp" android:text="save" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:padding="11dp" android:text="select" /> <TextView android:text="" 230

231 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_margintop="62dp" /> <TextView android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_marginbottom="40dp" /> </RelativeLayout> Step 3 : Open src -> package -> MainActivity.java and add following code : package com.akhilarao.sharedpreferences; import android.content.sharedpreferences; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.textview; import android.widget.toast; public class MainActivity extends AppCompatActivity { private SharedPreferences prefs; private String prefname = protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final EditText e_id=(edittext) findviewbyid(r.id.edittext1); final EditText e_name=(edittext) findviewbyid(r.id.edittext2); final TextView tv=(textview)findviewbyid(r.id.textview2) ; final TextView tv1=(textview)findviewbyid(r.id.textview3) ; Button save=(button) findviewbyid(r.id.button1); Button select=(button) findviewbyid(r.id.button2); save.setonclicklistener(new View.OnClickListener() { 231

232 @Override public void onclick(view v) { // TODO Auto-generated method stub prefs = getsharedpreferences(prefname, MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); //---save the values in the EditText view to preferences--editor.putint("id", Integer.parseInt(e_id.getText().toString())); editor.putstring("name", e_name.gettext().tostring()); //---saves the values--editor.commit(); Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show(); ); select.setonclicklistener(new View.OnClickListener() public void onclick(view v) { // TODO Auto-generated method stub prefs = getsharedpreferences(prefname, MODE_PRIVATE); String q=string.valueof(prefs.getint("id",100)); String qw=prefs.getstring("name",""); tv.settext(q); tv1.settext(qw); ); Step 4 : Open AndroidManifest.xml and add following code : <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.akhilarao.sharedpreferences"> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/apptheme"> 232

233 <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Step 5 : Open res ->values ->strings.xml and add following code : <resources> <string name="app_name">sharedpreferences</string> </resources> Step 6 : Output will be like this : 233

234 12.3 Common Types of Preferences: Every setting for your app is represented by a specific subclass of the Preference class. Each subclass includes a set of core properties that allow you to specify things such as a title for the setting and the default value. Each subclass also provides its own specialized properties and user interface. For instance, figure 1 shows a screenshot from the Messaging app's settings. Each list item in the settings screen is backed by a different Preferenceobject. A few of the most common preferences are: CheckBoxPreference: Shows an item with a checkbox for a setting that is either enabled or disabled. The saved value is a boolean (true if it's checked). ListPreference: Opens a dialog with a list of radio buttons. The saved value can be any one of the supported value types (listed above). EditTextPreference: 234

235 Opens a dialog with an Edit Text widget. The saved value is a String. See the Preference class for a list of all other subclasses and their corresponding properties. Of course, the built-in classes don't accommodate every need and your application might require something more specialized. For example, the platform currently does not provide a Preference class for picking a number or a date. So you might need to define your own Preference subclass. For help doing so, see the section about Building a Custom Preference Steps to Create Settings Preferences: Preference Settings allow the user to select basic settings for an app. It s a way of customising the app to suite the user. Now how you can create your own custom Preference Settings for your apps. We ll be using fragments and Headers so this tutorial is suitable for apps developed for devices running Android 3.0 and up. There are four parts to the Preference Framework. We ll cover all of them: Preference Screen Layout the xml file defining your settings items Preference Activity and Fragment these host the Preference screens. The activity hosts the fragment and the fragment hosts the Preference Screen, displaying your settings Preference Headers these are lists of sub screens. An xml file defines the Preference Fragments used for the Headers sub screens Shared Preference Change Listener listens for any changes in the Shared Preference values Each Preference appears as an item in a list. The user is able to modify these preference settings. Each preference has a corresponding key/value pair. These are saved in a SharedPreferences file. 235

236 You should only read this file in your app and only make changes to it in the Settings. The values are saved as: Boolean Float Long Int String String set It displays a Settings screen when the app starts. This screen has a few check boxes and an edit text field. It also has a preference item that triggers an intent to start a new activity. We use the new activity to demonstrate Preference Headers. Preference Headers is a feature that lets you build a list of sub screens. Selecting one of the list items displays a sub screen in a fragment. How to read saved preference : use a list of preferences use a multiple choice list of preferences when preference settings are changed and how to read the saved preferences from the SharedPreferences file. 236

237 The main Settings screen is on the left. Selecting the Headers Preferences option displays a list of sub screens. Selecting either of these options displays the settings for that sub screen The Galactic Transport sub screen. Choosing the Select Transport option displays the list on the right 237

238 The Galactic Cuisine sub screen. Choosing the Select your food option displays the list on the top-right where you can choose one item. Choosing the Try Multi List Choice option displays the list on the bottom-right where you can choose multiple items Choosing Read saved preferences displays this screen which shows all the settings values read from the saved preference file 238

239 A diagrammatic representation of our tutorial preference settings app The basic Settings: The Main Activity includes the Preference Fragment This is the entry point to the app. It hosts a fragment that displays our basic preference settings. File: xml/settings.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android=" > <PreferenceCategory android:title="@string/pref_user_profile" > <EditTextPreference android:title="@string/pref_user_name" android:summary="@string/pref_user_name_summary" android:key="prefusername"/> </PreferenceCategory> <PreferenceCategory android:title="@string/pref_update_setting" > <CheckBoxPreference android:defaultvalue="false" android:key="prefsendreport" android:summary="@string/pref_send_report_summary" android:title="@string/pref_send_report" > </CheckBoxPreference> <ListPreference android:key="prefsyncfrequency" android:entries="@array/syncfrequency" android:summary="@string/pref_sync_frequency_summary" android:entryvalues="@array/syncfrequencyvalues" 239

240 /> </PreferenceCategory> </PreferenceScreen> The list we defined in above Preference settings file will be declared as an array in arrays.xml. Create a file arrays.xml (if not present already in your project) in /res/values folder and copy following content into it: File: arrays.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android=" > <PreferenceCategory android:title="@string/pref_user_profile" > <EditTextPreference android:title="@string/pref_user_name" android:summary="@string/pref_user_name_summary" android:key="prefusername"/> </PreferenceCategory> <PreferenceCategory android:title="@string/pref_update_setting" > <CheckBoxPreference android:defaultvalue="false" android:key="prefsendreport" android:summary="@string/pref_send_report_summary" android:title="@string/pref_send_report" > </CheckBoxPreference> <ListPreference android:key="prefsyncfrequency" android:entries="@array/syncfrequency" android:summary="@string/pref_sync_frequency_summary" android:entryvalues="@array/syncfrequencyvalues" android:title="@string/pref_sync_frequency" /> </PreferenceCategory> </PreferenceScreen> <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="syncfrequency"> <item name="1">once a day</item> <item name="7">once a week</item> <item name="3">once a year</item> 240

241 <item name="0">never (Update maually)</item> </string-array> <string-array name="syncfrequencyvalues"> <item name="1">1</item> <item name="7">7</item> <item name="30">30</item> <item name="0">0</item> </string-array> </resources> In addition to arrays.xml, we will also need some string values for our app. Below is the list of string constant that we will add in strings.xml file. File: strings.xml <resources> <string name="app_name">android_preferences_example</string> <string name="hello_world">hello world!</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> <string name="pref_send_report">send crash reports</string> <string name="pref_send_report_summary">helps to fix bugs</string> <string name="pref_sync_frequency">sync frequency</string> <string name="pref_sync_frequency_summary">set the sync frequency</string> <string name="pref_user_name">set username</string> <string name="pref_user_name_summary">set your username</string> <string name="pref_user_profile">user Profile</string> <string name="pref_update_setting">update Settings</string> </resources> We have now created the basic setup for Preferences in our app. Now we need to integrate it with our actual Activity. 241

242 First we need to create a menu which will be shown when User clicks menu button. This menu will have only one menuitem, Settings. On click on this item, we will display the Settings preference screen. Create a file settings.xml under /res/menu folder and copy following content into it: File: menu/settings.xml <menu xmlns:android=" > <item android:id="@+id/menu_settings" ic_menu_preferences="" android:orderincategory="100" android:showasaction="never" android:title="@string/menu_settings" android:icon="@android:drawable/ic_menu_preferences"/> </menu> Create a new Activity classmainactivity under net.viralpatel.android package and copy following code into it: File: MainActivity.java package net.viralpatel.android; import android.app.activity; import android.content.intent; import android.content.sharedpreferences; import android.os.bundle; import android.preference.preferencemanager; import android.view.menu; import android.view.menuitem; import android.widget.textview; public class MainActivity extends Activity{ private static final int RESULT_SETTINGS Public void oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); 242

243 Public boolean oncreateoptionsmenu(menu menu){ getmenuinflater().inflate(r.menu.settings, menu); Public boolean onoptionsitemselected(menuitem item){ switch(item.getitemid()){ case R.id.menu_settings: Intent i =newintent(this, UserSettingActivity.class); startactivityforresult(i, RESULT_SETTINGS); break; Return Protected void onactivityresult(int requestcode,int resultcode, Intent data){ super.onactivityresult(requestcode, resultcode, data); switch(requestcode){ case RESULT_SETTINGS: showusersettings(); break; Private void showusersettings(){ SharedPreferences sharedprefs = PreferenceManager.getDefaultSharedPreferences(this); StringBuilder builder =newstringbuilder(); builder.append("\n Username: " + sharedprefs.getstring("prefusername","null")); 243

244 builder.append("\n Send report:" + sharedprefs.getboolean("prefsendreport",false)); builder.append("\n Sync Frequency: " +sharedprefs.getstring("prefsyncfrequency","null")); TextView settingstextview =(TextView)findViewById(R.id.textUserSettings); settingstextview.settext(builder.tostring()); In above MainActivity,showUserSettings method fetches the values stored in Preferences and display on screen. Note how we used Preference API for that: SharedPreferences sharedprefs = PreferenceManager.getDefaultSharedPreferences(this); sharedprefs.getstring("prefusername","null"); sharedprefs.getboolean("prefsendreport",false); Finally we need layout to display our MainActivity. Below is the layout file. This will display all selected preference values from the Settings screen. File: layout/activity_main.xml <LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textusersettings" 244

245 android:layout_width="wrap_content" android:layout_height="wrap_content" tools:context=".mainactivity" /> </LinearLayout> Screen shots of Android App And that s all! Just execute the app in Android emulator or real device and see following output. 245

246 246

247 247

248 CHAPTER-13 GCM Messaging 13.1 GCM: GCM stands for google cloud messaging. It is a service given by google that helps us to send both downstream and upstream messages between mobile and server. GCM is free to use and you can also create real time chat applications using GCM. It enables third-party application developers to send notification data or information from developer-run servers to applications that target the Google Android Operating System, as well as applications or extensions developed for the Google Chrome internet browser. It is available to developers free of charge. The GCM Service was first announced in June 2012 as a successor to Google's nowdefunct Android Cloud to Device Messaging (C2DM) service, citing improvements to authentication and delivery, new API endpoints and messaging parameters, and the removal of limitations on API send-rates and message sizes GCM service Architecture: 248

249 Google Cloud Messaging functions using server APIs and SDKs, both maintained by Google. The GCM has the ability to send push notifications, deep-linking commands, and application data. Larger messages can be sent with up to 4 KB of payload data. Upon allowing the application permission to receive and display notifications, the client application sends a registration API request to the Google Cloud Messaging interface to begin the registration process. The GCM Service receives and acknowledges the request and responds by giving the device a GCM Registration ID, a unique identifier that the developer later uses to send a notification to the individual device. The identifier is stored onto the device, and is typically sent to the developer's application server to be stored. The GCM Registration ID is a randomly-generated identifier that does not contain any personal or device information that could allow a developer to discover the personal identity of the user. When the developer wishes to send a notification event to a device, the process begins with an API POST request being sent to the GCM Authentication Service. The POST request includes the GCM Registration ID, priority, optional values and links, and the information that is to be displayed on the device upon its arrival. Upon successful verification of the GCM Registration ID and other credentials, an authentication token is returned. Both identifiers are then sent to the GCM Service to be enqueued and delivered to the device. How it works: Much of the heavy lifting in supporting push notifications on Android is facilitated by Google-powered connection servers. These Google servers provide an API for messages to be sent from your server and relay these messages to any Android/iOS devices authorized to receive them. 249

250 An Android device with Google Play Services will already have FCM client support available. For push notifications to be received, an app must first obtain a token by registering with a Google server: This token then must be passed along to your server so that it can be used to send subsequent push notifications: Push notifications can be received assuming your app has registered to listen for FCM-based messages: 250

251 In other words, in order to implement FCM, your app will need both a Google server and your own server. When your app gets a token from Google, it needs to forward this token to your server. This token should be persisted by the server so that it can be used to make API calls to the Google server. With this approach, your server and the Android device do not need to create a persistent connection and the responsibility of queuing and relaying messages is all handled by Google's servers. How to create project using google developer console Creating an Android Studio Project: Again we need to create a new Android Studio Project. So open Android Studio and create a new project. I have created AndroidGCM. Now once your project is loaded, copy the package name of your project. You can get the package name by going to the manifest file. Now we need to configure our application in Google Developers Console. Creating an App in Google Developers In this step we need to get google-services.json file. This file contains the configuration specific to your application. Go to this link. And click on GET A CONFIGURATION FILE 251

252 Now you will be asked to enter an app name, and your application s package name. Just put an app name (I have written MyGCMExample) and the package name of the project your created. We copied the package name after creating project from the manifest so you only need to paste it here (see the image below) and click on Continue To Choose and Configuration Service. Now in the next screen you will see a button to enable google cloud messaging, click on that. 252

253 After clicking on Enable Google Cloud Messaging you will get Server API Key and Sender Id. Copy it and save it on a text file it will be used. Now Scroll below and click on Continue To Generate Configuration Files. 253

254 Now you will get a button to download the configuration file. Click on the button and you will get your goolge-services.json file. 254

255 Your Google App part is over, now we will again come to our Android Studio Project. Implementing Android Push Notification Project Configuration Follow the steps from here very carefully. The first thing we need is to add the google-services.json to our project. Click on the project explorer and select project. 255

256 Right click on the app folder and paste the json file you just downloaded. Come inside your app level build.gradle file and add the following lines. dependencies { compile filetree(include: ['*.jar'], dir: 'libs') testcompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' //This line is added compile 'com.google.android.gms:play-services-gcm:8.3.0' //This line is added apply plugin: 'com.google.gms.google-services' You also need to add two more lines inside your project level build.gradle file. So open project level build.gradle and modify the codes as below. 256

257 // Top-level build file where you can add configuration options common to all subprojects/modules. buildscript { repositories { jcenter() dependencies { classpath 'com.android.tools.build:gradle:1.5.0' //These two lines are added classpath 'com.google.gms:google-services:1.5.0-beta2' classpath 'com.android.tools.build:gradle:2.0.0-alpha6' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files allprojects { repositories { jcenter() task clean(type: Delete) { delete rootproject.builddir Thats it now just sync your project. GCMRegistrationIntentService After Syncing create a new java class named GCMRegistrationIntentService.java and write the following code. package net.simplifiedcoding.androidgcm; import android.app.intentservice; import android.content.intent; import android.support.v4.content.localbroadcastmanager; import android.util.log; import com.google.android.gms.gcm.googlecloudmessaging; import com.google.android.gms.iid.instanceid; public class GCMRegistrationIntentService extends IntentService { //Constants for success and errors public static final String REGISTRATION_SUCCESS = 257

258 "RegistrationSuccess"; public static final String REGISTRATION_ERROR = "RegistrationError"; //Class constructor public GCMRegistrationIntentService() { protected void onhandleintent(intent intent) { //Registering gcm to the device registergcm(); private void registergcm() { //Registration complete intent initially null Intent registrationcomplete = null; //Register token is also null //we will get the token on successfull registration String token = null; try { //Creating an instanceid InstanceID instanceid InstanceID.getInstance(getApplicationContext()); //Getting the token from the instance id token instanceid.gettoken(getstring(r.string.gcm_defaultsenderid), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); = = //Displaying the token in the log so that we can copy it to send push notification //You can also extend the app by storing the token in to your server Log.w("GCMRegIntentService", "token:" + token); //on registration complete creating intent with success registrationcomplete = Intent(REGISTRATION_SUCCESS); //Putting the token to the intent registrationcomplete.putextra("token", token); catch (Exception e) { //If any error occurred Log.w("GCMRegIntentService", "Registration error"); registrationcomplete = Intent(REGISTRATION_ERROR); new new //Sending the broadcast that registration is completed LocalBroadcastManager.getInstance(this).sendBroadcast(registrati oncomplete); 258

259 GCMTokenRefreshListenerService Now create a new class named GCMTokenRefreshListenerService.java this will be used to register the device again if the server token has changed. package net.simplifiedcoding.androidgcm; import android.content.intent; import com.google.android.gms.iid.instanceidlistenerservice; public class GCMTokenRefreshListenerService extends InstanceIDListenerService { //If the token is changed registering the device public void ontokenrefresh() { Intent intent = new Intent(this, GCMRegistrationIntentService.class); startservice(intent); GCMPushReceiverService Now we need to create the receiver for our android push notification using gcm. Create a new class named GCMPushReceiverService.java and write the following code. 259

260 package net.simplifiedcoding.androidgcm; import android.app.notificationmanager; import android.app.pendingintent; import android.content.context; import android.content.intent; import android.media.ringtonemanager; import android.net.uri; import android.os.bundle; import android.support.v4.app.notificationcompat; import com.google.android.gms.gcm.gcmlistenerservice; //Class is extending GcmListenerService public class GCMPushReceiverService extends GcmListenerService { //This method will be called on every new message public void onmessagereceived(string from, Bundle data) { //Getting the message from the bundle String message = data.getstring("message"); //Displaying a notiffication with the message sendnotification(message); //This method is generating a notification and displaying the notification private void sendnotification(string message) { Intent intent = new Intent(this, MainActivity.class); intent.addflags(intent.flag_activity_clear_top); int requestcode = 0; PendingIntent pendingintent = PendingIntent.getActivity(this, requestcode, intent, PendingIntent.FLAG_ONE_SHOT); Uri sound = RingtoneManager.getDefaultUri(RingtoneManager. TYPE_NOTIFICATION) ; NotificationCompat.Builder nobuilder = new NotificationCompat.Builder (this).setsmallicon(r.mipmap.ic_launcher).setcontenttext(message).setautocancel(true).setcontentintent(pendingintent); NotificationManager notificationmanager = (NotificationManager) getsystemservice(context.notification_service); notificationmanager.notify(0, nobuilder.build()); //0 = ID of notification MainActivity.java package net.simplifiedcoding.androidgcm; 260

261 import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.app.activity; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.support.v4.content.localbroadcastmanager; import android.util.log; import android.widget.toast; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; public class MainActivity extends AppCompatActivity { //Creating a broadcast receiver for gcm registration private BroadcastReceiver protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //Initializing our broadcast receiver mregistrationbroadcastreceiver = new BroadcastReceiver() { //When the broadcast received //We are sending the broadcast from public void onreceive(context context, Intent intent) { //If the broadcast has received with success //that means device is registered successfully if(intent.getaction().equals(gcmregistrationintentservice.regist RATION_SUCCESS)){ //Getting the registration token from the intent String token = intent.getstringextra("token"); //Displaying the token as toast Toast.makeText(getApplicationContext(), "Registration token:" + token, Toast.LENGTH_LONG).show(); //if the intent is not with success then displaying error messages else if(intent.getaction().equals(gcmregistrationintentservice.registration_ ERROR)){ Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show(); else { Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show(); 261

262 ; //Checking play service is available or not int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext ()); //if play service is not available if(connectionresult.success!= resultcode) { //If play service is supported but not installed if(googleplayservicesutil.isuserrecoverableerror(resultcode)) { //Displaying message that play service is not installed Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show(); GooglePlayServicesUtil.showErrorNotification(resultCode, getapplicationcontext()); //If play service is not supported //Displaying an error message else { Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show(); //If play service is available else { //Starting intent to register device Intent itent = new Intent(this, GCMRegistrationIntentService.class); startservice(itent); //Registering receiver on activity protected void onresume() { super.onresume(); Log.w("MainActivity", "onresume"); LocalBroadcastManager.getInstance(this).registerReceiver(mRegistration BroadcastReceiver, new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS)); LocalBroadcastManager.getInstance(this).registerReceiver(mRegistration BroadcastReceiver, new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR)); //Unregistering receiver on activity protected void onpause() { super.onpause(); Log.w("MainActivity", "onpause"); LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistratio 262

263 nbroadcastreceiver); At last we need to add our listeners and broadcast receivers to manifest file, we also need to add some permission on manifest file. So open AndroidManifest.xml and modify it as below. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="net.simplifiedcoding.androidgcm"> <!-Adding permissions -internet -Wake_Lock -C2D_Message --> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.wake_lock" /> <permission android:name="net.simplifiedcoding.androidgcm.permission.c2d_mess AGE" android:protectionlevel="signature" /> <uses-permission android:name="net.simplifiedcoding.androidgcm.permission.c2d_message " /> <application android:allowbackup="true" android:supportsrtl="true" <activity android:name=".mainactivity" <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <!-GCM Receiver 263

264 --> <receiver android:name="com.google.android.gms.gcm.gcmreceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.send"> <intent-filter> <action android:name="com.google.android.c2dm.intent.receive"/> <category android:name="com.gnirt69.gcmexample"/> </intent-filter> </receiver> <!-GCM Receiver Service --> <service android:name=".gcmpushreceiverservice" android:exported="false"> <intent-filter> <action android:name="com.google.android.c2dm.intent.receive"/> </intent-filter> </service> <!-GCM Registration Intent Service --> <service android:exported="false"> android:name=".gcmregistrationintentservice" <intent-filter> <action android:name="com.google.android.gms.iid.instanceid"/> </intent-filter> </service> </application> </manifest> now just run your application. 264

265 In real world scenario we store this token into web server to send the push notification to the device, but as this tutorial is meant to teach you about implementing gcm only we need to copy this token to send a notification. Thats why we have displayed the token in the log as well, so that you can copy the token from the log. So just see your log and copy the token 265

266 Copy the whole token string and remove token: from it. Now you have the registration token and your Server API Key. Sending Push Notification to the Device On the first input field enter your SERVER API KEY, on second enter REGISTRATION TOKEN and on third enter the message you want to send, and click on send. And check your device. 266

267 267

268 CHAPTER-14 Material Desining & Pending Intent 14.1 Introduction to Material Design: Material Design is a visual language developed by Google which was first introduced with Lollipop OS and since then it has become popular in designing and developing Android Apps. As per Google this language is based on paper and ink. What is material design? Google introduced material design in last year s I/O, describing it as an interface that incorporates tactile surfaces, bold graphic design and fluid motion to create beautiful, intuitive experiences. Material design is the new user experience philosophy for Android apps! Material design is a comprehensive guide for visual, motion, and interaction design across platforms and devices. Android now includes support for material design apps. To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21 Version Lollipop) and above. Android provides the following elements to build material design apps: A new theme New widgets for complex views New APIs for custom shadows and animations Material Theme The new material theme provides: System widgets that let you set their color palette Touch feedback animations for the system widgets Activity transition animations You can customize the look of the material theme according to your brand identity with a color palette you control. You can tint the action bar and the status bar using theme attributes 268

269 The system widgets have a new design and touch feedback animations. You can customize the color palette, the touch feedback animations, and the activity transitions for your app. The material theme is defined (dark (light 14.2 Recycler View: RecyclerView is flexible and efficient version of ListView. It is an container for rendering larger data set of views that can be recycled and scrolled very efficiently. RecyclerView is like traditional ListView widget, but with more flexibility to customizes and optimized to work with larger datasets. Many apps need to display user-interface elements based on large data sets, or data that frequently changes. For example, a music app might need to display information about thousands of albums, but only a dozen of those albums might be on-screen at a time. If the app created UI widgets for each of those albums, the app would end up using a lot of memory and storage, potentially making the app slow and crash-prone. On the other hand, if the app created UI widgets each time a new album scrolled onto the screen and destroyed the widgets when it scrolled off, that would also cause the app to run slowly, since creating UI objects is a resource-intensive operation. To address this common situation, the Android Support Library provides the RecyclerView suite of objects. RecyclerView and its associated classes and interfaces help you to design and implement a dynamic user interface that runs efficiently. You can use these classes as they are, or customize them to suit your specific needs. RecyclerView Workflow To understand how RecyclerView works, it may be helpful to follow a typical workflow. In this case, we assume that an app's main activity uses a RecyclerView to manage a simple list of text items, such as a list of names. When the system creates the app's main activity, the system calls the activity's oncreate() method. That method takes a number of steps to set up the RecyclerView: The oncreate() method creates the RecyclerView specified by activity's layout: myrecyclerview = (RecyclerView) findviewbyid(r.id.myrecyclerview); The layout also specifies which layout manager the RecyclerView uses to arrange its data. 269

270 Note: You can dynamically set or change the RecyclerView layout by calling RecyclerView.setLayoutManager() at run time. However, if you do not need to change the layout at runtime, we recommend that you set the layout manager in the RecyclerView layout file. Among other reasons, if you use the layout file, Android Studio can properly preview the RecyclerView UI. The oncreate() method creates an adapter; the adapter class is specified by the app, extending the Android Support Library's RecyclerView.Adapter class. Typically, when the app creates the adapter, the app passes the information the adapter needs to get its data. myadapter = new CustomAdapter(myDataSet); The adapter's constructor does any necessary initialization. For example, it might create an inflater to use for inflating the layouts of its view holders. Note: For performance reasons, you should separate the logic that updates your list's data from the logic that manages the layouts and assigns the data to them. The oncreate() method attaches the adapter to the RecyclerView. myrecyclerview.setadapter(myadapter); The RecyclerView calls the adapter to create any necessary view holders. Each view holder displays one item's data. For example, a music app might use a view holder for each album. The adapter class's definition specifies which class it uses as its view holder: public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> The Android Support Library calls the adapter's oncreateviewholder() method. That method needs to construct the view holder and set the view it uses to display its contents. Typically, it would set the view by inflating an XML layout file. Since the view holder is not yet assigned to any particular data, the method does not actually set the view's contents. View thisitemsview = myinflater.inflate(r.layout.list_item_layout, parent, false); // Call the view holder's constructor, and pass the view to it; // return that new view holder return new CustomViewHolder(thisItemsView); The Android Support Library then binds the view holder to its data. It does this by calling the adapter's onbindviewholder() method, and passing the view holder's position in the RecyclerView. The onbindviewholder() method needs to fetch the appropriate data, and use it to fill in the view holder's layout. For example, if the RecyclerView is displaying a list of names, the method might find the appropriate name in the list, and fill in the view holder's TextView public void onbindviewholder(customviewholder holder, int position) { // Find out the data, based on this view holder's position 270

271 String thisitemsname = mynamelist.get(position); holder.nametextview.settext(thisitemsname); The Android Support Library repeats this process, creating and binding new view holders until the visible portion of the RecyclerView is filled. It also creates and binds one or two more, so if the user scrolls the list, the new view holders are ready to display. If the user scrolls the list, the Android Support Library brings the already-prepared view holders into view, and creates and binds new ones as necessary. It does not immediately destroy the view holders that have scrolled out of sight; they are kept available, in case the user scrolls back. However, after a certain number of view holders have been created, the Android Support Library does not create new ones. Instead, it rebinds existing view holders as needed by calling onbindviewholder() for them, specifying a new position. That method updates the view holder's contents, but it reuses the view that was already created for that view holder. The method does not have to perform costly actions like building or inflating a new view. You may find the DiffUtil class useful for determining which items in your list need to be updated. If the list changes, the app calls an appropriate RecyclerView.Adapter notification method. The Android Support Library responds to the notification by rebinding any affected view holders, allowing their data to be updated. The app can improve performance by choosing a more precise notification; for example, if the data in a single item needs to be updated, the app can call notifyitemchanged(int), and the Android Support Library will just rebind that one item if it is visible Card view: CardView is another major element introduced in Material Design. Using CardView you can represent the information in a card manner with a drop shadow (elevation) and corner radius which looks consistent across the platform. CardView extends the FrameLayout and it is supported way back to Android 2.x The CardView widget, is an extension of existing FrameLayout class. This helps to wrap other UI elements as Google style cards. CardView widgets can have shadows and rounded corners. Creating Lists and Cards 1. Create Lists 2. Create Cards 3. Add Dependencies you should also read 271

272 Material design specification Material design on Android To create complex lists and cards with material design styles in your apps, you can use the RecyclerView and CardView widgets Creating Lists & Cards Create Lists The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. The RecyclerView class simplifies the display and handling of large data sets by providing: Layout managers for positioning items Default animations for common item operations, such as removal or addition of items You also have the flexibility to define custom layout managers and animations for RecyclerView widgets. Figure 1.The RecyclerView widget. To use the RecyclerView widget, you have to specify an adapter and a layout manager. To create an adapter, extend the RecyclerView.Adapter class. The details of the implementation depend on the specifics of your dataset and the type of views. For more information, see the examples below. 272

273 Figure 2 - Lists with RecyclerView. A layout manager positions item views inside a RecyclerView and determines when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findviewbyid() lookups. RecyclerView provides these built-in layout managers: LinearLayoutManager shows items in a vertical or horizontal scrolling list. GridLayoutManager shows items in a grid. StaggeredGridLayoutManager shows items in a staggered grid. To create a custom layout manager, extend the RecyclerView.LayoutManager class. Animations Animations for adding and removing items are enabled by default in RecyclerView. To customize these animations, extend the RecyclerView.ItemAnimator class and use the RecyclerView.setItemAnimator()method. Examples The following code example demonstrates how to add the RecyclerView to a layout: 273

274 <!-- A RecyclerView with some commonly used attributes --> <android.support.v7.widget.recyclerview android:id="@+id/my_recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent"/> Once you have added a RecyclerView widget to your layout, obtain a handle to the object, connect it to a layout manager, and attach an adapter for the data to be displayed: publicclassmyactivityextendsactivity{ privaterecyclerview mrecyclerview; privaterecyclerview.adapter madapter; privaterecyclerview.layoutmanager protectedvoid oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.my_activity); mrecyclerview =(RecyclerView) findviewbyid(r.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mrecyclerview.sethasfixedsize(true); // use a linear layout manager mlayoutmanager =newlinearlayoutmanager(this); 274

275 mrecyclerview.setlayoutmanager(mlayoutmanager); // specify an adapter (see also next example) madapter =newmyadapter(mydataset); mrecyclerview.setadapter(madapter);... The adapter provides access to the items in your data set, creates views for items, and replaces the content of some of the views with new data items when the original item is no longer visible. The following code example shows a simple implementation for a data set that consists of an array of strings displayed using TextView widgets: publicclassmyadapterextendsrecyclerview.adapter<myadapter.viewholder>{ privatestring[] mdataset; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder publicstaticclassviewholderextendsrecyclerview.viewholder{ // each data item is just a string in this case publictextview mtextview; publicviewholder(textview v){ super(v); mtextview = v; 275

276 // Provide a suitable constructor (depends on the kind of dataset) publicmyadapter(string[] mydataset){ mdataset = mydataset; // Create new views (invoked by the layout publicmyadapter.viewholder oncreateviewholder(viewgroup parent, int viewtype){ // create a new view TextView v =(TextView)LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent,false); // set the view's size, margins, paddings and layout parameters... ViewHolder vh =newviewholder(v); return vh; // Replace the contents of a view (invoked by the layout publicvoid onbindviewholder(viewholder holder,int position){ // - get element from your dataset at this position 276

277 // - replace the contents of the view with that element holder.mtextview.settext(mdataset[position]); // Return the size of your dataset (invoked by the layout publicint getitemcount(){ return mdataset.length; 277

278 Create Cards CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. To create a card with a shadow, use the card_view:cardelevation attribute. CardView uses real elevation and dynamic shadows on Android 5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions. For more information, see Maintaining Compatibility. Use these properties to customize the appearance of the CardView widget: To set the corner radius the card_view:cardcornerradius attribute. your layouts, use To set the corner radius in your code, use the CardView.setRadius method. in To set the background the card_view:cardbackgroundcolor attribute. color of a card, The following code example shows you how to include a CardView widget in your layout: <LinearLayoutxmlns:android=" xmlns:tools=" xmlns:card_view=" > <!-- A CardView that contains a TextView --> <android.support.v7.widget.cardview xmlns:card_view=" android:id="@+id/card_view" android:layout_gravity="center" android:layout_width="200dp" android:layout_height="200dp" card_view:cardcornerradius="4dp"> 278 use

279 <TextView android:layout_width="match_parent" android:layout_height="match_parent"/> </android.support.v7.widget.cardview> </LinearLayout> Add Dependencies: The RecyclerView and CardView widgets are part of the v7 Support Libraries. To use these widgets in your project, add these Gradle dependencies to your app's module: dependencies{... compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+' 14.5 Swipe refresh Layout: The SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture. The activity that instantiates this view should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again; the listener is responsible for correctly determining when to actually initiate a refresh of its content. If the listener determines there should not be a refresh, it must call setrefreshing(false) to cancel any visual indication of a refresh. If an activity wishes to show just the progress animation, it should call setrefreshing(true). To disable the gesture and progress animation, call setenabled(false) on the view. This layout should be made the parent of the view that will be refreshed as a result of the gesture and can only support one direct child. This view will also be made the target of the gesture and will be forced to match both the width and the height supplied in this layout. The SwipeRefreshLayout does not provide accessibility events; instead, a menu item must be provided to allow refresh of the content wherever this gesture is used. 279

280 14.6 Material Design Colour Customization Introduced a new design guideline with the release of Android 5.0 (Lollipop) known as Material Design, and with this guidelines Google provide Material Theme to the android developer. This is a new user interface. In this post, I will show you way to use custom material design theme and color in your application. Setup Material Theme First of all, you have to setup material design theme to your styles.xml file. You can choose any of three material themes according to your wish: Theme.Material Theme.Material.Light Theme.Material.Light.DarkActionBar Here I have used Theme.Material.Light.DarkActionBar as app theme. <style name="apptheme" parent="theme.material.light.darkactionbar"> </style> Add Custom Theme Colors You have to create a colors.xml file in res/values folder to define custom theme colors. After defining theme colors, your colors.xml file seems like this. res/values/colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <colorname="colorprimary">#03a9f4</color> <colorname="colorprimarydark">#0288d1</color> <colorname="coloraccent">#00bcd4</color> <colorname="windowbackground">#fff</color> <colorname="navigationbarcolor">#0288d1</color> <colorname="statusbarcolor">#0288d1</color> <colorname="textcolorprimary">#fff4f4f4</color> </resources> 280

281 Look at following image, here I have shown meaning of colorprimary, colorprimarydark, coloraccent, windowbackground, navigationbarcolor, statusbarcolor, textcolorprimary. Update Your styles.xml File Here, I have added status bar color, action bar / app bar color, app background color, navigation bar color, etc. that we defined before in our colors.xml file. Your styles.xml file seems like this. res/values/styles.xml <resources> <!-- Base application theme. --> <style name="apptheme" parent="theme.material.light.darkactionbar"> <item name="colorprimary">@color/colorprimary</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="coloraccent">@color/coloraccent</item> <item name="android:windowbackground">@color/windowbackground</item> <item name="android:navigationbarcolor">@color/navigationbarcolor</item> <item name="android:statusbarcolor">@color/statusbarcolor</item> <item name="android:textcolorprimary">@color/textcolorprimary</item> <!-- Customize your theme here. --> </style> </resources> Only this much is not about the material design, it is lot more. Here I just described how to use custom material design theme and color in android application Toolbar A Toolbar is similar to an ActionBar. It s a ViewGroup so you can place it anywhere in your layout. You can even replace the ActionBar with a Toolbar. Toolbar s are also more flexible. You can modify its size, colour, position, etc. You can also add logos, labels, navigation icons and other views to it. With the release of Android 5.0 and material design, Android has updated the AppCompat support libraries so that we can use Toolbars on devices running API Level 7 and up. Take over the bar: Replacing the ActionBar with a Toolbar Put it out of action: Disable the ActionBar 281

282 You need to disable the ActionBar if you want to replace it with a Toolbar. We ve done this in our styles.xml file where we set our theme to use the NoActionBar variation of the AppCompat Light theme. Get your toolbox: Create your Toolbar widget in an XML layout file <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.toolbar xmlns:android=" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorprimary" android:elevation="4dp" > </android.support.v7.widget.toolbar> Use the support library s Toolbar widget element and give it an ID so that we can access it later in code. The width is set to match the parent s so that it will span the width of the screen. The height is set to 200dp to accommodate the dog image which is 200dp high. We ve set the background colour to orange. The minimum height is set to 200dp. This ensures that all the displayed items are vertically centred. Finally we include an image view referencing a drawable resource for the image to display. Get to work: Set up the Toolbar as the ActionBar in code We get a reference to the Toolbar and then call setsupportactionbar() to set the Toolbar as the ActionBar. Note that you should call this first if you re going to be adding logos and navigation icons else they won t show. Then we call setnavigationicon() to display our back arrow image which we ll use to navigate back. You must include a description for the navigation icon which will be used to describe the logo to visually impaired users We also include a logo for the Toolbar by calling setlogo(). We also include a description for it. Use the onoptionsitemselected() method to handle the options menu item selections. You can also use the setnavigationonclicklistener() to listen for when the navigation icon is pressed, using its onclick() method to deal with the navigation. We ll show you how when we discuss the standalone Toolbar later. 282

283 Call settitle(null) in the oncreate() method if the title shows and you don't want it to. Including a menu in the Toolbar As this Toolbar is replacing our ActionBar, we chose to include a menu action item as well as the menu s overflow button. We use the oncreateoptionsmenu() method to inflate the menu resource. Handling the Toolbar s item selections We use the onoptionsitemselected() method to handle the menu item selections. We display an appropriate Toast message if either of the menu items is selected. Selecting the action item makes the standalone Toolbar visible. We then use an animation to fade it in. You don t have to disable the ActionBar for the standalone option. Create your Toolbar widget in an XML layout file Define the Toolbar in a layout file: <android.support.v7.widget.toolbar android:id="@+id/mytoolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorprimary" android:elevation="4dp" android:visiblity="gone" /> We define the standalone Toolbar in our activity_main.xml layout file A quick explanation Use the support library s Toolbar widget element and give it an ID so that we can access it later in code. The width is set to match the parent s so that it will span the width of the screen. The height is set to wrap_content so it will only be as high as the largest object it contains. We use the layout_alignparentbottom attribute to display the Toolbar at the bottom of the screen. We ve set the background colour to orange using the background attribute. Finally we set the Toolbar s visibility to GONE. This ensures that it s not visible and nor does it take up any screen space. 283

284 We include two listeners: One listens for the menu item selections One listens for the navigation icon selections Listening for menu item selections We need to include the Toolbar class s setonmenuitemclicklistener() method to listen for when the menu s Action item is selected: Use the setonmenuitemclicklistener() method to listen for menu item selections A quick explanation We attach the listener to our standalone Toolbar. It listens for when a menu item is selected, triggering its onclick() method. Here we include a Toast message to display when the Action item is selected. Listening for when the navigation item is selected We include the Toolbar class s setnavigationonclicklistener() method to listen for when the navigation icon is selected: Use the setnavigationonclicklistener () method to listen for when the navigation icon is selected We attach the listener to our standalone Toolbar. It listens for when the navigation icon is selected, triggering its onclick() method. Here we include a Toast message which is displayed when the navigation icon is selected. Example: implement design for material design using xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:app=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> 284

285 <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="20dp"> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="visible" app:indicator="ballpulse" app:indicator_color="#ff00" /> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:visibility="visible" app:indicator="ballcliprotatemultiple" app:indicator_color="#ff00" /> 285

286 </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margintop="20dp" android:orientation="horizontal" android:padding="20dp"> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" android:visibility="visible" app:indicator="linescale" app:indicator_color="#ff00" /> </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" 286

287 android:layout_margintop="20dp" android:orientation="horizontal" android:padding="20dp"> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="visible" app:indicator="ballrotate" app:indicator_color="#ff00" /> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentright="true" android:visibility="visible" app:indicator="linespinfadeloader" app:indicator_color="#ff00" /> </RelativeLayout> <com.wang.avi.avloadingindicatorview 287

288 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" android:layout_gravity="center_horizontal" android:layout_margintop="20dp" android:visibility="visible" app:indicator="ballgridbeat" app:indicator_color="#ff00" /> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="20dp" android:visibility="visible" app:indicator="ballspinfadeloader" app:indicator_color="#ff00" /> <com.wang.avi.avloadingindicatorview android:layout_width="wrap_content" android:layout_height="wrap_content" 288

289 android:layout_alignparentright="true" android:layout_margintop="20dp" android:visibility="visible" app:indicator="ballscaleripple" app:indicator_color="#ff00" /> </RelativeLayout> implement your logic for material design using.java file package viralandroid.com.androidmaterialdesigntutorial; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.view.view; public class AndroidMaterialDesignLoaderExample extends AppCompatActivity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.material_design_loader_progress_android_example); 289

290 ballpulseanimloader(); ballcliprotatemultipleanimateloader(); linescaleloaderexample(); ballrotateloaderandroidexample(); linespinfadeloaderloader(); androidballgridbeatloaderbar(); androidballspinfadeloaderprogressbar(); ballscalerippleprogressloaderexample(); void ballpulseanimloader() { findviewbyid(r.id.material_design_ball_pulse_loader_progress).setvisibility(view.visibl E); void ballcliprotatemultipleanimateloader() { findviewbyid(r.id.material_design_ball_clip_rotate_multiple_loader).setvisibility(view.vis IBLE); void linescaleloaderexample() { findviewbyid(r.id.material_design_linear_scale_progress_loader).setvisibility(view.visib LE); 290

291 void ballrotateloaderandroidexample() { findviewbyid(r.id.material_design_ball_rotate_loader).setvisibility(view.visible); void linespinfadeloaderloader() { findviewbyid(r.id.material_design_linear_spin_fade_loader).setvisibility(view.visible); void androidballgridbeatloaderbar() { findviewbyid(r.id.material_design_ball_grid_beat_loader).setvisibility(view.visible); void androidballspinfadeloaderprogressbar() { findviewbyid(r.id.material_design_ball_spin_fade_loader).setvisibility(view.visible); void ballscalerippleprogressloaderexample() { findviewbyid(r.id.material_design_ball_scale_ripple_loader).setvisibility(view.visible); Output: 291

292 292

293 CHAPTER-15 Web Services & Client Services 15.1 Anatomy of Client - Server Anatomy of the Client/Server Model In client/server architecture, clients, or programs that represent users who need services, and servers, or programs that provide services, are separate logical objects that communicate over a network to perform tasks together. A client makes a request for a service and receives a reply to that request; a server receives and processes a request, and sends back the required response. Characteristics of Client/Server Architecture Asymmetrical protocols-there is a many-to-one relationship between clients and a server. Clients always initiate a dialog by requesting a service. Servers wait passively for requests from clients. Encapsulation of services-the server is a specialist: when given a message requesting a service, it determines how to get the job done. Servers can be upgraded without affecting clients as long as the published message interface used by both is unchanged. Integrity-The code and data for a server are centrally maintained, which results in cheaper maintenance and the protection of shared data integrity. At the same time, clients remain personal and independent. Location transparency-the server is a process that can reside on the same machine as a client or on a different machine across a network. Client/server software usually hides the location of a server from clients by redirecting service requests. A program can be a client, a server, or both. Message-based exchanges-clients and servers are loosely-coupled processes that can exchange service requests and replies using messages. Modular, extensible design-the modular design of a client/server application enables that application to be fault-tolerant. In a fault-tolerant system, failures may occur without causing a shutdown of the entire application. In a fault-tolerant client/server application, one or more servers may fail without stopping the whole system as long as the services offered on the failed servers are available on servers that are still active. Another advantage of modularity is that a client/server application can respond automatically to increasing or decreasing system loads by adding or shutting down one or more services or servers. 293

294 Platform independence-the ideal client/server software is independent of hardware or operating system platforms, allowing you to mix client and server platforms. Clients and servers can be deployed on different hardware using different operating systems, optimizing the type of work each performs. Reusable code-service programs can be used on multiple servers. Scalability-Client/server systems can be scaled horizontally or vertically..horizontal scaling means adding or removing client workstations with only a slight performance impact. Vertical scaling means migrating to a larger and faster server machine or adding server machines. Separation of Client/Server Functionality-Client/server is a relationship between processes running on the same or separate machines. A server process is a provider of services. A client is a consumer of services. Client/server provides a clean separation of functions. Shared resources-one server can provide services for many clients at the same time, and regulate their access to shared resources. Differences Between 2-Tier and 3-Tier Client/Server Architectures Every client/server application contains three functional units: Presentation logic or user interface (for example, ATM machines) Business logic (for example software that enables a customer to request an account balance) Data (for example, records of customer accounts) These functional units can reside on either the client or on one or more servers in your application. Which of the many possible variations you choose depends on how you split the application and which middleware you use to communicate between the tiers. In 2-tier client/server applications, the business logic is buried inside the user interface on the client or within the database on the server in the form of stored procedures. Alternatively, the business logic can be divided between the client and server. File servers and database servers with stored procedures are examples of 2-tier architecture. In 3-tier client/server applications, the business logic resides in the middle tier, separate from the data and user interface. In this way, processes can be managed and deployed separately from the user interface and the database. Also, 3-tier systems can integrate data from multiple sources. 294

295 2-Tier and 3-Tier Client/Server Models 15.2 Introduction To Web Services Android Web Service Creating web service application in android is not a difficult task. We can easily create a restful web service application in android to authenticate or save information into the external database such as oracle, mysql, postgre sql, sql server using other application developed in java,.net, php etc languages. That is what we are going to do. What is Web Service? A web service is a standard for exchanging information between different types of applications irrespective of language and platform. For example, an android application can interact with java or.net application using web services. Android Restful Web Service Example File: activity_main.xml RelativeLayout xmlns:android=" xmlns:tools=" 295

296 android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:hint="username" android:ems="10" > <requestfocus /> </EditText> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" 296

297 android:layout_margintop="67dp" android:ems="10" android:hint="password" android:inputtype="text Password" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_marginbottom="24dp" android:text="new User" /> <ProgressBar style="?android:attr/progressbarstylelarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="22dp" /> <Button 297

298 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="22dp" android:text="login" /> </RelativeLayout> File: activity_register_user.xml <RelativeLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="15dp" android:ems="10" android:hint="enter UserName" /> 298

299 <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="50dp" android:ems="10" android:hint="enter Password" android:inputtype="text Password" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:text="resister" /> <ProgressBar style="?android:attr/progressbarstylelarge" android:layout_width="wrap_content" android:layout_height="wrap_content" 299

300 android:layout_margintop="87dp" /> </RelativeLayout> MainActivity class File: MainActivity.java package com.example.newrestapi; import java.io.bufferedreader; import java.io.inputstream; import java.io.inputstreamreader; import java.util.arraylist; import java.util.list; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicnamevaluepair; import android.os.asynctask; import android.os.bundle; import android.app.activity; import android.content.intent; import android.view.view; import android.view.view.onclicklistener; 300

301 import android.widget.button; import android.widget.edittext; import android.widget.progressbar; import android.widget.toast; public class MainActivity extends Activity { EditText password,username; Button login,resister; ProgressBar progressbar; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); password=(edittext) findviewbyid(r.id.edittext2); username=(edittext) findviewbyid(r.id.edittext1); login=(button) findviewbyid(r.id.button1); resister=(button) findviewbyid(r.id.button2); //progess_msz.setvisibility(view.gone); progressbar=(progressbar) findviewbyid(r.id.progressbar1); progressbar.setvisibility(view.gone); resister.setonclicklistener(new OnClickListener() 301

302 public void onclick(view arg0) { // TODO Auto-generated method stub Intent intent=new Intent(MainActivity.this,ResisterUser.class); startactivity(intent); ); login.setonclicklistener(new OnClickListener() { public void onclick(view v) { progressbar.setvisibility(view.visible); String s1=username.gettext().tostring(); String s2=password.gettext().tostring(); new ExecuteTask().execute(s1,s2); ); class ExecuteTask extends AsyncTask<String, Integer, String> protected String doinbackground(string... params) { String res=postdata(params); 302

303 return protected void onpostexecute(string result) { progressbar.setvisibility(view.gone); //progess_msz.setvisibility(view.gone); Toast.makeText(getApplicationContext(), result, 3000).show(); public String PostData(String[] valuse) { String s=""; try { HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost(" List<NameValuePair> list=new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("name", valuse[0])); list.add(new BasicNameValuePair("pass",valuse[1])); httppost.setentity(new UrlEncodedFormEntity(list)); HttpResponse httpresponse= httpclient.execute(httppost); HttpEntity httpentity=httpresponse.getentity(); s= readresponse(httpresponse); 303

304 catch(exception exception) { return s; public String readresponse(httpresponse res) { InputStream is=null; String return_text=""; try { is=res.getentity().getcontent(); BufferedReader bufferedreader=new BufferedReader(new InputStreamReader(is)); String line=""; StringBuffer sb=new StringBuffer(); while ((line=bufferedreader.readline())!=null) { sb.append(line); return_text=sb.tostring(); catch (Exception e) { return return_text; 304

305 File: RegisterUser.java package com.example.newrestapi; import java.util.arraylist; import java.util.list; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicnamevaluepair; import android.os.asynctask; import android.os.bundle; import android.app.activity; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.progressbar; public class ResisterUser extends Activity { EditText username,passwprd; Button resister,login; ProgressBar progressbar; 305

306 protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_resister_user); username=(edittext) findviewbyid(r.id.edittext1);; passwprd=(edittext) findviewbyid(r.id.edittext2); resister=(button) findviewbyid(r.id.button1); progressbar=(progressbar) findviewbyid(r.id.progressbar1); progressbar.setvisibility(view.gone); resister.setonclicklistener(new OnClickListener() public void onclick(view v) { progressbar.setvisibility(view.visible); String s1=username.gettext().tostring(); String s2=passwprd.gettext().tostring(); new ExecuteTask().execute(s1,s2); ); class ExecuteTask extends AsyncTask<String, Integer, String> 306

307 protected String doinbackground(string... params) { PostData(params); return protected void onpostexecute(string result) { progressbar.setvisibility(view.gone); public void PostData(String[] valuse) { try { HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost( " List<NameValuePair> list=new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("name", valuse[0])); list.add(new BasicNameValuePair("pass",valuse[1])); httppost.setentity(new UrlEncodedFormEntity(list)); httpclient.execute(httppost); 307

308 catch(exception e) { System.out.println(e); File: AndroidManifest.xml You need to provide INTERNET permission in AndroidManifest.xml file. <xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.newrestapi" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <uses-permission android:name="android.permission.internet" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="com.example.newrestapi.mainactivity" 308

309 > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="com.example.newrestapi.resisteruser" > </activity> </application> </manifest> 309

310 15.3 Formats to Exchange Data Simple Object Access Protocol (SOAP) is a method for sending information to and from Web Services in an extensible format. SOAP can be used to send information or remote procedure calls encoded as XML. Essentially, SOAP serves as a universally accepted method of communication with web services. Businesses adhere to the SOAP conventions in order to simplify the process of interacting with Web Services. Web Service Description Language (WSDL) was created to provide information about how to connect to and query a specific Web Service. This document also adheres to strict formatting and organizational guidelines. However, the methods, parameters, and service information are application specific. Web Services perform different functionality and contain independent information, however they are all organized the same way. By creating a standard organizational architecture for these services, developers can effectively invoke and utilize them with little to no familiarization. To use a web service, a developer can follow the design standards of the WSDL to easily determine all the information and procedures associated with its usage. 310

311 Service Discovery-UDDI UDDI defines registries in which services can be published and found. The UDDI specification was creaed by Microsoft, Ariba, and IBM. UDDI defines a data structure and Application Programming Interface (API). In the three-tier model mentioned before, UDDI is the service broker. Its function is to enable service consumers to find appropriate service providers. Connecting to UDDI registries using Java can be accomplished through the Java API for XML Registries (JAXR). JAXR creates a layer of abstraction, so that it can be used with UDDI and other types of XML Registries, such as the ebxml Registry and Repository standard XML Format The Android Eclipse plugins now provides its own custom XML formatter. This formatter replaces the default Eclipse XML formatter, but there is a setting you can uncheck to revert to the default Eclipse XML formatter. The new formatter basically formats the XML the "standard" Android way out of the box, following the formatting conventions used in the various Android documentation, tutorial and platform source code. In particular, this means that it is going to format the XML differently depending on whether the XML is in a resource value file such as strings.xml, or a layout file, or a manifest file,and so on. This is one of the main reasons we provide our own formatter, because general text editors and IDEs tend to apply a single set of formatting rules to all files. Another key feature of the formatter is that it can sort the attributes, either alphabetically or in the "preferred" Android order: id style layout width and layout height other layout attributes, sorted alphabetically remaining attributes, sorted alphabetically This is on by default, so if you open an XML file and hit Ctrl-Shift-F to format the document, it will not only reformat your XML but it will reorder all the attributes to follow the above order as well. Finally, we now support "Format on Save", which is just like the equivalent action in Java files: It automatically applies a format on the whole document before saving the file. By default, the formatter will use the Android-defaults for indentation: 4 space characters. However, there is a setting for turning this off and making the indentation use the Eclipse XML indentation settings instead (which defaults to one tab character). Here are the current options related to the XML formatter: 311

312 Also note that files created with the New XML File and New Android Project wizards are now run through the formatter, so they should pick up any custom formatting configuration settings. Also, the new formatter tries to be smart about "partial formatting", where you've selected a range of text and you want to only format that portion; it tries to preserve the indentation level surrounding the node, and it can also format for example only the opening tag, which is useful when you set an attribute on a node that has children, and you expect only the opening tag to be reformatted to accommodate the attribute change and the child content should be left alone. These changes are important for the "Automatically format the XML edited by the visual layout editor" setting Types of XML Parsing XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it. Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML. 312

313 The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only. <?xml version="1.0"?> <current> <cityid=" "name="london"> <coordlon=" "lat=" "/> <country>gb</country> <sunrise=" t06:13:56"set=" t17:21:45"/> </city> <temperaturevalue="289.54"min="289.15"max="290.15"unit="kelvin"/> <humidityvalue="77"unit="%"/> <pressurevalue="1025"unit="hpa"/> </current> XML-Elements An xml file consist of many components. Here is the table defining the components of an XML file and their description. Sr.No Component & description 1 Prolog An XML file starts with a prolog. The first line that contains the information about a file is prolog 2 Events 313

314 An XML file has many events. Event could be like this. Document starts, Document ends, Tag start, Tag end and Text e.t.c 3 Text Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag. 4 Attributes Attributes are the additional properties of a tag such as value e.t.c XML -Parsing In the next step, we will create XMLPullParser object, but in order to create that we will first create XmlPullParserFactory object and then call its newpullparser() method to create XMLPullParser. Its syntax is given below private XmlPullParserFactory xmlfactoryobject = XmlPullParserFactory.newInstance(); private XmlPullParser myparser = xmlfactoryobject.newpullparser(); The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream. Its syntax is given below myparser.setinput(stream, null); The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below intevent= myparser.geteventtype(); while(event!=xmlpullparser.end_document){ 314

315 String name=myparser.getname(); switch(event){ casexmlpullparser.start_tag: break; casexmlpullparser.end_tag: if(name.equals("temperature")){ temperature= myparser.getattributevalue(null, "value"); break; event= myparser.next(); The method geteventtype returns the type of event that happens. e.g: Document start, tag start e.t.c. The method getname returns the name of the tag and since we are only interested in temperature, so we just check in conditional statement that if we got a temperature tag, we call the method getattributevalue to return us the value of temperature tag. Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below Sr.No Method & description 1 getattributecount() This method just Returns the number of attributes of the current start tag 315

316 2 getattributename(int index) This method returns the name of the attribute specified by the index value 3 getcolumnnumber() This method returns the Returns the current column number, starting from 0. 4 getdepth() This method returns Returns the current depth of the element. 5 getlinenumber() Returns the current line number, starting from 1. 6 getnamespace() This method returns the name space URI of the current element. 7 getprefix() This method returns the prefix of the current element 8 getname() This method returns the name of the tag 9 gettext() This method returns the text for that particular element 10 iswhitespace() This method checks whether the current TEXT event contains only whitespace characters. 316

317 Example Here is an example demonstrating the use of XML DOM Parser. It creates a basic application that allows you to parse XML. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/mainactivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Create a new XML file under Assets Folder/file.xml 5 Modify AndroidManifest.xml to add necessary internet permission 6 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import java.io.inputstream; import javax.xml.parsers.documentbuilder; import javax.xml.parsers.documentbuilderfactory; import org.w3c.dom.document; import org.w3c.dom.element; import org.w3c.dom.node; 317

318 import org.w3c.dom.nodelist; import android.app.activity; import android.os.bundle; import android.widget.textview; publicclassmainactivityextendsactivity{ TextView publicvoid oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv1=(textview)findviewbyid(r.id.textview1); try{ InputStreamis=getAssets().open("file.xml") DocumentBuilderFactory dbfactory =DocumentBuilderFactory.newInstance(); DocumentBuilder dbuilder =dbfactory.newdocumentbuilder(); Document doc =dbuilder.parse(is); Element element=doc.getdocumentelement(); element.normalize(); NodeList nlist =doc.getelementsbytagname("employee"); for(int i=0; i<nlist.getlength(); i++){ 318

319 Node node =nlist.item(i); if(node.getnodetype()==node.element_node){ Element element2 =(Element) node; tv1.settext(tv1.gettext()+"\nname : "+ getvalue("name", element2)+"\n"); tv1.settext(tv1.gettext()+"surname : "+ getvalue("surname", element2)+"\n"); tv1.settext(tv1.gettext()+" "); catch(exception e){e.printstacktrace(); privatestaticstring getvalue(string tag,element element){ NodeList nodelist= element.getelementsbytagname(tag).item(0).getchildnodes(); Node node =nodelist.item(0); return node.getnodevalue(); Following is the content of Assets/file.xml. <?xml version="1.0"?> <records> <employee> 319

320 <name>sairamkrishna</name> <surname>mammahe</surname> <salary>50000</salary> </employee> <employee> <name>gopal </name> <surname>varma</surname> <salary>60000</salary> </employee> <employee> <name>raja</name> <surname>hr</surname> <salary>70000</salary> </employee> </records> Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> 320

321 <RelativeLayoutxmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifestxmlns:android=" package="com.example.sairamkrishna.myapplication"> <application 321

322 android:allowbackup="true" <activity android:name=".mainactivity" <intent-filter> <actionandroid:name="android.intent.action.main"/> <categoryandroid:name="android.intent.category.launcher"/> </intent-filter> </activity> </application> </manifest> Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window 322

323 15.6 JSON Format SOAP SOAP (Simple Object Access Protocol) is an XML based message format. Here is a simple SOAP message: <?xml version="1.0"?> <soap:envelope xmlns:soap=" soap:encodingstyle=" <soap:header> 323

324 </soap:header> <soap:body>... message data... <soap:fault> </soap:fault> </soap:body> </soap:envelope> As you can see a SOAP message consists of: Envelope o Header o Body Message Data Fault (optional) The same SOAP message structure is used to send both requests and responses between client and web service. The Fault element inside the Body element is optional. A Fault element is only sent back if an error occurs inside the web service. Otherwise the normal message data is sent back. SOAP doesn't specify how a message gets from the client to the web service, although the most common scenario is via HTTP. REST + XML REST (REpresentational State Transfer) style web services work a bit different from SOAP web services. A REST request is a simple HTTP request just like a regular browser would send to a web server. There is typically no XML request sent. A REST response is typically an XML document sent back in a regular HTTP response, just as if a browser had requested it. 324

325 In REST you don't think so much in terms of "services", but rather in "resources". A resource has a given URL, just like an HTML page in a web site. An example of a resource could be a user profile in a social application. Such a resource could have the URL: This URL might return an XML document (resource) describing me. Here is how the XML file returned could look: <profile> <firstname>jakob</firstname> <lastname>jenkov</lastname> <address> <street>the Road 123</street> <zip>12345</zip> <city>copenhagen</city> </address> </profile> REST also naturally supports collections of resources. For instance, this URL might represent a list of all public user profiles: Here is an example of how such a profile list in XML could look: <profiles> <profile>...</profile> <profile>...</profile> <profile>...</profile> </profiles> The two URL's above only reads a resource or resource collection. If you need to modify a resource in REST, you do so by sending different HTTP request to the server. When you read a resource you send an HTTP GET request. If you need to write a resource, you would send 325

326 an HTTP PUT instead. If you need to delete a resource you would send an HTTP DELETE etc. REST + JSON REST + JSON is basically the same as REST + XML except that data is transfered in JSON (JavaScript Object Notation) instead of XML. The advantage of JSON over XML is that web browser are able to parse the JSON structures into JavaScript objects natively. You don't have to parse the JSON yourself in the browser then. That is much easier to work with in applications that use AJAX a lot. Here is a JSON example: { firstname : "Jakob", lastname : "Jenkov", address : { street : "The Road 123", zip : "12345", city : "Copenhagen" XML RPC XML RPC is closer to SOAP than it is to REST. XML RPC has both a request and a response format. XML RPC is a somewhat simpler protocol than SOAP is. It is also closer modeled to a regular procedure call. Some people claim that XML RPC is now dead or obsolete. Here is a simple XML RPC request example: POST /RPC2 HTTP/1.0 User-Agent: My XML-RPC API/1.0.0 (Win7) Host: jenkov.com Content-Type: text/xml Content-length:

327 <?xml version="1.0"?> <methodcall> <methodname>getprofile</methodname> <params> <param> <value><string>jakob Jenkov</string></value> </param> </params> </methodcall> Note: The Content-Length HTTP header is not set correctly. It should contain the number of bytes in the XML request. Here is an XML RPC response example: HTTP/ OK Connection: close Content-Length: 213 Content-Type: text/xml Date: Wed, 03 Feb :00:00 GMT+1 Server: jenkov.com <?xml version="1.0"?> <methodresponse> <params> <param> <struct> <member> 327

328 <name>firstname</name> <value>jakob</value> </member> <member> <name>lastname</name> <value>jenkov</value> </member> <member> <name>address</name> <value> <struct>...</struct> </value> </member> </struct> </param> </params> </methodresponse> 15.7 Types of JSON Parsing. JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer. 328

329 The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only. { "sys": { "country":"gb", "sunrise": , "sunset": , "weather":[ { "id":711, "main":"smoke", "description":"smoke", "icon":"50n" ], "main": { "temp":304.15, "pressure":1009, 329

330 JSON - Elements An JSON file consist of many components. Here is the table defining the components of an JSON file and their description Sr.No Component & description Array([) In a JSON file, square bracket ([) represents a JSON array 1 2 Objects({) In a JSON file, curly bracket ({) represents a JSON object 3 Key A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object 4 Value Each key has a value that could be string, integer or double e.t.c 330

331 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); The last step is to parse the JSON. A JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below JSONObjectsys = reader.getjsonobject("sys"); country= sys.getstring("country"); JSONObjectmain = reader.getjsonobject("main"); temperature= main.getstring("temp"); The method getjsonobject returns the JSON object. The method getstring returns the string value of the specified key. Apart from the these methods, there are other methods provided by this class for better parsing JSON files. These methods are listed below Sr.No Method & description 1 get(string name) This method just Returns the value but in the form of Object type 2 getboolean(string name) 331

332 This method returns the boolean value specified by the key 3 getdouble(string name) This method returns the double value specified by the key 4 getint(string name) This method returns the integer value specified by the key 5 getlong(string name) This method returns the long value specified by the key 6 length() This method returns the number of name/value mappings in this object.. 7 names() This method returns an array containing the string names in this object. Example To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application. 2 Modify src/mainactivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Modify the res/values/string.xml to add necessary string components 332

333 5 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/mainactivity.java. package com.example.tutorialspoint7.myapplication; import android.os.asynctask; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.util.log; import android.widget.listadapter; import android.widget.listview; import android.widget.simpleadapter; import android.widget.toast; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import java.util.arraylist; import java.util.hashmap; publicclassmainactivityextendsappcompatactivity{ 333

334 privatestring TAG =MainActivity.class.getSimpleName(); privatelistview lv; ArrayList<HashMap<String,String>> Protectedvoid oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); contactlist=newarraylist<>(); lv=(listview) findviewbyid(r.id.list); newgetcontacts().execute(); Protectedvoid onpreexecute(){ super.onpreexecute(); Toast.makeText(MainActivity.this,"Json Data is ProtectedVoid doinbackground(void... arg0){ HttpHandlersh=newHttpHandler(); 334

335 // Making a request to url and getting response Stringurl=" String jsonstr= sh.makeservicecall(url); Log.e(TAG,"Response from url: "+ jsonstr); if(jsonstr!=null){ try{ JSONObject jsonobj =newjsonobject(jsonstr); // Getting JSON Array node JSONArray contacts =jsonobj.getjsonarray("contacts"); // looping through All Contacts for(int i =0; i < contacts.length(); i++){ JSONObject c =contacts.getjsonobject(i); String id =c.getstring("id"); String name =c.getstring("name"); String =c.getstring(" "); String address =c.getstring("address"); String gender =c.getstring("gender"); // Phone node is JSON Object JSONObject phone =c.getjsonobject("phone"); String mobile =phone.getstring("mobile"); String home =phone.getstring("home"); 335

336 String office =phone.getstring("office"); // tmp hash map for single contact HashMap<String,String> contact =newhashmap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put(" ", ); contact.put("mobile", mobile); // adding contact to contact list contactlist.add(contact); catch(finaljsonexception e){ Log.e(TAG,"Json parsing error: "+ e.getmessage()); Publicvoid run(){ Toast.makeText(getApplicationContext(), "Json parsing error: "+ e.getmessage(), Toast.LENGTH_LONG).show(); ); 336

337 else{ Log.e(TAG,"Couldn't get json from server."); Publicvoid run(){ Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show(); ); Protectedvoid onpostexecute(void result){ super.onpostexecute(result); ListAdapter adapter =newsimpleadapter(mainactivity.this, contactlist, R.layout.list_item,newString[]{" ","mobile", newint[]{r.id. , R.id.mobile); lv.setadapter(adapter); 337

338 Following is the modified content of the xml HttpHandler.java. package com.example.tutorialspoint7.myapplication; import android.util.log; import java.io.bufferedinputstream; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.protocolexception; import java.net.url; publicclasshttphandler{ privatestaticfinalstring TAG =HttpHandler.class.getSimpleName(); 338

339 publichttphandler(){ publicstring makeservicecall(string requrl){ String response =null; try{ URL url =newurl(requrl); HttpURLConnection conn =(HttpURLConnection)url.openConnection(); conn.setrequestmethod("get"); // read the response InputStreamin=newBufferedInputStream(conn.getInputStream()); response= convertstreamtostring(in); catch(malformedurlexception e){ Log.e(TAG,"MalformedURLException: "+ e.getmessage()); catch(protocolexception e){ Log.e(TAG,"ProtocolException: "+ e.getmessage()); catch(ioexception e){ Log.e(TAG,"IOException: "+ e.getmessage()); catch(exception e){ Log.e(TAG,"Exception: "+ e.getmessage()); 339

340 return response; privatestring convertstreamtostring(inputstreamis){ BufferedReader reader =newbufferedreader(newinputstreamreader(is)); StringBuilder sb =newstringbuilder(); String line; try{ while((line = reader.readline())!=null){ sb.append(line).append('\n'); catch(ioexception e){ e.printstacktrace(); finally{ try{ is.close(); catch(ioexception e){ e.printstacktrace(); 340

341 return sb.tostring(); Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayoutxmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.tutorialspoint7.myapplication.mainactivity"> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content"/> </RelativeLayout> Following is the modified content of the xml res/layout/list_item.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android=" android:layout_width="fill_parent" android:layout_height="wrap_content" 341

342 android:orientation="vertical" <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingbottom="2dip" <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textcolor="#5d5d5d" android:textstyle="bold"/> </LinearLayout> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifestxmlns:android=" package="com.example.tutorialspoint7.myapplication"> 342

343 <uses-permissionandroid:name="android.permission.internet"/> <application android:allowbackup="true" android:supportsrtl="true" <activity android:name=".mainactivity"> <intent-filter> <actionandroid:name="android.intent.action.main"/> <categoryandroid:name="android.intent.category.launcher"/> </intent-filter> </activity> </application> </manifest> Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's 343

344 activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window Above Example showing the data from string json,the data has contained employer details as well as salary information. 344

345 CHAPTER Introduction to google maps Google Maps is a Web-based service that provides detailed information about geographical regions and sites around the world. In addition to conventional road maps, Google Maps offers aerial and satellite views of many places. In some cities, Google Maps offers street views comprising photographs taken from vehicles. Google Maps offers several services as part of the larger Web application, as follows. A route planner offers directions for drivers, bikers, walkers, and users of public transportation who want to take a trip from one specific location to another. The Google Maps application program interface (API) makes it possible for Web site administrators to embed Google Maps into a proprietary site such as a real estate guide or community service page. Google Maps for Mobile offers a location service for motorists that utilizes the Global Positioning System (GPS) location of the mobile device (if available) along with data from wireless and cellular networks. Google Street View enables users to view and navigate through horizontal and vertical panoramic street level images of various cities around the world. Supplemental services offer images of the moon, Mars, and the heavens for hobby astronomers. Android allows us to integrate google maps in our application. You can show any location on the map, or can show different routes on the map etc. You can also customize the map according to your choices. In your android studio Run your project Click on Gradle menu 345

346 Expand Gradle task tree Click on android-> signingreport and see the magic It will tell you everything Result Under Run Tab If Android Studio < 2.2 From android studio

347 Result will be available under Run console but use highlighted toggle button Or Second Way is Create new project in android studio New -> Google Maps Activity 347

348 then open google_maps_api.xml xml file as shown in pics you will see your SHA key 348

349 Under Gradle Projects Window > Select Root Project > signingreport > double click Next 349

350 Creating a Sample on Latitute and Longitude activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.sreya.googlelatlng.mainactivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancelarge" android:text="latitude" 350

351 android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_margintop="85dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancelarge" android:text="0.0" android:layout_alignparentright="true" android:layout_alignparentend="true" android:layout_marginright="45dp" android:layout_marginend="45dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancelarge" android:text="longitude" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_margintop="49dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancelarge" 351

352 android:text="0.0" /> </RelativeLayout> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.sreya.googlelatlng"> <uses-permission android:name="android.permission.access_fine_location"></usespermission> <uses-permission android:name="android.permission.access_coarse_location"></uses-permission> <uses-permission android:name="android.permission.internet"></uses-permission> <application android:allowbackup="true" android:supportsrtl="true" <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for App Indexing. See for more information. --> 352

353 <meta-data android:name="com.google.android.gms.version" /> </application> </manifest> MainActivity.java package com.example.sreya.googlelatlng; import android.manifest; import android.app.activity; import android.content.context; import android.content.pm.packagemanager; import android.location.criteria; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; import android.net.uri; import android.os.bundle; import android.support.v4.app.activitycompat; import android.widget.textview; import android.widget.toast; import com.google.android.gms.appindexing.action; import com.google.android.gms.appindexing.appindex; import com.google.android.gms.common.api.googleapiclient; public class MainActivity extends Activity implements LocationListener { double lat,lng; TextView tv1, tv2; /** 353

354 * ATTENTION: This was auto-generated to implement the App Indexing API. * See for more information. */ private GoogleApiClient protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv1 = (TextView) findviewbyid(r.id.textview2); tv2 = (TextView) findviewbyid(r.id.textview4); LocationManager locationmanager = (LocationManager) getsystemservice(context.location_service); Criteria criteria = new Criteria(); String provider = locationmanager.getbestprovider(criteria, false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onrequestpermissionsresult(int requestcode, String[] permissions, // int[] grantresults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; Location location = locationmanager.getlastknownlocation(locationmanager.network_provider); if(location==null) { 354

355 Toast.makeText(getApplicationContext(),"Network not found!!!!!",toast.length_long).show(); else { onlocationchanged(location); // ATTENTION: This was auto-generated to implement the App Indexing API. // See for more information. client = new public void onlocationchanged(location location) { lat=location.getlatitude(); lng=location.getlongitude(); tv1.settext(""+lat); public void onstatuschanged(string s, int i, Bundle bundle) public void onproviderenabled(string s) public void onproviderdisabled(string s) { 355

356 @Override public void onstart() { super.onstart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See for more information. client.connect(); Action viewaction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main ", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse(" // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.sreya.googlelatlng/http/host/path") ); AppIndex.AppIndexApi.start(client, public void onstop() { super.onstop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See for more information. Action viewaction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main ", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. 356

357 Uri.parse(" // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.sreya.googlelatlng/http/host/path") ); AppIndex.AppIndexApi.end(client, viewaction); client.disconnect(); Output: Creating a Sample Application 357

358 google_maps_api.xml <resources> <!-TODO: Before you run your application, you need a Google Maps API key. To get one, follow this link, follow the directions and press "Create" at the end: apiid=maps_android_backend&keytype=client_side_android&r=60:ac:ea:eb:21: 19:D5:B8:85:FB:9E:70:9D:FE:63:CB:04:70:D1:21%3Bcom.example.sreya.googlemaps You can also add your credentials to an existing key, using this line: 60:AC:EA:EB:21:19:D5:B8:85:FB:9E:70:9D:FE:63:CB:04:70:D1:21;com.example.sreya.go oglemaps Alternatively, follow the directions here: Once you have your key (it starts with "AIza"), replace the "google_maps_key" string in this file. --> <string name="google_maps_key" templatemergestrategy="preserve" translatable="false">your_key_here</string> 358

359 </resources> ActivityManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.example.sreya.googlemaps"> <!-The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine location permissions for the 'MyLocation' functionality. --> <uses-permission android:name="android.permission.access_fine_location" /> <application android:allowbackup="true" android:supportsrtl="true" <!-- 359

360 The API key for Google Maps-based APIs is defined as a string resource. (See the file "res/values/google_maps_api.xml"). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. --> <meta-data android:name="com.google.android.geo.api_key" android:value="@string/google_maps_key" /> <activity android:name=".mapsactivity" android:label="@string/title_activity_maps"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> 360

361 </manifest> MapsActivity.java package com.example.sreya.googlemaps; import android.support.v4.app.fragmentactivity; import android.os.bundle; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.onmapreadycallback; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapfragment = (SupportMapFragment) 361

362 getsupportfragmentmanager().findfragmentbyid(r.id.map); public void onmapready(googlemap googlemap) { mmap = googlemap; // Add a marker in Sydney and move the camera LatLng tarnaka = new LatLng( , ); mmap.addmarker(new MarkerOptions().position(tarnaka).title("Marker in Tarnaka")); mmap.movecamera(cameraupdatefactory.newlatlng(tarnaka)); Output: 362

363 CHAPTER

364 Deployment Creating an Account and Deploying app in Playstore You have finished your Android app, and celebrated its perfection with many flagons of ale (or pitchers of beer). Hooray! Now you re ready to send your app out into the world. Soon it will reside not only on your own Android device, but on the devices of people around the globe. It s an exciting step! There are several ways to distribute your Android app. This Android app distribution tutorial will cover two of the most common channels: the Google Play Store, where over 1.8 million Android apps are available, and the Amazon Appstore, which has over 300,000. In this step-by-step, you ll see how to take your finished Android app and release it to the Google Play Store and other stores. Getting Started To publish an app, you first need a finished app, Currently, the best way to refactor an app s package name in Android Studio is to start in the Project pane of Android Studio, with the Android view chosen. Select the gear icon that looks like this: gear_icon You will see a drop-down menu with several project viewing options. Uncheck Compact Empty Middle Packages if it is not already unchecked: 364

365 Now you can refactor the parts of the package name separately. Right-click on the package named example, select Refactor\Rename, and change it to your name or domain name. Then do the same for the package omgandroid. Next, open build.gradle (the one labeled Module: OMGAndroid, NOT the one for whole project), and find defaultconfig. Add a applicationid parameter with your new package name: defaultconfig { applicationid 'com.colemanfrancis.bookmastergeneral' minsdkversion 14 targetsdkversion 23 Finally, open manifest\androidmanifest.xml, find the manifest tag at the top of the file, and locate the package attribute within it. Update it with your new package name: <manifest xmlns:android=" 365

366 package="com.colemanfrancis.bookmastergeneral" android:versioncode="1" android:versionname="1.0"> Build and run to verify that your refactoring worked correctly. With your unique package name in hand, you re now ready to package your app for distribution. Creating a Signed APK When developing on the Android operating system, you use the Android application package (APK) format to distribute apps. Android requires that APKs are digitally signed with a certificate before they can be installed. The certificate is used to identify the author of the app. More information about app signing can be found here. A signed APK can be generated manually from command line or in Android Studio. In Android Studio, select Build\Generate Signed APK 366

367 Your app only has one module, so select Next. With your app module chosen, you need to tell Android Studio how to sign the APK. You ll use a key store, which will stay private to you. Android Studio will guide you through creating a new key store; start by selecting Create new Choose a filename and location on your system, set and confirm a secure password, and fill in the rest of the information about yourself 367

368 Click OK, and Android Studio will create your key store. You ll need that file, with its password info, to make any updates to your app, so don t lose it! With your new key store, Android Studio returns you to the dialog box you saw before. Now the key store information is pre-filled, so just click Next. 368

369 Choose a destination folder for your signed APK, specify your Build Type as release, and click Finish. When the packaging process is complete, Android Studio will notify you that your APK is ready, and let you open it in Finder: The Google Play Developer Console To submit an app to Google Play, you first need a Google Account. Create one here (or sign in, if you already have an account) before going further. When you are signed into your Google Account, navigate to the Google Play Developer Console. You should see a screen like this: 369

370 Agree to the Google Play Developer distribution agreement, pay the one-time $25 Google Developer Registration Fee, then complete your Developer Profile on this screen: With your developer account now registered, your developer console has more options. Click Publish an Android App on Google Play to continue. 370

371 Since this is your first application, you re given a dialog box to specify the app name and a choice on how to begin. Type in your app name and choose Upload APK. This creates a draft store listing for your app, currently containing nothing except the app title. To begin, click Upload your first APK to Production. 371

372 Choose the APK file you created earlier, and upload it. When the upload is complete, you will see the app listing updated like this: Notice that the check mark next to APK is green, indicating that your APK is ready! Time to move on to the remaining check mark. Completing the Store Listing 372

373 Bookmaster General is a pretty simple app, so the rest of the process will be easy. Click on the Store Listing check mark in the menu on the left page and fill in the Short Description and Full Description fields with information about the app: Next, upload at least two screenshots of the app. If you have the app on an Android device, you can simply take screenshots straight from the device. If you prefer to use an emulator for the screenshots, you can easily make these in Android Studio. Build and run the app, then navigate to the part of the app where you d like the screenshot. With the Android Monitor tab opened in Android Studio, click the camera icon on the far left Android Studio will present you with the captured image from the emulator. Click Save and select the file location on your system. Drag these images onto your store listing where you see the following prompt 373

374 In addition to screenshots, you need to upload a high-resolution version of the app icon and a feature graphic to display at the top of the page. Complete the store listing by specifying an Application Type, Category, Content rating, and Contact . Other fields are optional This questionnaire asks a straightforward series of questions about the content of the app. For those using our sample app, Bookmaster General is in the Reference, News, or Educational category; answer No to all the content questions. If you re using your own app, give the appropriate answers. Once you are finished, click Save questionnaire, then Calculate rating. You will see the ratings for the various locales where your app may be on sale 374

375 Scroll to the bottom of the list and click Apply rating. The Content Rating check mark is now green. Select the Pricing & Distribution check mark for the final step: setting the price of your app, and in which countries it will be available. For this example, the app will be free and available universally. The Free pricing option is selected by default, so keep that choice. Check the box next to SELECT ALL COUNTRIES. 375

376 Scroll down past the list of countries, and you will find several more distribution options. Check the boxes by Content guidelines and US export laws to indicate your app s compliance with relevant rules, then scroll to the top of the page and click Save draft. With that, the final check box is green, and the Publish app button in the top-right of the console is now active! When you re satisfied with your app and store listing, go ahead and click it. Your app listing status now updates to Pending Publication, like this: It generally takes at least a few hours for your app to be available in Google Play, so go grab some pizza. Eventually you ll see a listing 376

377 Congratulations on your first app in Google Play. 377

SD Module- Android Programming

SD Module- Android Programming Assignment No. 1 SD Module- Android Programming R (2) C (4) V (2) T (2) Total (10) Dated Sign Title: Download Install and Configure Android Studio on Linux /windows platform. Problem Definition: Install

More information

Android App Development. Ahmad Tayeb

Android App Development. Ahmad Tayeb Android App Development Ahmad Tayeb Ahmad Tayeb Lecturer @ Department of Information Technology, Faculty of Computing and Information Technology, KAU Master degree from Information Sciences and Technologies,

More information

Introduction To Android

Introduction To Android Introduction To Android Mobile Technologies Symbian OS ios BlackBerry OS Windows Android Introduction to Android Android is an operating system for mobile devices such as smart phones and tablet computers.

More information

SD Module-1 Android Dvelopment

SD Module-1 Android Dvelopment SD Module-1 Android Dvelopment Experiment No: 05 1.1 Aim: Download Install and Configure Android Studio on Linux/windows platform. 1.2 Prerequisites: Microsoft Windows 10/8/7/Vista/2003 32 or 64 bit Java

More information

Android App Development. Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore

Android App Development. Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore Android App Development Muhammad Sharjeel COMSATS Institute of Information Technology, Lahore Mobile devices (e.g., smartphone, tablet PCs, etc.) are increasingly becoming an essential part of human life

More information

Mobile Computing. Introduction to Android

Mobile Computing. Introduction to Android Mobile Computing Introduction to Android Mobile Computing 2011/2012 What is Android? Open-source software stack for mobile devices OS, middleware and key applications Based upon a modified version of the

More information

Java Training Center - Android Application Development

Java Training Center - Android Application Development Java Training Center - Android Application Development Android Syllabus and Course Content (3 months, 2 hour Daily) Introduction to Android Android and it's feature Android releases and Versions Introduction

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Teodoro Montanaro Politecnico di Torino, 2016/2017 Disclaimer This is only a fast introduction: It is not complete (only scrapes the surface) Only superficial

More information

Android Application Development

Android Application Development Android Application Development Octav Chipara What is Android A free, open source mobile platform A Linux-based, multiprocess, multithreaded OS Android is not a device or a product It s not even limited

More information

Beginning Android 4 Application Development

Beginning Android 4 Application Development Beginning Android 4 Application Development Lee, Wei-Meng ISBN-13: 9781118199541 Table of Contents INTRODUCTION xxi CHAPTER 1: GETTING STARTED WITH ANDROID PROGRAMMING 1 What Is Android? 2 Android Versions

More information

Android Development Tools = Eclipse + ADT + SDK

Android Development Tools = Eclipse + ADT + SDK Lesson 2 Android Development Tools = Eclipse + ADT + SDK Victor Matos Cleveland State University Portions of this page are reproduced from work created and shared by Google and used according to terms

More information

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna Programming with Android: System Architecture Luca Bedogni Marco Di Felice Dipartimento di Scienze dell Informazione Università di Bologna Outline Android Architecture: An Overview Android Dalvik Java

More information

Android for Ubiquitous Computing Researchers. Andrew Rice University of Cambridge 17-Sep-2011

Android for Ubiquitous Computing Researchers. Andrew Rice University of Cambridge 17-Sep-2011 Android for Ubiquitous Computing Researchers Andrew Rice University of Cambridge 17-Sep-2011 Getting started Website for the tutorial: http://www.cl.cam.ac.uk/~acr31/ubicomp/ Contains links to downloads

More information

Android. Lesson 1. Introduction. Android Developer Fundamentals. Android Developer Fundamentals. to Android 1

Android. Lesson 1. Introduction. Android Developer Fundamentals. Android Developer Fundamentals. to Android 1 Android Lesson 1 1 1 1.0 to Android 2 Contents Android is an ecosystem Android platform architecture Android Versions Challenges of Android app development App fundamentals 3 Android Ecosystem 4 What is

More information

CS 528 Mobile and Ubiquitous Computing Lecture 2a: Introduction to Android Programming. Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 2a: Introduction to Android Programming. Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 2a: Introduction to Android Programming Emmanuel Agu Editting in Android Studio Recall: Editting Android Can edit apps in: Text View: edit XML directly Design

More information

Overview. What are layouts Creating and using layouts Common layouts and examples Layout parameters Types of views Event listeners

Overview. What are layouts Creating and using layouts Common layouts and examples Layout parameters Types of views Event listeners Layouts and Views http://developer.android.com/guide/topics/ui/declaring-layout.html http://developer.android.com/reference/android/view/view.html Repo: https://github.com/karlmorris/viewsandlayouts Overview

More information

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna Programming with Android: System Architecture Luca Bedogni Marco Di Felice Dipartimento di Scienze dell Informazione Università di Bologna Outline Android Architecture: An Overview Android Dalvik Java

More information

Mobile OS. Symbian. BlackBerry. ios. Window mobile. Android

Mobile OS. Symbian. BlackBerry. ios. Window mobile. Android Ing. Elton Domnori December 7, 2011 Mobile OS Symbian BlackBerry Window mobile Android ios Mobile OS OS First release Last release Owner Android Android 1.0 September 2008 Android 4.0 May 2011 Open Handset

More information

CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android Programming. Emmanuel Agu

CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android Programming. Emmanuel Agu CS 4518 Mobile and Ubiquitous Computing Lecture 2: Introduction to Android Programming Emmanuel Agu Android Apps: Big Picture UI Design using XML UI design code (XML) separate from the program (Java) Why?

More information

ANDROID USER INTERFACE

ANDROID USER INTERFACE 1 ANDROID USER INTERFACE Views FUNDAMENTAL UI DESIGN Visual interface element (controls or widgets) ViewGroup Contains multiple widgets. Layouts inherit the ViewGroup class Activities Screen being displayed

More information

Required Core Java for Android application development

Required Core Java for Android application development Required Core Java for Android application development Introduction to Java Datatypes primitive data types non-primitive data types Variable declaration Operators Control flow statements Arrays and Enhanced

More information

Android Basics. Android UI Architecture. Android UI 1

Android Basics. Android UI Architecture. Android UI 1 Android Basics Android UI Architecture Android UI 1 Android Design Constraints Limited resources like memory, processing, battery à Android stops your app when not in use Primarily touch interaction à

More information

Android Programming (5 Days)

Android Programming (5 Days) www.peaklearningllc.com Android Programming (5 Days) Course Description Android is an open source platform for mobile computing. Applications are developed using familiar Java and Eclipse tools. This Android

More information

UNIT:2 Introduction to Android

UNIT:2 Introduction to Android UNIT:2 Introduction to Android 1 Syllabus 2.1 Overview of Android 2.2 What does Android run On Android Internals? 2.3 Android for mobile apps development 2.5 Environment setup for Android apps Development

More information

CS260 Intro to Java & Android 04.Android Intro

CS260 Intro to Java & Android 04.Android Intro CS260 Intro to Java & Android 04.Android Intro Winter 2015 Winter 2015 CS260 - Intro to Java & Android 1 Android - Getting Started Android SDK contains: API Libraries Developer Tools Documentation Sample

More information

MC Android Programming

MC Android Programming MC1921 - Android Programming Duration: 5 days Course Price: $3,395 Course Description Android is an open source platform for mobile computing. Applications are developed using familiar Java and Eclipse

More information

Building User Interface for Android Mobile Applications II

Building User Interface for Android Mobile Applications II Building User Interface for Android Mobile Applications II Mobile App Development 1 MVC 2 MVC 1 MVC 2 MVC Android redraw View invalidate Controller tap, key pressed update Model MVC MVC in Android View

More information

ANDROID DEVELOPMENT. Course Details

ANDROID DEVELOPMENT. Course Details ANDROID DEVELOPMENT Course Details centers@acadgild.com www.acadgild.com 90360 10796 01 Brief About the Course Android s share of the global smartphone is 81%. The Google Certified Android development

More information

Introduction to Android

Introduction to Android Introduction to Android http://myphonedeals.co.uk/blog/33-the-smartphone-os-complete-comparison-chart www.techradar.com/news/phone-and-communications/mobile-phones/ios7-vs-android-jelly-bean-vs-windows-phone-8-vs-bb10-1159893

More information

BCA 6. Question Bank

BCA 6. Question Bank BCA 6 030010601 : Introduction to Mobile Application Development Question Bank Unit 1: Introduction to Android and Development tools Short questions 1. What kind of tool is used to simulate Android application?

More information

Programming with Android: System Architecture. Luca Bedogni. Dipartimento di Scienze dell Informazione Università di Bologna

Programming with Android: System Architecture. Luca Bedogni. Dipartimento di Scienze dell Informazione Università di Bologna Programming with Android: System Architecture Luca Bedogni Dipartimento di Scienze dell Informazione Università di Bologna Outline Android Architecture: An Overview Android Java Virtual Machine Android

More information

Android OS. Operating System based on Linux [ ] [Jonas Teuscher, Alex Cuordileone, Cédric Glaus]

Android OS. Operating System based on Linux [ ] [Jonas Teuscher, Alex Cuordileone, Cédric Glaus] 1 Android OS Operating System based on Linux [24-02-16] [Jonas Teuscher, Alex Cuordileone, Cédric Glaus] 1 https://www.androidpit.com/android-marshmallow-update-overview-for-smartphones-and-tablets 2 https://blog.idrsolutions.com/2014/12/android-apps-ide-for-java-coder-programmers/

More information

Android App Development

Android App Development Android App Development Outline Introduction Android Fundamentals Android Studio Tutorials Introduction What is Android? A software platform and operating system for mobile devices Based on the Linux kernel

More information

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment FRAGMENTS Fragments An activity is a container for views When you have a larger screen device than a phone like a tablet it can look too simple to use phone interface here. Fragments Mini-activities, each

More information

LECTURE 08 UI AND EVENT HANDLING

LECTURE 08 UI AND EVENT HANDLING MOBILE APPLICATION DEVELOPMENT LECTURE 08 UI AND EVENT HANDLING IMRAN IHSAN ASSISTANT PROFESSOR WWW.IMRANIHSAN.COM User Interface User Interface The Android Widget Toolbox 1. TextView 2. EditText 3. Spinner

More information

Android Development Tutorial. Yi Huang

Android Development Tutorial. Yi Huang Android Development Tutorial Yi Huang Contents What s Android Android architecture Android software development Hello World on Android More 2 3 What s Android Android Phones Sony X10 HTC G1 Samsung i7500

More information

IJRDTM Kailash ISBN No Vol.17 Issue

IJRDTM Kailash ISBN No Vol.17 Issue ABSTRACT ANDROID OPERATING SYSTEM : A CASE STUDY by Pankaj Research Associate, GGSIP University Android is a software stack for mobile devices that includes an operating system, middleware and key applications.

More information

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu Announcements Group formation: Projects 2, 3 and final project will be

More information

CS 528 Mobile and Ubiquitous Computing Lecture 2a: Android UI Design in XML + Examples. Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 2a: Android UI Design in XML + Examples. Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 2a: Android UI Design in XML + Examples Emmanuel Agu Android UI Design in XML Recall: Files Hello World Android Project XML file used to design Android UI

More information

CSCU9YH Development with Android

CSCU9YH Development with Android CSCU9YH Development with Android Computing Science and Mathematics University of Stirling 1 Android Context 3 Smartphone Market share Source: http://www.idc.com/promo/smartphone-market-share/os 4 Smartphone

More information

Programming Android UI. J. Serrat Software Design December 2017

Programming Android UI. J. Serrat Software Design December 2017 Programming Android UI J. Serrat Software Design December 2017 Preliminaries : Goals Introduce basic programming Android concepts Examine code for some simple examples Limited to those relevant for the

More information

Android-Basics. Praktikum Mobile und Verteilte Systeme. Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld

Android-Basics. Praktikum Mobile und Verteilte Systeme. Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld Praktikum Mobile und Verteilte Systeme Android-Basics Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld http://www.mobile.ifi.lmu.de WS 2017/18 Programming with Android Today: Android basics

More information

Android UI: Overview

Android UI: Overview 1 Android UI: Overview An Activity is the front end component and it can contain screens. Android screens are composed of components or screen containers and components within the containers Screen containers

More information

Syllabus- Java + Android. Java Fundamentals

Syllabus- Java + Android. Java Fundamentals Introducing the Java Technology Syllabus- Java + Android Java Fundamentals Key features of the technology and the advantages of using Java Using an Integrated Development Environment (IDE) Introducing

More information

SHWETANK KUMAR GUPTA Only For Education Purpose

SHWETANK KUMAR GUPTA Only For Education Purpose Introduction Android: INTERVIEW QUESTION AND ANSWER Android is an operating system for mobile devices that includes middleware and key applications, and uses a modified version of the Linux kernel. It

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi Introduction An application is composed of at least one Activity GUI It is a software component that stays behind a GUI (screen) Activity It runs inside the

More information

Android Ecosystem and. Revised v4presenter. What s New

Android Ecosystem and. Revised v4presenter. What s New Android Ecosystem and Revised v4presenter What s New Why Mobile? 5B 4B 3B 2B 1B Landlines PCs TVs Bank users Mobiles 225M AOL 180M 135M 90M 45M 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Quarters

More information

Praktikum Entwicklung Mediensysteme. Implementing a User Interface

Praktikum Entwicklung Mediensysteme. Implementing a User Interface Praktikum Entwicklung Mediensysteme Implementing a User Interface Outline Introduction Programmatic vs. XML Layout Common Layout Objects Hooking into a Screen Element Listening for UI Notifications Applying

More information

Praktikum Mobile und Verteilte Systeme. Android-Basics. Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld

Praktikum Mobile und Verteilte Systeme. Android-Basics. Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld Praktikum Mobile und Verteilte Systeme Android-Basics Prof. Dr. Claudia Linnhoff-Popien André Ebert, Sebastian Feld http://www.mobile.ifi.lmu.de SoSe 2018 Programming with Android Today: Android basics

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING 1) What is Android? Important Android Questions It is an open-sourced operating system that is used primarily

More information

CS378 -Mobile Computing. User Interface Basics

CS378 -Mobile Computing. User Interface Basics CS378 -Mobile Computing User Interface Basics User Interface Elements View Control ViewGroup Layout Widget (Compound Control) Many pre built Views Button, CheckBox, RadioButton TextView, EditText, ListView

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Alberto Monge Roffarello Politecnico di Torino, 2017/2018 Some slides and figures are taken from the Mobile Application Development (MAD) course Disclaimer

More information

Android-Basics. Praktikum Mobile und Verteilte Systeme

Android-Basics. Praktikum Mobile und Verteilte Systeme Praktikum Mobile und Verteilte Systeme Android-Basics Prof. Dr. Claudia Linnhoff-Popien André Ebert, Thomy Phan, Robert Müller, Steffen Illium http://www.mobile.ifi.lmu.de WS 2018/19 Programming with Android

More information

Android. Operating System and Architecture. Android. Screens. Main features

Android. Operating System and Architecture. Android. Screens. Main features Android Android Operating System and Architecture Operating System and development system from Google and Open Handset Alliance since 2008 At the lower level is based on the Linux kernel and in a higher

More information

Android. (XKE Mars 2009) Erwan Alliaume.

Android. (XKE Mars 2009) Erwan Alliaume. Android (XKE Mars 2009) Erwan Alliaume ealliaume(*at*)xebia(*dot*)fr http://www.xebia.fr http://blog.xebia.fr History August 2005 Google acquires Android November 2007 Open Handset Alliance announcement

More information

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University User Interface: Layout Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University http://twitter.com/krunapon Agenda User Interface Declaring Layout Common Layouts User Interface

More information

Mobile Programming Lecture 1. Getting Started

Mobile Programming Lecture 1. Getting Started Mobile Programming Lecture 1 Getting Started Today's Agenda About the Android Studio IDE Hello, World! Project Android Project Structure Introduction to Activities, Layouts, and Widgets Editing Files in

More information

Introduction to Android Android Smartphone Programming. Outline University of Freiburg. What is Android? Background University of Freiburg.

Introduction to Android Android Smartphone Programming. Outline University of Freiburg. What is Android? Background University of Freiburg. Introduction to Android Android Smartphone Programming Matthias Keil Institute for Computer Science Faculty of Engineering October 19, 2015 Outline 1 What is Android? 2 3 Applications: A Quick Glimpse

More information

Questions and Answers. Q.1) Which of the following is the most ^aeuroeresource hungry ^aeuroepart of dealing with activities on android?

Questions and Answers. Q.1) Which of the following is the most ^aeuroeresource hungry ^aeuroepart of dealing with activities on android? Q.1) Which of the following is the most ^aeuroeresource hungry ^aeuroepart of dealing with activities on android? A. Closing an app. B. Suspending an app C. Opening a new app D. Restoring the most recent

More information

COSC 3P97 Mobile Computing

COSC 3P97 Mobile Computing COSC 3P97 Mobile Computing Mobile Computing 1.1 COSC 3P97 Prerequisites COSC 2P13, 3P32 Staff instructor: Me! teaching assistant: Steve Tkachuk Lectures (MCD205) Web COSC: http://www.cosc.brocku.ca/ COSC

More information

Mobile Application Development Android

Mobile Application Development Android Mobile Application Development Android Lecture 2 MTAT.03.262 Satish Srirama satish.srirama@ut.ee Android Lecture 1 -recap What is Android How to develop Android applications Run & debug the applications

More information

MARS AREA SCHOOL DISTRICT Curriculum TECHNOLOGY EDUCATION

MARS AREA SCHOOL DISTRICT Curriculum TECHNOLOGY EDUCATION Course Title: Java Technologies Grades: 10-12 Prepared by: Rob Case Course Unit: What is Java? Learn about the history of Java. Learn about compilation & Syntax. Discuss the principles of Java. Discuss

More information

Android Software Development Kit (Part I)

Android Software Development Kit (Part I) Android Software Development Kit (Part I) Gustavo Alberto Rovelo Ruiz October 29th, 2010 Look & Touch Group 2 Presentation index What is Android? Android History Stats Why Andriod? Android Architecture

More information

Android Overview. Most of the material in this section comes from

Android Overview. Most of the material in this section comes from Android Overview Most of the material in this section comes from http://developer.android.com/guide/ Android Overview A software stack for mobile devices Developed and managed by Open Handset Alliance

More information

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41 AndroidHTP_02.fm Page 41 Wednesday, April 30, 2014 3:00 PM 2.3 Creating an App 41 the Welcome app s TextView and the ImageViews accessibility strings, then shows how to test the app on an AVD configured

More information

Android Application Development 101. Jason Chen Google I/O 2008

Android Application Development 101. Jason Chen Google I/O 2008 Android Application Development 101 Jason Chen Google I/O 2008 Goal Get you an idea of how to start developing Android applications Introduce major Android application concepts Provide pointers for where

More information

Android Programming in Bluetooth Cochlea Group

Android Programming in Bluetooth Cochlea Group Android Programming in Bluetooth Cochlea Group Zijian Zhao Abstract: My project is mainly android programming work in the Bluetooth Cochlea Group. In this report I will first introduce the background of

More information

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml Android Application Written in Java (it s possible to write native code) Good

More information

ANDROID SYLLABUS. Advanced Android

ANDROID SYLLABUS. Advanced Android Advanced Android 1) Introduction To Mobile Apps I. Why we Need Mobile Apps II. Different Kinds of Mobile Apps III. Briefly about Android 2) Introduction Android I. History Behind Android Development II.

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie Android Anatomy Android Anatomy 2! Agenda

More information

Lecture 2 Android SDK

Lecture 2 Android SDK Lecture 2 Android SDK This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a

More information

Diploma in Android Programming (DAP)

Diploma in Android Programming (DAP) Diploma in Android Programming (DAP) Duration: 01 Year Total credit: 32 1 st Semester (DAP) Theory Course Course Title (T-L-P) Credit Code CSP-80 Operating Systems T 04 CSP-45 Programing in JAVA T 04 CSP-46

More information

Android Training Overview (For Demo Classes Call Us )

Android Training Overview (For Demo Classes Call Us ) Android Training Overview (For Demo Classes Call Us +91 9990173465) We are an esteemed organization engaged in providing Training Courses for Android. It is a software stack for mobile phones & tablets

More information

EMBEDDED SYSTEMS PROGRAMMING Application Basics

EMBEDDED SYSTEMS PROGRAMMING Application Basics EMBEDDED SYSTEMS PROGRAMMING 2015-16 Application Basics APPLICATIONS Application components (e.g., UI elements) are objects instantiated from the platform s frameworks Applications are event driven ( there

More information

Introduction to Android development

Introduction to Android development Introduction to Android development Manifesto Digital We re an award winning London based digital agency that loves ideas design and technology We aim to make people s lives better, easier, fairer, more

More information

Ahmed Ali Big fan of Android

Ahmed Ali Big fan of Android Ahmed Ali Big fan of Android Mobile Operating Systems What is your Mobile OS? What is your opinion about it? Why you are using it? Do you know any other OSs?? Mobile Operating Systems Click to edit Master

More information

Android Layout Types

Android Layout Types Android Layout Types Android Linear Layout Android LinearLayout is a view group that aligns all children in either vertically or horizontally. android:divider - This is drawable to use as a vertical divider

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie User Interface Design" & Development -

More information

1. What are the key components of Android Architecture? 2. What are the advantages of having an emulator within the Android environment?

1. What are the key components of Android Architecture? 2. What are the advantages of having an emulator within the Android environment? 1. What are the key components of Android Architecture? Android Architecture consists of 4 key components: - Linux Kernel - Libraries - Android Framework - Android Applications 2. What are the advantages

More information

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology Android App Development Mr. Michaud ICE Programs Georgia Institute of Technology Android Operating System Created by Android, Inc. Bought by Google in 2005. First Android Device released in 2008 Based

More information

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH Android Basics - Bhaumik Shukla Android Application Developer @ STEALTH FLASH Introduction to Android Android is a software stack for mobile devices that includes an operating system, middleware and key

More information

ORACLE UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP)

ORACLE UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP) Android Syllabus Pre-requisite: C, C++, Java Programming SQL & PL SQL Chapter 1: Introduction to Android Introduction to android operating system History of android operating system Features of Android

More information

Minds-on: Android. Session 1

Minds-on: Android. Session 1 Minds-on: Android Session 1 Paulo Baltarejo Sousa Instituto Superior de Engenharia do Porto 2016 Outline Mobile devices Android OS Android architecture Android Studio Practice 1 / 33 2 / 33 Mobile devices

More information

Lecture 1 Introduction to Android. App Development for Mobile Devices. App Development for Mobile Devices. Announcement.

Lecture 1 Introduction to Android. App Development for Mobile Devices. App Development for Mobile Devices. Announcement. CSCE 315: Android Lectures (1/2) Dr. Jaerock Kwon App Development for Mobile Devices Jaerock Kwon, Ph.D. Assistant Professor in Computer Engineering App Development for Mobile Devices Jaerock Kwon, Ph.D.

More information

3- Windows Operating System

3- Windows Operating System 3- The most popular desktop Operating System around the world is Microsoft Windows. According to the research published recently, there are about 83 percent of desktop computer users choose Microsoft Windows

More information

Android. Michael Greifeneder. Image source: Android homepage

Android. Michael Greifeneder. Image source: Android homepage Android Michael Greifeneder Image source: Android homepage Inhalt Overwiew Hardware Software Development Demo Tools Basics Debugging/Emulator Location Android And Me Why I like Android Blend of Linux and

More information

GUI Design for Android Applications

GUI Design for Android Applications GUI Design for Android Applications SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November

More information

UI Fragment.

UI Fragment. UI Fragment 1 Contents Fragments Overviews Lifecycle of Fragments Creating Fragments Fragment Manager and Transactions Adding Fragment to Activity Fragment-to-Fragment Communication Fragment SubClasses

More information

The World of Android Development

The World of Android Development The World of Android Development Java Concepts The Big Difference WEB APPS & MOBILE APPS Advantages of Web apps o Universal access Browsers are everywhere Any device on the network can access content PCs,

More information

Lab 1: Getting Started With Android Programming

Lab 1: Getting Started With Android Programming Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Eng. Jehad Aldahdooh Mobile Computing Android Lab Lab 1: Getting Started With Android Programming To create a new Android Project

More information

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

ANDROID APPS DEVELOPMENT FOR MOBILE GAME ANDROID APPS DEVELOPMENT FOR MOBILE GAME Application Components Hold the content of a message (E.g. convey a request for an activity to present an image) Lecture 2: Android Layout and Permission Present

More information

Mobile and Wireless Systems Programming

Mobile and Wireless Systems Programming to Android Android is a software stack for mobile devices that includes : an operating system middleware key applications Open source project based on Linux kernel 2.6 Open Handset Alliance (Google, HTC,

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi View System A system for organizing GUI Screen = tree of views. View = rectangular shape on the screen that knows how to draw itself wrt to the containing

More information

GUJARAT TECHNOLOGICAL UNIVERSITY

GUJARAT TECHNOLOGICAL UNIVERSITY 1. Learning Objectives: To be able to understand the process of developing software for the mobile To be able to create mobile applications on the Android Platform To be able to create mobile applications

More information

Mobile development initiation

Mobile development initiation Mobile development initiation Outline Mobile development: o Why? o How? o New issues Android ios 2 Mobile growth ¼ Internet access Sales of smartphones and tablets increase o + 70% tab Community 3 Why

More information

Android Essentials with Java

Android Essentials with Java Android Essentials with Java Before You Program o Exercise in algorithm generation Getting Started o Using IntelliJ CE Using Variables and Values o Store data in typed variables Static Methods o Write

More information

Activities and Fragments

Activities and Fragments Activities and Fragments 21 November 2017 Lecture 5 21 Nov 2017 SE 435: Development in the Android Environment 1 Topics for Today Activities UI Design and handlers Fragments Source: developer.android.com

More information

Android Programming Lecture 2 9/7/2011

Android Programming Lecture 2 9/7/2011 Android Programming Lecture 2 9/7/2011 Creating a first app 1. Create a new Android project (a collection of source code and resources for the app) from the Eclipse file menu 2. Choose a project name (can

More information

INTRODUCTION TO ANDROID

INTRODUCTION TO ANDROID INTRODUCTION TO ANDROID 1 Niv Voskoboynik Ben-Gurion University Electrical and Computer Engineering Advanced computer lab 2015 2 Contents Introduction Prior learning Download and install Thread Android

More information

ANDROID COURSE BROCHURE

ANDROID COURSE BROCHURE Page 1 1Pointer Technology Chacko Towers,Anna nagar Main Road, Anna Nager(Annai Insititute 2nd Floor) Pondicherry-05 Mobile :+91-9600444787,9487662326 Website : http://www.1pointer.com/ Email : info@1pointer.com/onepointertechnology@gmail.com

More information