Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-BCA-SEM-V-Mobile Application Development-Second Draft

CU-BCA-SEM-V-Mobile Application Development-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-02-26 01:58:23

Description: CU-BCA-SEM-V-Mobile Application Development-Second Draft

Search

Read the Text Version

the UIs. In some cases, these changes could be considered a new screen in which case a user may reasonably expect the back button to return to the previous layout. 9.5 KEYWORDS  Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own they must be hosted by an activity or another fragment.  User interface is the point of human-computer interaction and communication in a device. This can include display screens, keyboards, a mouse, and the appearance of a desktop. It is also the way through which a user interacts with an application or a website.  Dynamic feature modules allow you to separate certain features and resources from the base module of your app. using the Play Core Library, dynamic APKs may be installed on demand after the base APK is installed on the device to provide additional functionality to the user.  Life cycle is a course of events that brings a new product into existence and follows its growth into a mature product and eventual critical mass and decline. The most common steps in the life cycle of a product include product development, market introduction, growth, maturity, and decline/stability.  TabLayout is used to implement horizontal tabs. TabLayout is introduced in design support library to implement tabs. Tabs are created using new Tab method of TabLayout class. The title and icon of Tabs are set through set Text and set Icon methods of TabListener interface respectively. 9.6 LEARNING ACTIVITY 1. Search a Fragment section in your phone. ___________________________________________________________________________ _________________________________________________________________________ 2. Develop a detailed Life cycle ofFragment. ___________________________________________________________________________ __________________________________________________________________________ 9.7 UNIT END QUESTIONS A. Descriptive Questions 201 CU IDOL SELF LEARNING MATERIAL (SLM)

Short Questions 1. Elaborate on the populating dynamic activity layouts with fragments. 2. Write a short note on Fragments. 3. What are android fragment classes? 4. Explain tabbed activity with fragments. 5. What isfragment life cycle? Long Questions 1. Explain fragment. 2. Discuss fragment life cycle. 3. Explain tabbed activity with fragments. 4. Explain model of fragment lifecycle. 5. Explain a. Attaching and Detaching Fragments from the Parent Activity b. Creating and Destroying Fragments c. Creating and Destroying User Interfaces d. Fragment States B. Multiple Choice Questions 1. What is a piece of an activity which enable more modular activity design? a. Fragment b. sub-activity c. Intents d. Filters 2. What is true about Fragments? a. A fragment has its own layout and its own behaviour with its own life cycle callbacks. b. You can add or remove fragments in an activity while the activity is running. c. You can combine multiple fragments in a single activity to build a multi-pane UI. d. All of these 3. Which method is called once the fragment gets visible? 202 a. onStart CU IDOL SELF LEARNING MATERIAL (SLM)

b. onPause c. onResume d. onStop 4. Which method is called Fragment going to be stopped? a. OnDestroyView b. onPause c. onResume d. onStop 5. Which method Fragment becomes active? a. OnPause b. onResume c. onStart d. onCreate Answers 1-a, 2- d, 3-a, 4- d, 5- b 9.8 REFERENCES Reference  James McCaffrey, 2006, NET Test Automation Recipes.  Gary Mak, Josh Long, 2010, Spring Enterprise Recipes.  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011, “Programming Android”, O’Reilly books. Textbooks  J. Burton Browning, Bruce Sutherland, 2020, C++20 Recipes.  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc. 203 CU IDOL SELF LEARNING MATERIAL (SLM)

Websites  https://abhiandroid.com/  https://www.tutorialspoint.com/  https://www.javatpoint.com/  https://www.careerride.com/ 204 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 10: ANDROID MENUS STRUCTURE 10.0 Learning Objectives 10.1 Introduction 10.2 Style and Themes 10.3 Menus 10.3.1 Options 10.3.2 Context 10.3.3 Popup 10.4 Summary 10.5 Keywords 10.6 Learning Activity 10.7 Unit End Questions 10.8 References 10.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Elaborate Style and Themes.  Define the Popup.  Explain the Menus.  LearnOptions & Context. 10.1 INTRODUCTION 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, 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. Although the design and user experience for some menu items have changed, the semantics to define a set of actions and options is still 205 CU IDOL SELF LEARNING MATERIAL (SLM)

based on the Menu APIs. This guide shows how to create the three fundamental types of menus or action presentations on all versions of Android: Options Menu and app bar 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 email,\" and \"Settings.\"See the section about Creating an Options Menu. Context Menu and Contextual Action Mode A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.The contextual action mode displays action items that affect the selected content in a bar at the top of the screenand allows the user to select multiple items.See the section about Creating Contextual Menus. 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. See the section about Creating a Popup Menu. Styles in Android allow you to define the look and feel, for example colours and fonts, of Android components in XML resource files. This way you must set common style attributes only once in one central place. This is typically used for reducing styling duplication in a way highly analogous to CSS in the web development world. By specifying styles in one central file, we can then apply consistent styling across our application's views. In android, Styles and Themes are used to change the look and feel of Views and appearance of application based on our requirements. By using Styles and Themes we can reduce the code duplication and make our app light & responsive. Generally, the style is a combination of multiple attributes such as background colour, font colour, font size, font style, height, width, padding, margin, etc. and it is used to change the look and feel of View or window. In android, the style is defined in a separate XML resource file, and we can use that defined style for the Views in XML that specifies the layout. The Styles in android are like CSS styles in web design. 10.2 STYLE AND THEMES Styles and themes on Android allow you to separate the details of your app design from the UI structure and behaviour, similar to stylesheets in web design. A style is a collection of 206 CU IDOL SELF LEARNING MATERIAL (SLM)

attributes that specify the appearance for a single View. A style can specify attributes such as font colour, font size, background colour, and much more. A theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy not just an individual view. When you apply a theme, every view in the app or activity applies each of the theme's attributes that it supports. Themes can also apply styles to non-view elements, such as the status bar and window background. Styles and themes are declared in a style resource file in res/values/, usually named styles.xml. Figure: 10.1: Themes applied to same activity Themes versus Styles Themes and styles have many similarities, but they are used for different purposes. Themes and styles have the same basic structure a key-value pair which maps attributes to resources. A style specifies attributes for a particular type of view. For example, one style might specify a button's attributes. Every attribute you specify in a style is an attribute you could set in the layout file. By extracting all the attributes to a style, it's easy to use and maintain them across multiple widgets. A theme defines a collection of named resources which can be referenced by styles, layouts, widgets, and so on. Themes assign semantic names, like colour Primary, to Android resources. Styles and themes are meant to work together. For example, you might have a style that specifies that one part of a button should be colour Primary, and another part should be colour Secondary. The actual definitions of those colours are provided in the theme. When the device goes into night mode, your app can switch from its \"light\" theme to its \"dark\" theme, changing the values for all those resource names. You don't need to change the styles, since the styles are using the semantic names and not specific colour definitions. 207 CU IDOL SELF LEARNING MATERIAL (SLM)

Create and Apply a Style To create a new style or theme, open your project's res/values/styles.xml file. For each style you want to create, follow these steps: Add a <style> element with a name that uniquely identifies the style. Add an <item> element for each style attribute you want to define. The name in each item specifies an attribute you would otherwise use as an XML attribute in your layout. The value in the <item> element is the value for that attribute. Extend and Customize a Style When creating your own styles, you should always extend an existing style from the framework or support library so that you maintain compatibility with platform UI styles. To extend a style, specify the style you want to extend with the parent attribute. You can then override the inherited style attributes and add new ones. However, you should always inherit your core app styles from the Android Support Library. The styles in the support library provide compatibility with Android 4.0 and higher by optimizing each style for the UI attributes available in each version. The support library styles often have a name like the style from the platform, but with AppCompact included. To inherit styles from a library or your own project, declare the parent style name without the @android: style/ part shown above. You can also inherit by extending a style's name with a dot notation, instead of using the parent attribute. That is, prefix the name of your style with the name of the style you want to inherit, separated by a period. You should usually do this only when extending your own styles, not styles from other libraries. You can continue inheriting styles like this as many times as you'd like by chain on more names. To find which attributes you can declare with an <item> tag, refer to the \"XML attributes\" table in the various class references. All views support XML attributes from the base View class, and many views add their own special attributes. For example, the TextView XML attributes includes the android: input type attribute that you can apply to a text view that receives input, such as an EditText widget. Apply a Style as a Theme You can create a theme the same way you create styles. The difference is how you apply it: instead of applying a style with the style attribute on a view, you apply a theme with the android:theme attribute on either the <application> tag or an <activity> tag in the AndroidManifest.xml file. 208 CU IDOL SELF LEARNING MATERIAL (SLM)

Now every view in the app or activity applies the styles defined in the given theme. If a view supports only some of the attributes declared in the style, then it applies only those attributes and ignores the ones it does not support. Beginning with Android 5.0 and Android Support Library v22.1, you can also specify the android:theme attribute to a view in your layout file. This modifies the theme for that view and any child views, which is useful for altering theme colour palettes in a specific portion of your interface. The previous examples show how to apply a theme such as Theme.App Compact that’s supplied by the Android Support Library. But you'll usually want to customize the theme to fit your app's brand. The best way to do so is to extend these styles from the support library and override some of the attributes, as described in the next section. Style Hierarchy Android provides a variety of ways to set attributes throughout your Android app. For example, you can set attributes directly in a layout, you can apply a style to a view, you can apply a theme to a layout, and you can even set attributes programmatically. When choosing how to style your app, be mindful of Android's style hierarchy. In general, you should use themes and styles as much as possible for consistency. If you've specified the same attributes in multiple places, the list below determines which attributes are ultimately applied. The list is ordered from highest precedence to lowest: 1. Applying character- or paragraph-level styling via text spans to Text View derived classes 2. Applying attributes programmatically 3. Applying individual attributes directly to a View 4. Applying a style to a View 5. Default styling 6. Applying a theme to a collection of Views, an activity, or your entire app 7. Applying certain View-specific styling, such as setting a TextAppearance on a TextView 209 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure: 10.2. Styling from a span overrides styling from a textAppearance. TextAppearance One limitation with styles is that you can apply only one style to a View. In a TextView, however, you can also specify a TextAppearance attribute which functions similarly to a style, as shown in the following example: <TextView ... android:textAppearance=\"@android:style/TextAppearance.Material.Headline\" android: text=\"This text is styled via textAppearance!\" /> TextAppearance allows you to define text-specific styling while leaving a View’s style available for other uses. Note, however, that if you define any text attributes directly on the View or in a style, those values will override the TextAppearance values. TextAppearance supports a subset of styling attributes that TextView offers. For the full attribute list, see TextAppearance. Some common TextView attributes not included are lineHeightlines, breakStrategy, and hyphenationFrequency. TextAppearance works at the character level and not the paragraph level, so attributes that affect the entire layout are not supported. Customize the Default Theme When you create a project with Android Studio, it applies a material design theme to your app by default, as defined in your project's styles.xml file. This AppTheme style extends a theme from the support library and includes overrides for colour attributes that are used by key UI elements, such as the app bar and the floating action button (if used). So, you can quickly customize your app's colour design by updating the provided colours. For example, your styles.xml file should look like this: <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <!-- Customize your theme here. --> 210 CU IDOL SELF LEARNING MATERIAL (SLM)

<item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> Notice that the style values are actually references to other colour resources, defined in the project's res/values/colors.xml file. So that's the file you should edit to change the colours. But before you start changing these colours, preview your colours with the Material Colour Tool. This tool helps you pick colours from the material palette and preview how they'll look in an app. Once you know your colours, update the values in res/values/colors.xml: <?xml version=\"1.0\" encoding=\"utf-8\"?> <resources> <!--colour for the app bar and other primary UI elements --> <colour name=\"colorPrimary\">#3F51B5</colour> <!-- a darker variant of the primary color, used for the status bar (on Android 5.0+) and contextual app bars --> <color name=\"colorPrimaryDark\">#303F9F</color> <!-- a secondary color for controls like checkboxes and text fields --> <color name=\"colorAccent\">#FF4081</color> </resources> And then you can override whatever other styles you want. For example, you can change the activity background color as follows: <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> ... <item name=\"android:windowBackground\">@color/activityBackground</item> </style> For a list of attributes, you can use in your theme, see the table of attributes at R.styleable.Theme. And when adding styles for the views in your layout, you can also find attributes by looking at the \"XML attributes\" table in the view class references. For example, all views support XML attributes from the base View class. Most attributes are applied to specific types of views, and some apply to all views. However, some theme attributes listed at R.styleable.Theme apply to the activity window, not the views 211 CU IDOL SELF LEARNING MATERIAL (SLM)

in the layout. For example, windowBackground changes the window background and windowEnterTransition defines a transition animation to use when the activity starts (for details, see Start an Activity with an Animation). The Android Support Library also provides other attributes you can use to customize your theme extended from Theme.AppCompat (such as the colorPrimary attribute shown above). These are best viewed in the library's attrs.xml file Note: Attribute names from the support library do not use the android: prefix. That's used only for attributes from the Android framework. There are also different themes available from the support library that you might want to extend instead of the ones shown above. The best place to see the available themes is the library's themes.xml file. Add version-specific styles If a new version of Android ads theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example: res/values/styles.xml # themes for all versions res/values-v21/styles.xml # themes for API level 21+ only Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a \"base\" theme and then extending it in your version-specific styles. For example, to declare window transitions for Android 5.0 (API level 21) and higher, you need to use some new attributes. So, your base theme in res/values/styles.xml could look like this: <resources> <!-- base set of styles that apply to all versions --> <style name=\"BaseAppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <item name=\"colorPrimary\">@color/primaryColor</item> <item name=\"colorPrimaryDark\">@color/primaryTextColor</item> <item name=\"colorAccent\">@color/secondaryColor</item> </style> <!-- declare the theme name that's actually applied in the manifest file --> <style name=\"AppTheme\" parent=\"BaseAppTheme\" /> </resources> 212 CU IDOL SELF LEARNING MATERIAL (SLM)

Then add the version-specific styles in res/values-v21/styles.xml as follows: <resources> <!-- extend the base theme to add styles available only with API level 21+ --> <style name=\"AppTheme\" parent=\"BaseAppTheme\"> <item name=\"android:windowActivityTransitions\">true</item> <item name=\"android:windowEnterTransition\">@android:transition/slide_right</item> <item name=\"android:windowExitTransition\">@android:transition/slide_left</item> </style> </resources> Now you can apply AppTheme in your manifest file and the system selects the styles available for each system version. For more information about using alternative resources for different devices, read Providing Resources. Customize Widget Styles Every widget in the framework and support library has a default style. For example, when you style your app using a theme from the support library, an instance of Button is styled using the Widget.AppCompat.Button style. If you'd like to apply a different widget style to a button, then you can do so with the style attribute in your layout file. For example, the following applies the library's borderless button style: <Button style=\"@style/Widget.AppCompat.Button.Borderless\" ... /> And if you want to apply this style to all buttons, you can declare it in your theme's buttonStyle as follows: <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <item name=\"buttonStyle\">@style/Widget.AppCompat.Button.Borderless</item> ... </style> You can also extend widget styles, just like extending any other style, and then apply your custom widget style in your layout or in your theme. 213 CU IDOL SELF LEARNING MATERIAL (SLM)

10.3 MENUS Create menu resources to design your menu layouts in XML, rather than constructing them in code. You can use menu resources to define both Activity and context menus within your applications, and provide the same options you would have when constructing your menus in code. When defined in XML, a menu is inflated within your application via the inflate method of the MenuInflator Service, usually within the onCreateOptionsMenu method. Each menu definition is stored in a separate file, each containing a single menu, in the res/menu folder the filename then becomes the resource identifier. Using XML to define your menus is bestpractice design in Android. Listing 3-3 shows a simple example. LISTING 3-3: Simple menu layout resource <?xml version=”1.0” encoding=”utf-8”?> <menu xmlns:android=”http://schemas.android.com/apk/res/android”> <item android:id=”@+id/menu_refresh” android:title=”@string/refresh_mi” /> <item android:id=”@+id/menu_settings” android:title=”@string/settings_mi” /> </menu> In android, Menu is an important part of UI component which is used to provide some common functionality around the application. With the help of menu user can experience smooth and consistent experience throughout the application. In order to use menu, we should define it in separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities. 10.3.1 Options Menu In Android apps, you can make use of three standard menus supported within the platform: the context menu, the options menu, and submenus. The options menu appears when the user presses the menu button on their Android device. This is a common feature in almost all apps, so your users will be used to the menu appearing in this way. The options menu is typically used for providing additional info about an app, as well as linking to a help and settings sections. To implement an options menu for an Activity in an Android app, a few straightforward steps are required. Implement an Options Menu Step 1: Open an Activity Class 214 CU IDOL SELF LEARNING MATERIAL (SLM)

The options menu you create will work with one or more Activity classes, so choose an Activity and open it in Eclipse. If your app only has one Activity class as its main screen, you can use it. If you want to create a new Activity for the purposes of this tutorial, feel free to do so. Select your application package and choose \"File\", \"New\", and then \"Class\" and enter a name of your choice. Remember to make your class extend the Activity class and add it to the application Manifest. Step 2: Create a Resources Folder If you look at your application project in the Eclipse Package Explorer, you will see the various files and directories within it. The \"res\" folder holds all of your application resources. To create a menu, you need a menu folder, so create one inside the \"res\" folder by selecting it and choosing \"File\", \"New\", then \"Folder\" and entering \"menu\" as the name. Figure: 10.3: Creating new folder Your new folder will appear within the \"res\" directory: 215 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure: 10.4: Res Directory 2. Million+ WordPress Themes & PlugINS Web & Email Templates UI Kits and More Download thousands of WordPress themes and plugging, web templates, UI elements, and much more with an Envato Elements membership. Get unlimited access to a growing library to millions of creative and code assets. Figure: 10.5: Thumbs of php PHP Scripts Figure 10.6: PHP Scripts 216 CU IDOL SELF LEARNING MATERIAL (SLM)

IOS App Templates 2,500+ stunning IOS app templates for your next project, Figure: 10.7: Development of app templates UX & UI Kits Easily customizable UX and UI kits to inspire your next project Step 3: Create a Menu XML File Your options menu will be defined as an XML file inside the new menu folder you created. Choose the folder and create a new file by selecting \"File\", \"New\", then \"File\" and entering a name. You can choose any filename you like, for example \"my_options_menu.xml\". Eclipse will display error messages when you first create the menu file, but don't worry, these will disappear as you build it. Open your new XML file and enter the following outline: 1. <menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> 2. </menu> Between these opening and closing tags, you will place XML markup for each item in your options menu. Step 4: Add Items to Your Menu You can add one or more items to your options menu depending on the needs of your own project. Add an item for each menu option using the following syntax: 1 <item android:id=\"@+id/about\" 2 android:title=\"About\" /> 217 CU IDOL SELF LEARNING MATERIAL (SLM)

3 <item android:id=\"@+id/help\" 4 android:title=\"Help\" /> This defines two menu items, one for an \"About\" section and one for \"Help\" information. Each menu has an ID attribute and a title. The ID attribute allows your application code to refer to the item and the title defines the text users will see when the menu appears. Step 5: Create Icons for Your Menu Items You do not need to create icons for your options menu items, but you can do so if you wish. Use a graphic design or image editing program of your choice to create your icons as PNG files and place them in your application draw able folders. By default, Eclipse creates three draw able folders, for low, medium, and high-resolution user devices. You can copy image files into these folders by browsing to your workspace, then locating your Android project directory and finding the \"res/draw able\" folders from there. The official Android guidelines recommend a maximum of 72px squared for high resolution, 48px for medium and 36px for low. Once you have your icons in their folders, you can alter your menu item XML to include them as follows: 1 <item android:id=\"@+id/about\" 2 android:icon=\"@drawable/about\" 3 android:title=\"About\" /> 4 <item android:id=\"@+id/help\" 5 android:icon=\"@drawable/help\" 6 android:title=\"Help\" /> Each draw able reference uses the filename minus its extension. Step 6: Inflate Your Menu Resource To instruct Android to use your options menu, open the Activity class you want it to appear with. Add the following method to your Java code, inside the class declaration and after the \"onCreate\" method: 1. public boolean onCreateOptionsMenu(Menu menu) 2. MenuInflater inflater = getMenuInflater(); 3. inflater.inflate(R.menu.my_options_menu, menu); 4. return true; 218 CU IDOL SELF LEARNING MATERIAL (SLM)

Alter the \"my_options_menu\" section if you saved your menu XML file with a different name. Figure 10.8: GreatAndroid App Step 7: Detect User Interaction To respond to user interaction with your menu, you first need to detect it within your Activity class. Add the following method outline after the \"onCreateOptionsMenu\" method: 1. public boolean onOptionsItemSelected(MenuItem item) 2. //respond to menu item selection Inside this method, which returns a Boolean value, you can add code to respond to each item. The system will automatically call the \"onOptionsItemSelected\" method when the user chooses any of the options menu items. Step 8: Respond to Menu Item Selection Before your code can respond appropriately to user interaction with the menu, you need to work out which item was selected. Add a switch statement to your method using the following sample syntax: 01 switch (item.getItemId()) { 02 case R.id.about: 03 startActivity(new Intent(this, About.class)); 04 return true; 219 CU IDOL SELF LEARNING MATERIAL (SLM)

05 case R.id.help: 06 startActivity(new Intent(this, Help.class)); 07 return true; 08 default: 09 return super.onOptionsItemSelected(item); Add a case statement for each item in your menu. This sample code starts new Activity screens for each item chosen. If you opt to do this, you will need to add an Activity class for each option in your application Java code as well as in the Manifest file. 10.3.2 Context Menu The previous section showed how the options menu is displayed when the user presses the MENU button. Besides the options menu, you can also display a context menu. A context menu is usually associated with a view on an activity, and it is displayed when the user taps and holds an item. For example, if the user taps on a Button view and holds it for a few seconds, a context menu can be displayed. If you want to associate a context menu with a view on an activity, you need to call the setOnCreateContextMenu Listener method of that particular view. The following Try It Out shows how you can associate a context menu with a Button view Creating Contextual Menus Figure10.9: Screenshots of a floating context menu and the contextual action bar 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 List 220 CU IDOL SELF LEARNING MATERIAL (SLM)

View, Grid View, 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 when the user performs a long-click view that declares support for a context menu. Users can perform a contextual action on one item at a time. In the contextual action mode, this mode is a system implementation of ActionMode that displays a contextual action bar at the top of the screen with action items that affect the selected item. When this mode is active, users can perform an action on multiple items at once. Note: The contextual action mode is available on Android 3 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. 10.3.3 Popup Menu Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content. In android, Popup Menu displays a list of items in a modal popup window that is anchored to the view. The popup menu will appear below the view if there is a room or above the view in case if there is no space and it will be closed automatically when we touch outside of the popup. The android Popup Menu provides an overflow style menu for actions that are related to specific content. In android, the Popup Menu provides an overflow of actions that are related to specific content and the actions in the popup menu won’t affect the corresponding content. The popup menu won’t support any item shortcuts and item icons. In android, the Popup menu is available with API level 11 and higher versions. If you are using Android 3.0 +, the Popup Menu won’t support any item shortcuts and item icons in the menu. 10.4 SUMMARY  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 Android-powered devices are no longer required to provide a dedicated Menu button.  A context menu is a floating menu that appears when the user performs a long-click on an element. 221 CU IDOL SELF LEARNING MATERIAL (SLM)

 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.  In Android apps, you can make use of three standard menus supported within the platform: the context menu, the options menu, and submenus. The options menu appears when the user presses the menu button on their Android device. This is a common feature in almost all apps, so your users will be used to the menu appearing in this way. The options menu is typically used for providing additional info about an app, as well as linking to a help and settings sections. To implement an options menu for an Activity in an Android app, a few fairly straightforward steps are required.  Styles and themes on Android allow you to separate the details of your app design from the UI structure and behaviour, similar to styles sheets in web design. A style is a collection of attributes that specify the appearance for a single View.  Themes and styles have many similarities, but they are used for different purposes. Themes and styles have the same basic structure a key-value pair which maps attributes to resources.  Create menu resources to design your menu layouts in XML, rather than constructing them in code. You can use menu resources to define both Activity and context menus within your applications, and provide the same options you would have when constructing your menus in code.  In Android apps, you can make use of three standard menus supported within the platform: the context menu, the options menu, and submenus. The options menu appears when the user presses the menu button on their Android device.  Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content. In android, Popup Menu displays a list of items in a modal popup window that is anchored to the view. The popup menu will appear below the view if there is a room or above the view in case if there is no space and it will be closed automatically when we touch outside of the popup. 10.5 KEYWORDS  Style is a collection of attributes that specify the appearance for a single View. A style can specify attributes such as font colour, font size, background colour, and much more.  Theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy not just an individual view. 222 CU IDOL SELF LEARNING MATERIAL (SLM)

 Option Menus are the primary menus of android. They can be used for settings, search, delete item etc. When and how this item should appear as an action item in the app bar is decided by the Show Action attribute.  Context menu is like a floating menu and arises when the user has long pressed or clicks on an item and is beneficial for implementing functions that define the specific content or reference frame effect. The Android context menu is alike to the right-click menu in Windows or Linux.  Popup Menu displays a list of items in a modal popup window that is anchored to the view. The popup menu will appear below the view if there is a room or above the view in case if there is no space and it will be closed automatically when we touch outside of the popup. 10.6 LEARNING ACTIVITY 1. Find Style and Theme in your android phone. ___________________________________________________________________________ __________________________________________________________________________ 2. Find Context menu, Popup menu & Option menu in your android phone ___________________________________________________________________________ __________________________________________________________________________ 10.7 UNIT END QUESTIONS A. Descriptive Questions 223 Short Questions 1. Describe about the term Menus? 2. Write a short note on Style? 3. What is meant byOption menu? 4. What isContextmenu? 5. Define Themes? Long Questions 1. Explain the Style and Themes. 2. Discuss in brief about the Menus. 3. Explain Option menu. 4. Describe the Context menu. CU IDOL SELF LEARNING MATERIAL (SLM)

5. Explain Popup menu. 224 B. Multiple Choice Questions 1. How many sizes are supported by Android? a. Android supported all sizes b. Android does not support all sizes c. Android supports small, normal, large and extra-large sizes d. Size is undefined in android 2. Which are android provides a few standard themes, listed in? a. Rstyle b. X style c. menifeest.XML d. Application 3. What are the types of menus is/are supported by Android? a. Option menu and Context menu b. Only Option menu c. Only Context menu d. None of these. 4. What method you should override to use Android menusystem? a. OnCreateOptions Menu b. OnCreate Menu c. On Menu Created d. On Create Context Menu 5. Which configuration file holds the permission to use theinternet? a. Layout file b. Property file c. Java source file d. Manifest file Answers 1-c, 2- a, 3-a, 4- a, 5- d CU IDOL SELF LEARNING MATERIAL (SLM)

10.8 REFERENCES Reference  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011, “Programming Android”, O’Reilly books.  Mike Driscoll, 2017, wxPython Recipes.  John Ciliberti, 2017, ASP.NET Core Recipes. Textbooks  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc.  Wlodzimierz Gajda, 2014, Git Recipes Websites  https://medium.com  https://www.tutorialspoint.com/  https://www.javatpoint.com/  https://www.careerride.com/ 225 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 11: DATABASE CONNECTIVITY STRUCTURE 11.0 Learning Objectives 11.1 Introduction 11.2 SQLITE Database with CRUD Operations 11.2.1 Working with SQ LITE Databases 11.2.2 Introducing the SQLITE Open Helper 11.2.3 Creating and using SQLITE Database 11.3 Summary 11.4 Keywords 11.5 Learning Activity 11.6 Unit End Questions 11.7 References 11.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Define an SQLite Database.  Explain the Working with SQLite Databases.  Outline the SQLite Open Helper.  Explain how to create and using SQLite Database. 11.1 INTRODUCTION Android provides structured data persistence through a combination of SQLite databases and Content Providers. SQLite databases can be used to store application data using a managed, structured approach. Android offers a full SQLite relational database library. Every application can create its own databases over which it has complete control. Having created your underlying data store, Content Providers offer a generic, well-defined interface for using and sharing data that provides a consistent abstraction from the underlying data source. SQLite is an open-source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. To access this database, you don't need to establish any kind of 226 CU IDOL SELF LEARNING MATERIAL (SLM)

connections for it like JDBC, ODBC etc.SQLite is an open-source relational database i.e., used to perform database operations on android devices such as storing, manipulating, or retrieving persistent data from the database. It is embedded in android by default. So, there is no need to perform any database setup or administration task. Here, we are going to see the example of SQLite to store and fetch the data. Data is displayed in the log cat, for displaying data on the spinner or list view, move to the next page. he first step in learning how to connect an Android app to a MySQL database is configuring the backend. We will need a MySQL server of course, but we will also need a simple API. Our app won’t connect directly to the database; instead, it will need to send requests to an API that we will write. This simple script will take the request, process it, and respond to the app. For this tutorial, we will be using a PHP script for our API. Since we will be using both MySQL and PHP, the LAMP stack template offered by SkySilk is perfect. SQLite is a relational database management system. If most RDBMSs such as MySQL, Oracle, etc. are standalone server processes, then SQLite is embedded because it is provided in the form of a library that is linked in applications. Like other RDBMSs, data is accessed in a SQLite database by using Structured Query Language. The first step in learning how to connect an Android app to a MySQL database is configuring the backend. We will need a MySQL server of course, but we will also need a simple API. Our app won't connect directly to the database; instead, it will need to send requests to an API that we will write. Saving data to a database is ideal for repeating or structured data, such as contact information. This page assumes that you are familiar with SQL databases in general and helps you get started with SQLite databases on Android. The APIs you'll need to use a database on Android are available in the android database sqlite package of the main principles of SQL databases is the schema: a formal declaration of how the database is organized. The schema is reflected in the SQL statements that you use to create your database. You may find it helpful to create a companion class, known as a contract class, which explicitly specifies the layout of your schema in a systematic and self- documenting way. A contract class is a container for constants that define names for URIs, tables, and columns. The contract class allows you to use the same constants across all the other classes in the same package. This lets you change a column name in one place and have it propagated throughout your code. A good way to organize a contract class is to put definitions that are global to your whole database in the root level of the class. Then create an inner class for each table. Each inner class enumerates the corresponding table's columns. Databases store information and its contents can be everything from product cat logs to repositories of customer information. For information to be easy to access, use and understand, database management systems are required. Database management systems can help sort information as well as link databases to each other and provide reports about changes and trends in the information in databases. Although database management systems all perform the same basic task, which is to enable users to create, edit and access information 227 CU IDOL SELF LEARNING MATERIAL (SLM)

in databases, how they accomplish this can vary. Additionally, the features, functionality, and support associated with each management system can differ significantly. 11.2 SQLITE DATABASE WITH CRUD OPERATIONS Using SQLite, you can create fully encapsulated relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the /data/data//databases folder on your device (or emulator). All databases are private, accessible only by the application that created them. Database design is a big topic that deserves more thorough coverage than is possible within this book. It is worth highlighting that standard database best practices still apply in Android. When you’re creating databases for resource-constrained devices, it’s important to normalize your data to minimize redundancy SQLite is a well-regarded relational database management system. It is:  Open-source  Standards-compliant  Lightweight  Single-tier It has been implemented as a compact C library that’s included as part of the Android software stack. By being implemented as a library, rather than running as a separate ongoing process, each SQLite database is an integrated part of the application that created it. This reduces external dependencies, minimizes latency, and simplifies transaction locking and synchronization. SQLite has a reputation for being extremely reliable and is the database system of choice for many consumer electronic devices, including many MP3 players and smartphones. Lightweight and powerful, SQLite differs from many conventional database engines by loosely typing each column, meaning that column values are not required to conform to a single type; instead, each value is typed individually in each row. As a result, type checking isn’t necessary when assigning or extracting values from each column within a row. The purpose of writing this is for beginners who are curious about backend development or front-end developers who want to learn database technology with server-side programminglanguage. As we know that server-side language like python, java, and many others are not sufficient for backed developers and even a backend developer needs to be more knowledgeable in database technologies.So, let’s start with the basics of SQLite Database with python. I chose the SQLite database is just an option; one can apply the same knowledge with any other database also like Mysql and Oracle or any other.The best part of 228 CU IDOL SELF LEARNING MATERIAL (SLM)

database technology is all the databases are very similar for SQL concepts accept few new Databases. We are not using any python package to make our job easy for learning these four basic operations. CRUD C: Create R: Read U: Update D: Delete CREATE: Inserting or creating a new record within the table. So let’s create an example table within Sqlite Database. # creating table into database!!! Import sqlite3 # Connect to sqlite database conn = sqlite3.connect # Cursor object Cursor = conn.cursor() # drop query cursor.execute(\"DROP TABLE IF EXISTS STUDENT\") # create query Query = \"\"\"CREATE TABLE STUDENT ID INT PRIMARY KEY NOT NULL, NAME CHAR (20) NOT NULL, ROLL CHAR (20), ADDRESS CHAR (50), CLASS CHAR (20) cursor.execute(query) # Commit and close conn.commit 229 CU IDOL SELF LEARNING MATERIAL (SLM)

conn.close The conn = sqlite3.connectis the connection method and it is simple with SQLite DB, but it will differ with different databases. The cursor executemethod execute sqlite queries. CREATE TABLE table_name ( Column name datatype properity, The above syntax can be mapped with the query, there are three main attributes of a create query “column name datatype property”. After every database operation, we should add a commit and close DB operation. INSERT: Import sqlite3 conn = sqlite3.connect('students.db') conn.execute(\"INSERT INTO STUDENT (ID,NAME,ROLL,ADDRESS,CLASS) \" \"VALUES (1, 'John', '001', 'Bangalore', '10th')\") conn.execute(\"INSERT INTO STUDENT (ID,NAME,ROLL,ADDRESS,CLASS) \" \"VALUES (2, 'Naren', '002', 'Hyd', '12th')\") conn.commit() conn.close() The above query syntax is hardcoded data insertion but when we have data from an external input then we can modify the syntax this way. Query = ('INSERT INTO STUDENT (ID, NAME,ROLL,ADDRESS,CLASS) ' 'VALUES (:ID, :NAME, :ROLL, :ADDRESS, :CLASS);') params = { 'ID': 3, 'NAME': 'Jax', 'ROLL': '003', 'ADDRESS': 'Delhi', 'CLASS': '9th' conn.execute(query, params) 230 CU IDOL SELF LEARNING MATERIAL (SLM)

READ: This is an important operation because this belongs to select query and has a lot more verity in fetching the records from the database. Sometimes this operation will be very tricky with multiple table databases, Here are a few examples of select operations. Import sqlite3 conn = sqlite3.connect('students.db') Cursor = conn.execute(\"SELECT * from STUDENT\") print (cursor.fetchall()) conn.close() The simplest way fetching all the data “SELECT * from TABLENAME” SELECT column1, column2, columnN FROM table name; We can mention only those column names are required; It is always good practice to mention names of the column if all the data is not required to fetch. SELECT column1, column2, column FROM table name WHERE column name = value; Where clause returns specific rows which record will match with the value. UPDATE: The update is changing the existing record, the simple rule of the update is to use the best approach to reach the record and change it. Import sqlite3 conn = sqlite3.connect('students.db') conn.execute(\"UPDATE STUDENT set ROLL = 005 where ID = 1\") conn.commit() Cursor = conn.execute(\"SELECT * from STUDENT\") print(cursor.fetchall()) conn.close() Note: Why I say about use the best approaches because with not only in cases of update whereas in all the database operation we should avoided reading or fetching unnecessary record it will save the query time and will increase whole system performance of any application. DELETE: Removing any records from the table is a DELETE operation and the code below shows the delete query example. 231 CU IDOL SELF LEARNING MATERIAL (SLM)

Import sqlite3 conn = sqlite3.connect('students.db') conn.execute(\"DELETE from STUDENT where ID = 2;\") conn.commit() cursor = conn.execute(\"SELECT from STUDENT\") print(cursor.fetchall()) conn.close() These are the basic CRUD operations on the SQLite database using python. The source code is available on this GitHub click here. It is always good to directly jump into developing an application we should learn the basic of backbone technologies required for those applications. If one is clear with basic knowledge of database operation with CRUD operation, then it is ok to use any of the python SQL libraries for easy implementation. 11.2.1 Working with SQLite Databases This section shows you how to create and interact with SQLite databases within your applications. When working with databases, its good form to encapsulate the underlying database and expose only the public methods and constants required to interact with that database, generally using what’s often referred to as a contract or helper class. This class should expose database constants, particularly column names, which will be required for populating and querying the database. Later in this chapter you’ll be introduced to Content Providers, which can also be used to expose these interaction constants. Listing 8-1 shows a sample of the type of database constants that should be made public within a helper class LISTING 8-1: Skeleton code for contract class constants // the index (key) column name for use in where clauses. Public static final String KEY_ID = “_id”; // the name and column index of each column in your database. // these should be descriptive. Public static final String KEY_GOLD_HOARD_NAME_COLUMN = “GOLD_HOARD_NAME_COLUMN”; Public static final String KEY_GOLD_HOARD_ACCESSIBLE_COLUMN = “OLD_HOARD_ACCESSIBLE_COLUMN”; 232 CU IDOL SELF LEARNING MATERIAL (SLM)

Public static final String KEY_GOLD_HOARDED_COLUMN = “GOLD_HOARDED_COLUMN”; // TODO: Create public field for each column in your table. Creating the Data Model Once completed, the application will consist of an activity and a database handler class. The database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer between the underlying SQLite database and the activity class, with the activity calling on the database handler to interact with the database (adding, removing and querying database entries). In order to implement this interaction in a structured way, a third class will need to be implemented to hold the database entry data as it is passed between the activity and the handler. This is actually a very simple class capable of holding product ID, product name and product quantity values, together with getter and setter methods for accessing these values. Instances of this class can then be created within the activity and database handler and passed back and forth as needed. Essentially, this class can be thought of as representing the database model Within the Eclipse environment, right-click on the Database project name in the Package Explorer panel and select the New -> Class menu option. Use the Browse button to the right of the Package field to locate and select the package name you chose when creating the project in the preceding chapter. Name the new class Product and make sure that java lang.Object is selected as the superclass before clicking on Finish to create the class. Having created the class, locate the Product.java source file in the Package Explorer panel and double click on it to load it into an editing panel. Once loaded, modify the code to add the appropriate data members and methods: Package com.example.database; Public class Product { Private int _id; Private String _productname; Private int _quantity; Public Product PublicProduct (int id, String productname, int quantity this._id = id; this._productname = productname; this._quantity = quantity; PublicProduct (String productname, int quantity 233 CU IDOL SELF LEARNING MATERIAL (SLM)

this._productname = productname; this._quantity = quantity; Public void setID(int id) this._id = id; Public int getID Return this._id; Public void setProductName(String productname This /product name = productname; Public String getProductName Return this._productname; Publicvoid set Quantity (int quantity This. Quantity = quantity; Public int get Quantity Return this._quantity; The completed class contains private data members for the internal storage of data columns from database entries and a set of methods to get and set those values. Once the changes have been made, save the file. Implementing the Data Handler The data handler will be implemented by subclassing from the Android SQLiteOpenHelper class and, as outlined in An Overview of Android SQLite Databases, adding the constructor, on Create and on Upgrade methods. Since the handler will be required to add, query, and delete data on behalf of the activity component, corresponding methods will also need to be added to the class. Begin by adding a second new class to the project. This time the class will be named MyDBHandler and sub classed from android database sqlite.SQ Lite Open Helper. Once the new class has been created, load it into an editing panel where it will read as follows: Packagecom.example.database; Import android.database.sqlite.SQLiteDatabase; Import android.database.sqlite.SQLiteOpenHelper; 234 CU IDOL SELF LEARNING MATERIAL (SLM)

Public class MyDBHandler extends SQLiteOpenHelper @Override Public voidonCreate(SQLiteDatabase arg0) // TODO Auto-generated method stub @Override Public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) // TODO Auto-generated method stub Eclipse has anticipated some of our requirements and has pre-populated the source file with template on Create and on Upgrade methods. It has not, however, added a constructor method (a closer inspection of the editing panel will reveal that Eclipse has already flagged this oversight with a warning icon in the left hand edge of the panel). In the first instance, modify the code to declare constants for the database name, table name, table columns and database version, and to add a constructor method: Package com.example.database; Import android.content.ContentValues; Import android.content.Context; Import android.database.Cursor; Import android.database.sqlite.SQLiteDatabase; Import android.database.sqlite.SQLiteDatabase.CursorFactory; Import android.database.sqlite.SQLiteOpenHelper; Public class MyDBHandler extends SQLiteOpenHelper { Private static final int DATABASE_VERSION = 1; Private static final String DATABASE_NAME = \"productDB.db\"; Public static final String TABLE_PRODUCTS = \"products\"; Public static final String COLUMN_ID = \"_id\"; Public static final String COLUMN_PRODUCTNAME = \"productname\"; Public static final String COLUMN_QUANTITY = \"quantity\"; PublicMyDBHandler(Context context, String name, CursorFactory factory, int version) { 235 CU IDOL SELF LEARNING MATERIAL (SLM)

Super (context, DATABASE_NAME, factory, DATABASE_VERSION); @Override Public voidonCreate(SQLiteDatabase arg // TODO Auto-generated method stub @Override Public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) // TODO Auto-generated method stub Next, the on Create method needs to be implemented so that the products table is created when the database is first created. This involves constructing a SQL CREATE statement containing instructions to create a new table with the appropriate columns and then passing that through to the exec SQL method of the SQLiteDatabase object passed as an argument to on Create: @Override Public void onCreate(SQLiteDatabase db) { String CREATE_PRODUCTS_TABLE = \"CREATE TABLE” + TABLE_PRODUCTS + \"(\" + COLUMN_ID + “INTEGER PRIMARY KEY,\" + COLUMN_PRODUCTNAME + “TEXT,\" + COLUMN_QUANTITY + “INTEGER\" + \")\"; db.execSQL(CREATE_PRODUCTS_TABLE); The on Upgrade method is called when the handler is invoked with a greater database version number from the one previously used. The exact steps to be performed in this instance will be application specific, so for the purposes of this example we will simply remove the old database and create a new one: @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_PRODUCTS); onCreate(db); 236 CU IDOL SELF LEARNING MATERIAL (SLM)

All that now remains to be implemented in the handler class are the methods to add, query and remove database table entries. The Add Handler Method The method to insert database records will be named add Product and will take as an argument an instance of our Product data model class. A ContentValues object will be created in the body of the method and primed with key-value pairs for the data columns extracted from the Product object. Next, a reference to the database will be obtained via a call to get Writable Database followed by a call to the insert method of the returned database object. Finally, once the insertion has been performed, the database needs to be closed: Public void add Product (Product product) ContentValues values = new ContentValues(); values.put(COLUMN_PRODUCTNAME, product.getProductName()); values.put(COLUMN_QUANTITY, product.getQuantity()); SQLiteDatabase db = this.getWritableDatabase(); db.insert(TABLE_PRODUCTS, null, values); db.close(); The Query Handler Method The method to query the database will be named find Product and will take as an argument a String object containing the name of the product to be located. Using this string, a SQL SELECT statement will be constructed to find all matching records in the table. For the purposes of this example, only the first match will then be returned, contained within a new instance of our Product data model class: Public Product findsProduct (String product name) String query = \"Select * FROM \" + TABLE_PRODUCTS + \" WHERE \" + COLUMN_PRODUCTNAME + \" = \\\"\" + productname + \"\\\"\"; SQLiteDatabase db = this.getWritableDatabase(); Cursor = db.rawQuery(query, null) Product = new Product(); if (cursor.moveToFirst()) { cursor.moveToFirst(); product.setID(Integer.parseInt(cursor.getString(0))); 237 CU IDOL SELF LEARNING MATERIAL (SLM)

product.setProductName(cursor.getString(1)); product.setQuantity(Integer.parseInt(cursor.getString(2))); cursor.close(); } else { Product = null; } db.close(); return product; The Delete Handler Method The deletion method will be named delete Product and will accept as an argument the entry to be deleted in the form of a Product object. The method will use a SQL SELECT statement to search for the entry based on the product name and, if located, delete it from the table. The success or otherwise of the deletion will be reflected in a Boolean return value: Public boolean deleteProduct(String productname) { boolean result = false; String query = \"Select * FROM \" + TABLE_PRODUCTS + \" WHERE \" + COLUMN_PRODUCTNAME + \" = \\\"\" + productname + \"\\\"\"; SQLiteDatabase db = this.getWritableDatabase(); Cursor = db.rawQuery(query, null); Product = new Product(); if (cursor.moveToFirst()) { product.setID(Integer.parseInt(cursor.getString(0))); db.delete(TABLE_PRODUCTS, COLUMN_ID + \" = ?\", new String[] { String.valueOf(product.getID()) }); cursor.close(); result = true; } db.close(); 238 CU IDOL SELF LEARNING MATERIAL (SLM)

Return result; Implementing the Activity Event Methods The final task prior to testing the application is to wire up onClick event handlers on the three buttons in the user interface and to implement corresponding methods for those events. Locate and load the fragment database.xml file into the Graphical Layout tool, switch to the XML view and locate and modify the three button elements to add onClick properties Testing the Application With the coding changes completed, compile and run the application either in an AVD session or on a physical Android device. Once the application is running, enter a product name and quantity value into the user interface form and touch the Add button. Once the record has been added the text boxes will clear. Repeat these steps to add a second product to the database. Next, enter the name of one of the newly added products into the product name field and touch the Find button. The form should update with the product ID and quantity for the selected product. Touch the Delete button to delete the selected record. A subsequent search by product name should indicate that the record no longer exists. 11.2.2 Introducing the SQLite Open Helper SQLite Open Helper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases. By implementing an SQLite Open Helper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened, as well as ensure that each operation is completed efficiently. It’s good practice to defer creating and opening databases until they’re needed. The SQLite Open Helper caches database instances after they’ve been successfully opened, so you can make requests to open the database immediately prior to performing a query or transaction. For the same reason, there is no need to close the database manually unless you no longer need to use it again. 11.2.3 Creating and using SQLite Database This Section will show how quickly and easily you can set up and start using an SQLite database using LiveCode. This example will work equally well on the desktop and mobile with no changes required. Our example database will contain one table holding contact details. Creating In this example we wil be building our stack into an app so open a new Mainstack from the File menu and set its width to 768 and its height to 1024. Adding Controls 239 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure11.1: Adding controls For this simple example we only need 5 controls. We need to be able to 1. Connect to the database, and create it if it does not exist 2. Add a single table to the database 3. Populate the database with some content 4. Retrieve the content from the database and display it To do this we need 4 buttons to perform these actions and a field to display the information we retrieve from the database. Drag the buttons and field onto the stack from the tools palette and name them appropriately. Using Databases with LiveCode LiveCode provides a full range of commands and functions allowing communication with external SQL databases. You use SQL queries to specify the parts of the data you want to work with, to get data and to make changes to the database. LiveCode provides built in drivers for accessing SQLite databases, no additional installation is required. For more details on LiveCode database functionality see the Dictionary and the User Guide. Connecting to the database 240 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure: 11.2 Connecting to the database The first thing we need to do is establish a connection with the database. To do this we use the OpenDatabase command. This command establishes a connection with the database and returns the connection id. We store the connection id as we will need it when we want to communicate with the database. The command will create an SQLite database if it does not already exist. Adding a Table to the Database Next, we want to add a table to the database. To do this we construct the SQL statement that will create the table and use the ExecuteSQL command to execute the query in the database. Inserting Data into the Database The next step is to insert some records into the contact details table we have just created. Just as in the previous step this is done by constructing SQL Insert statements and using the LiveCode database commands to execute them in the database. Retrieving and Displaying Data Now we have a database with records in it, we need to retrieve that data and display it. Just a before we use and SQL query to retrieve the data from the database but in this case we use the DataFromQuery function as we want it to return data from the database so we can display it in the field. Creating the DataBase and Displaying the Data Figure11.3: Creating the database and displaying the data To create and populate the database and display the content we just need to press each button in turn. 241 CU IDOL SELF LEARNING MATERIAL (SLM)

Building a Standalone for IOS Figure11.4: Building a standalone for IOS For this example, we are building an IOS app so open up the Standalone Application Settings and select the IOS panel. Set the Internal App ID and choose your profile. Select the SQLite External from the Inclusions pane and Portrait Orientation and choose the rest of your settings. Deploying to an IOS device Figure11.5: Deploying to an IOS device Now deploy your app to your chosen device. As we stated at the start this stack will work just as well as a Desktop application with no changes required. 242 CU IDOL SELF LEARNING MATERIAL (SLM)

Setting up the standalone settings for Android Figure11.6: Setting up the standalone settings for Android To deploy to Android, you need to open the Standalone Application Settings. Check Android in the Android pane and check the SQLite External in the Inclusions pane. Deploying to Android Figure11.7: Deploying to Android 243 CU IDOL SELF LEARNING MATERIAL (SLM)

Then select the device or simulator in the Test Target in the Development Menu, click Test in the menubar and your application will be deployed to the device. 11.3 SUMMARY  SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database. It is embedded in android by default. So, there is no need to perform any database setup or administration task.  Databases store information and its contents can be everything from product catalos to repositories of customer information. For information to be easy to access, use and understand, database management systems are required.  It has been implemented as a compact C library that’s included as part of the Android software stack. By being implemented as a library, rather than running as a separate ongoing process, each SQLite database is an integrated part of the application that created it. This reduces external dependencies, minimizes latency, and simplifies transaction locking and synchronization.  Using SQLite, you can create fully encapsulated relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the /data/data//databases folder on your device (or emulator). All databases are private, accessible only by the application that created them. Database design is a big topic that deserves more thorough coverage than is possible within this book. It is worth highlighting that standard database best practices still apply in Android. In particular, when you’re creating databases for resource- constrained devices (such as mobile phones), it’s important to normalize your data to minimize redundancy  Once completed, the application will consist of an activity and a database handler class. The database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer between the underlying SQLite database and the activity class, with the activity calling on the database handler to interact with the database.  SQLite Open Helper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases. By implementing an SQLite Open Helper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened, as well as ensure that each operation is completed efficiently.  Databases store information and its contents can be everything from product catalo’s to repositories of customer information. For information to be easy to access, use and understand, database management systems are required. Database management systems can help sort information as well as link databases to each other and provide 244 CU IDOL SELF LEARNING MATERIAL (SLM)

reports about changes and trends in the information in databases. Although database management systems all perform the same basic task, which is to enable users to create, edit and access information in databases, how they accomplish this can vary. Additionally, the features, functionality, and support associated with each management system can differ significantly. 11.4 KEYWORDS  SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.  Database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system. Most databases use structured query language for writing and querying data.  Constructors have the same name as the class or struct, and they usually initialize the data members of the new object. In the following example, a class named Taxi is defined by using a simple constructor.  Coding is the process of creating instructions for computers using programming languages. Computer code is used to program the websites, apps, and other technologies we interact with every day. If you pay any attention to tech, you've undoubtedly heard the terms coding and programming dozens of times.  Android version indicates the version of Android platform. The bigger the version number is, the newer the Android is. Newer version has more and better features than their predecessors. Android has code names for different versions too. They are all confectionery-themed and have been in alphabetical order starting from Android Cupcake 1.5. 11.5 LEARNING ACTIVITY 1. How do you think Database is very useful in android? ___________________________________________________________________________ __________________________________________________________________________ 2. Find whatthe use of SQ Lite in Smartphone is. ___________________________________________________________________________ __________________________________________________________________________ 245 CU IDOL SELF LEARNING MATERIAL (SLM)

11.6 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is SQLite database? 2. Define CRUD Operations? 3. What is meant by DELETE under CRUD? 4. Describe about SQLite Open Helper. 5. What is CREATE in CRUD? Long Questions 1. Elaborate SQLite. 2. Explain briefly SQLite Database with CRUD Operations. 3. Explain briefly working with SQLite Databases. 4. Explain briefly introducing the SQLite Open Helper. 5. Explain briefly Creating and using SQLite Database B. Multiple Choice Questions 1. What is SQLite? a. NoSQL database b. Distributed database c. Relational database d. Operational database that is developing the training material for training? 2. In which code does SQLite written? a. C++ b. C c. Java d. Python 3. What does is an in-process library that implements in SQ Lite? 246 a. Self-contained b. Serverless c. Zero-configuration d. All of these CU IDOL SELF LEARNING MATERIAL (SLM)

4. What does SQLite dot commands and exception should not be terminated by? a. : b. / c. ; d. ' 5. What does SQLite is case insensitive? a. TRUE b. FALSE c. Can be true or false d. Cannot say Answers 1-c,2- b, 3-d, 4- c, 5- a 11.7 REFERENCES Textbooks  Wei - Meng Le, 2012, Beginning Android 4 Application Development”, John Wiley & Sons, Inc.  Reto Meier, 2012, Professional Android 4 Application Development”, John Wiley & Sons, Inc.  Neil Smyth · 2017, Kotlin / Android Studio Reference Books  Grant Allen, Bob Bryla, Darl Kuhn, 2010, Oracle SQL Recipes.  Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi Nakamura, 2011, “Programming Android”, O’Reilly books.  Nathan A, 2005, Regular Expression Recipes,Good · Snippet view. Websites  https://en.wikipedia.org/  https://www.gizbot.com/  https://www.geeksforgeeks.org/ 247 CU IDOL SELF LEARNING MATERIAL (SLM)

 https://www.tutorialspoint.com/ 248 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 12: DEPLOYMENT 249 STRUCTURE 12.0 Learning Objectives 12.1 Introduction 12.2 Steps to Deploy Android Application in Play Store 12.2.1 Create a Google Developer Account 12.2.2 Add a Merchant Account 12.2.3 Prepare the Documents 12.2.4 Study Google Developer Policies 12.2.5 Technical Requirements 12.2.6 Creating the App on the Google Console 12.2.7 Store Listing 12.2.8 Content Rating 12.2.9 Pricing the Application 12.2.10 Upload APK and Send for Review 12.3 Summary 12.4 Keywords 12.5 Learning Activity 12.6 Unit End Questions 12.7 References 12.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Explain Steps to Deploy Android Application in Play Store.  Explain how to Create a Google Developer Account.  Identify Technical Requirements.  Analyse Store Listing.  Add a Merchant Account.  Learn Google Developer Policies. CU IDOL SELF LEARNING MATERIAL (SLM)

12.1 INTRODUCTION Google Play and the Apple App Store are by far the two largest platforms to distribute and promote apps. To avoid any issues and possible rejections, your applications should be built following the specific requirements of each of those Stores. If you are ready to publish, chances are you already built and tested your app. testing an exact copy of your app in the same version as the one which will be released on the stores, is a very important step you shouldn’t overlook. If you are using GoodBarber, you will find in your back office dedicated online helps to generate the ADHOC version, for both the IOS and the Android version of your app. With over 1 billion monthly active users, Google Play is arguably one of the largest platforms for distributing, promoting, and selling Android apps. For newbie’s and first-timers, publishing an app on Google Play can seem like an intimidating process. Like any other app store, the platform comes with its own set of rules, regulations, and procedures and you need to understand how it works to avoid any future issues. This article is a step-by-step guide on how to successfully publish your app on the Google Play Store. When the application development process is completed, it’s high time to introduce your special product to the world. First publishing may be thrilling and tricky. Don’t worry. Today we will guide you through the release process on the Play Store that is undoubtedly the leader in the number of published apps and users. First, we’d like to give you precious advice: do not postpone some crucial tasks until the release or pre-release date. Completing them in advance will save your time and nerves. Google publishes the source code for Android through its \"Android Open Source Project\", allowing enthusiasts and developers to program and distribute their own modified versions of the operating system. However, not all these modified versions are compatible with apps developed for Google's official Android versions. The \"Android Compatibility Program\" serves to \"define a baseline implementation of Android that is compatible with third-party apps written by developers\". Only Android devices that comply with Google's compatibility requirements may install and access Google's Play Store application. As stated in a help page for the Android Open-Source Project, \"Devices that are \"Android compatible\" may participate in the Android ecosystem, including Android Market; devices that don't meet the compatibility requirements exist outside that ecosystem. In other words, the Android Compatibility Program is how we separate \"Android compatible devices\" from devices that merely run derivatives of the source code. We welcome all uses of the Android source code, but only Android compatible devices as defined and tested by the Android Compatibility Program may participate in the Android ecosystem. 250 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook