Mobile Application Development Digital Notes (2022-2023) PDF
Document Details
Uploaded by FlexibleClimax
Malla Reddy College of Engineering and Technology
2023
Tags
Summary
These are digital notes for a mobile application development course, likely for an undergraduate student at MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY. The notes cover topics including Android operating system, application components, UI design, intents, and databases. The document's keywords also include the specific course name and year.
Full Transcript
DIGITAL NOTES ON MOBILE APPLICATION DEVELOPMENT B.TECH IV YEAR - I SEM (2022-23) DEPARTMENT OF INFORMATION TECHNOLOGY MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY (Autonomous Institution – UGC, Govt. of India) (Affiliated to...
DIGITAL NOTES ON MOBILE APPLICATION DEVELOPMENT B.TECH IV YEAR - I SEM (2022-23) DEPARTMENT OF INFORMATION TECHNOLOGY MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY (Autonomous Institution – UGC, Govt. of India) (Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified) Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, INDIA. 1 MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY IV YearB.Tech IT ISem L T/P/D C 3 -/-/- 3 (R18A120) MOBILE APPLICATION DEVELOPMENT Course Outcomes Analyze architecture of android and current trends in mobile operating systems. Apply suitable software tools and APIs for the development User Interface of aparticular mobile application. Apply intents and broadcast receivers in android application. Develop and design apps for mobile devices using SQLiteDatabase. UNIT-I Introduction to Android Operating System: Android OS and Features – Android development framework; Installing and running applications on Android Studio, Creating AVDs, Types of Android application; Creating Activities, Activity Life Cycle, Activity states, monitoring state changes; UNIT- II Android application components – Android Manifest file, Externalizing recourses like Simple Values, Drawables, Layouts, Menus, etc, Building User Interfaces: Fundamental Android UI design, Layouts – Linear, Relative, Grid and Table Layouts. User Interface (UI) Components UNIT-III Fragments – Creating fragments, Lifecycle of fragments, Fragment states, Adding fragments to Activity, adding, removing and replacing fragments with fragment transactions, interfacing between fragments and Activities, UNIT-IV Intents and Broadcasts: Using intents to launch Activities, Types of Intents, Passing data to Intents, Getting results from Activities, Broadcast Receivers – Using Intent filters to service implicit Intents, Resolving Intent filters; UNIT-V Database: Introduction to SQLite database, creating and opening a database, creating tables, inserting retrieving and deleting data; TEXT BOOKS: 1. Professional Android 4 Application Development, Reto Meier, Wiley India, (Wrox), 2012 2. Android Application Development for Java Programmers, James C Sheusi, Cengage Learning, 2013 REFERENCEs: 1. Beginning Android 4 Application Development, Wei-Meng Lee, Wiley India(Wrox), 2013 2. Android Application Development (with Kitkat Support), Black Book, Pradeep Kothari, 2014, Dreamtech Press publisher, Kogent Learning Inc.,2014 3. Android Programming: Pushing the Limits, Erik Hellman, 1st Edition,Wiley Publications, 2014 2 INDEX UNIT TOPIC PAGE NO NO Introduction Android OS and Features 1-11 I Android development framework; 11-18 Installing and running applications on Android Studio 18-25 Creating Activities 26-31 Android applicationcomponents 49-52 II Building User Interfaces Critical Section problem 52-5 Fragments 66-82 III Intents and Broadcasts 90-105 IV Database 111-119 V 3 UNIT-I Introductionto Android Operating System: Android OSand Features– Androiddevelopmentframework; Installing andrunningapplicationson Android Studio, Creating AVDs, Typesof Androidapplication; CreatingActivities, Activity LifeCycle, Activitystates,monitoringstatechanges; Introduction To Android Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. Android has come a long way from its humble beginnings, as the product of a small start up, all the way to becoming the leading mobile operating system worldwide. Google’s introduction of Project Treble in Android Oreo should make it easier for phone makers to update their devices faster. One challenge for Android device owners that has beenan issue for the OS ever since it launched is updating it with the latest security patches, for major feature updates. Google’s supported Nexus and Pixel devices consistently receive regular monthly security updates, and the latest version of the OS. Operating Systems Different OS run on different types of hardware and are designed for different types of applications. For example, iOS is designed for iPhones and iPad tablets, while Mac desktops and laptops use macOS. Microsoft Windows : Initial versions of Windows worked with MS-DOS, providing a modern graphical interface on top of DOS's traditional text-based commands. The Windows Start menu helps users find programs and files on their devices. APPLE IOS Apple's iOS is one of the most popular smartphone operating systems, second only to Android. It runs on Apple hardware, including iPhones, iPad tablets and iPod Touch media players. GOOGLE'S ANDROID OS Android is the most popular operating system in the world judging by the number of devices installed. Users can download custom versions of the operating system. APPLE MAC OS Apple's macOS, successor to the popular OS X operating system, runs on Apple laptops and 4 desktops.. MacOS is known for its user-friendly features, which include Siri and FaceTime. LINUX OPERATING SYSTEM Linux can be run on a wide variety of hardware and is available free of charge over the internet. FeaturesofAndroid Android is a powerful operating system competing with Apple 4GS and support great features. Few of them are listed below: Feature Description Beautiful UI Android OS basic screen provides a beautiful and intuitive user interface. Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX. Storage SQLite, a lightweight relational database, is used for data storage purposes. Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP Messaging SMS and MMS Web browser Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3. Multi-touch Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero. Multi-tasking User can jump from one task to another and same time various application can run simultaneously. Resizable widgets Widgets are resizable, so users can expand them to show more content or shrink them to save space Multi-Language Support single direction and bi-directional text. 5 GCM Google Cloud Messaging (GCM) is a service that let developers send short message data to their users on Android devices, without needing a proprietary sync solution. Wi-Fi Direct A technology that let apps discover and pair directly, over a high- bandwidth peer-to-peer connection. Android Beam A popular NFC-based technology that let users instantly share, just by touching two NFC-enabled phones together. THE DEVELOPMENT FRAMEWORK: ANDROID ARCHITECTURE Android operating system is a stack of software components which is roughly divided into five sections and four main layers as shown below in the architecture diagram Android is structured in the form of a software stack comprising applications, an operating system, run-time environment, middleware, services and libraries. Each layer of the stack, and the corresponding elements within each layer, are tightly integrated and carefully tunedto provide the optimal application development and execution environment for mobile devices. THE LINUX KERNEL Positioned at the bottom of the Android software stack, the Linux Kernel provides a level of abstraction between the device hardware and the upper layers of the Android software stack. Based on Linux version 2.6, the kernel provides pre-emptive multitasking, low-level core system services such as memory, process and power management in addition to providing a network stack and device drivers for hardware such as the device display, Wi-Fi and audio. ANDROID RUNTIME – ART When an Android app is built within Android Studio it is compiled into an intermediate byte- code format (DEX format). When the application is subsequently loaded onto the device, the Android Runtime (ART) uses a process referred to as Ahead-of-Time (AOT) compilation to translate the byte-code down to the native instructions required by the device processor. This format is known as Executable and Linkable Format (ELF). Each time the application is subsequently launched, the ELF executable version is run, resulting in faster application performance and improved battery life. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes use of Linux core features like memory management and multi- threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language. 6 ANDROID LIBRARIES In addition to a set of standard Java development libraries (providing support for such general purpose tasks as string handling, networking and file manipulation), the Android development environment also includes the Android Libraries. These are a set of Java-based libraries that are specific to Android development. C/C++ LIBRARIES The Android runtime core libraries are Java-based and provide the primary APIs for developers writing Android applications. It is important to note, however, that the corelibraries do not perform much of the actual work and are, in fact, essentially Java ―wrappers‖ around a set of C/C++ based libraries. APPLICATION FRAMEWORK The Application Framework is a set of services that collectively form the environment in which Android applications run and are managed. This framework implements the concept that Android applications are constructed from reusable, interchangeable and replaceable components. This concept is taken a step further in that an application is also able to publish its capabilities along with any corresponding data so that they can be found and reused by other applications. APPLICATIONS Located at the top of the Android software stack are the applications. These comprise both the native applications provided with the particular Android implementation (for example web browser and email applications) and the third party applications installed by the user after purchasing the device. 7 INSTALLING AND RUNNING APPLICATIONS ON ANDROID STUDIO Step 1 - System Requirements 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 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- 143.3101438-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 8 Once you launched Android Studio, its time to mention JDK path or later version in android studio installer. Below the image initiating JDK to android SDK Need to check the components, which are required to create applications, below the image has selected AndroidStudio, AndroidSDK, AndroidVirtualMachineand performance(Intelchip). 9 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. 10 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. 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 11 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) 12 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. 13 Step 3 - Create 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 14 ur 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. 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 ). 15 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 above. CREATING AN ANDROID PROJECT CREATE THE APP PROJECT 1. Open Android Studio if it is not already opened. 2. In the main Welcome to Android Studio window, click StartanewAndroid Studioproject. 3. In the Create Android Project window, enter Hello World for the Application name. 4. Verify that the default Project location is where you want to store your Hello World app and other Android Studio projects, or change it to your preferred directory. 5. Accept the default android.example.com for Company Domain, or create a unique company domain. If you are not planning to publish your app, you can accept the default. Be aware that changing the package name of your app later is extra work. 6. Leave unchecked the options to Include C++support and Include Kotlin support, and click Next. 7. On the TargetAndroidDevicesscreen, PhoneandTabletshouldbeselected. Ensure that API15:Android4.0.3IceCreamSandwichis set to Minimum SDK; if not, usethe popup menu to set it. 16 hese are the settings. As of this writing, these settings make Hello World app compatible with 9% of Android devices active on the Google Play Store. 8. Leave unchecked the Include Instant App support and all other options. Then click Next. If your project requires additional components for your chosen target SDK, Android Studio will install them automatically. 9. The Add an Activity window appears. An Activity is a single, focused thing that the user can do. It is a crucial component of any Android app. An Activity typically has a layout associated with it that defines how UI elements appear on a screen. Android Studio provides Activity templates to help you get started. For the Hello Worldproject, choose Empty Activity as shown below, and click Next. 10. The Configure Activity screen appears (which differs depending on which template you chose in the previous step). By default, the empty Activity provided by the template is named MainActivity. You can change this if you want, but this lesson uses MainActivity. 11. Make sure that the Generate Layout file option is checked. The layout nameby default is activity_main. You can change this if you want, but this lesson uses activity_main. 12. Make sure that the Backwards Compatibility (App Compat) option is checked. This ensures that your app will be backwards-compatible with previous versions of Android. 13. Click Finish. Android Studio creates a folder for your projects, and builds the project with Gradle. The Android Studio editor appears. Follow these steps: 1. Click the activity_main.xmltab to see the layout editor. 2. Click the layout editor Design tab, if not already selected, to show a graphicalrendition of the layout as shown below. 3. Click the MainActivity.java tab to see the code editor as shown below. Explore the Project > Android pane. 1. If not already selected, click the Project tab in the vertical tab column on the left side of the Android Studio window. The Project pane appears. 2. To view the project in the standard Android project hierarchy, choose Android from the popup menu at the top of the Project pane, as shown below. Explore the manifests folder e manifests folder contains files that provide essential information about your app to the Android system, which the system must have before it can run any of the app's code. 17 Expand the manifests folder. 1. Open the AndroidManifest.xml file. 2. The AndroidManifest.xml file describes all of the components of your Android app. All components for an app, such as each Activity, must be declared in this XML file. In other course lessons you will modify this file to add features and feature permissions. For an introduction, see App Manifest Overview. RUN ON EMULATOR 1.Lets create an android virtual device (avd). In order to run an emulator on your computer, you have to create a configuration that describes the virtual device. In Android Studio, select Tools > Android > AVD Manager, or click the AVD Manager icon in the toolbar. The Your Virtual Devices screen appears. If you've already created virtual devices, the screen shows them; otherwise you see a blank list. 2.Click the +Create Virtual Device. The Select Hardware window appears showing a list of pre configured hardware devices. For each device, the table provides a column for its diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density(Density). 3. Choose a device such as Nexus 5x or Pixel XL, and click Next. The System Image screen appears. 4.Click the Recommended tab if it is not already selected, and choose which version of the Android system to run on the virtual device (such as Oreo).Click the link to start thedownload, and click Finishwhen it's done. 5.After choosing a system image, click Next. The Android Virtual Device (AVD) window appears. You can also change the name of the AVD. Check your configuration and click Finish. Run the app on the virtual device Let’s run your Hello World app. 1. In Android Studio, choose Run> Runapp or click the Run icon in thetoolbar. 2. TheSelectDeploymentTarget window,underAvailableVirtual Devices,selectthe virtual device, which you just created, and click OK The emulator starts and boots just like a physical device. Your app builds, and once the emulato r is ready, Android Studio will upload the app to the emulator and run it. 18 DEPLOY IT ON USB-CONNECTED ANDROID DEVICE Configure the Android device In order to install an application directly to your device, you need to configure it to use a USB connection. The configuration settings vary by device. For Android 4.2 and later devices, you need to enable Developer options by opening Settings, click About then click the Build number item seven items. If you do not do this, you will not see the Developer options item in Settings. 1. Open Settings. 2. Click Security. 3. Enable Unknown sources, that is, check this option. This permits the device to install apps that do not originate from Google Play. 4. Back out to Settings. 5. Click Developer options. 6. If available: Set the switch in the title bar to on. 7. Enable USB debugging, that is, check this option. This permits the device to install apps over a USB connection. 8. Optional: Enable Stay awake, that is, check this option. This option keeps the screen on and disables the lock screen while the device is connected to USB. 9. Optional: Enable Allow mock locations, that is, check this option. This option creates fake GPS locations to test location services. 10. Back out of or close Settings. Install the USB driver (Windows only) Developers on Windows may need to install a USB driver specific to the manufacturer and model of the device on which they'll be testing. The driver enables your Windows computer to communicate with your Android device. Google provides download links to the drivers at Android Developer: OEM USB Drivers. Connect the device Connect the Android device to your computer using an USB cord. Note that some USB cables are only power cables and do not allow communications with the device. Make sure you use a USB cable that allows a data connection. For 4.2 devices, an "Allow USB debugging?" dialog will appear once connected via USB. Click the OK button. Deploy the application using Axway Appcelerator Studio Once you have configured your device and connected it to your computer's USB port, you are ready to deploy your app to it. 19 In Studio, first select the project in the Project Explorer view, then in the global tool bar, select Run from the Launch Mode drop-down list and an Android device from the Target drop-down list under the Android Application Installer category. If the Launch Automatically option is enabled under the Target drop- down list, the application will be automatically launched after the device is selected. If not, you need to click the Run button to start the build process. Your app will be built, installed to your device and automatically launched CREATING ACTIVITIES An activity is the single screen in android. It is like window or frame of Java. By the help of activity, you can place all your UI components or widgets in a single screen. 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. 20 Android Activity Lifecycle Let's see the lifecycle methods of android activity. 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. 21 Sr.No Callback & Description 1 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 call ed when the c activity is being resumed. onStop() 5 This callback is called when the activity is no longer visible. onDestroy() 6 This callback is called before the activity is destroyed by the system. onRestart() This callback is called when the activity restarts after stopping it. 22 xample This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter − Step Description 1 You will use Android studio to create an Android application and name it as HelloWorld under a pack ge World Example chapter. 2 Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged. 3 Run the application to launch Android emulator and verify the result of the changes done in the applic tio Page 23 23 Android Activity Lifecycle Example It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content on the logcat. File: MainActivity.java package example.mrcet.com.activitylifecycle; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("lifecycle","onCreate invoked"); } @Override protected void onStart() { super.onStart(); Log.d("lifecycle","onStart invoked"); } @Override protected void onResume() { super.onResume(); Log.d("lifecycle","onResume invoked"); } @Override protected void onPause() { super.onPause(); Log.d("lifecycle","onPause invoked"); } @Override protected void onStop() { super.onStop(); Log.d("lifecycle","onStop invoked"); } @Override protected void onRestart() { super.onRestart(); Log.d("lifecycle","onRestart invoked"); } 24 An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file: setContentView(R.layout.activity_main); An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an that includes the MAIN action and LAUNCHER category as follows: File: activity_main.xml 1. 2. 8. 9. 1. 18. 25 UNIT - II Androidapplicationcomponents– Android Manifestfile, Externalizingrecourseslike Simple Values, Drawables, Layouts, Menus, etc, Building User Interfaces: Fundamental Android UI design, Layouts – Linear, Relative, Grid and Table Layouts. User Interface (UI)Components ANDROID-APPLICATIONCOMPONENTS Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact. There are following four main components that can be used within an Android application − Sr.No Components & Description 1 Activities They dictate the UI and handle the user interaction to the smart phone screen. Services 2 They handle background processing associated with an application. Broadcast Receivers 3 They handle communication between Android OS and applications. Content Providers 4 They handle data and database management issues. Activities An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. An activity is implemented as a subclass of Activity class as follows − public class MainActivity extends Activity { } Services 26 service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. A service is implemented as a subclass of Service class as follows − public class MyService extends Service { } Broadcast Receivers Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object. public class MyReceiver extends BroadcastReceiver { public void onReceive(context,intent){} Content Providers A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. public class MyContentProvider extends ContentProvider { public void onCreate(){} } We will go through these tags in detail while covering application components in individual chapters. Additional Components There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are − S.No Components & Description 1 Fragments Represents a portion of user interface in an Activity. Views 2 UI elements that are drawn on-screen including buttons, lists forms etc. 27 Layouts 3 View hierarchies that control screen format and appearance of the views. Intents 4 Messages wiring components together. Resources 5 External elements, such as strings, constants and drawable pictures. Manifest 6 Configuration file for the application. ANDROID MANIFEST FILE The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc. It performs some other tasks also: o It is responsible to protect the application to access any protected parts by providing the permissions. o It also declares the android api that the application is going to use. o It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc. This is the required xml file for all the android application and located inside the root directory. Manifest file: 28 EXTERNALIZING RESOURCES: There are many more items which you use to build a good Android application. Apart from coding for the application, you take care of various other resources like static content that your code uses, such as bitmaps, colors, layout definitions, user interface strings, animation instructions, and more. These resources are always maintained separately in various sub-directories under res/ directory of the project. This tutorial will explain you how you can organize your application resources, specify alternative resources and access them in your applications. Organize resource in Android Studio MyProject/ app/ manifest/ AndroidManifest.xm l java/ MyActivity.java res/ drawable/ icon.png layout/ activity_main.xm l info.xml values/ strings.xml Sr.No. Directory & Resource Type 29 1 anim/ XML files that define property animations. They are saved in res/anim/ folder and accessed R.a from the 2 color/ XML files that define a state list of colors. They are saved in res/color/ and accessed from r cla the R.colo 3 drawable/ Image files like.png,.jpg,.gif or XML files that are compiled into bitmaps, state lists, io shapes, animat accessed from the R.drawable class. 4 layout/ XML files that define a user interface layout. They are saved in res/layout/ and accessed ayo from the R.l 5 menu/ XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. T the R.menu class. 6 raw/ ou Arbitrary files to save in their raw form. You need to call Resources.openRawResource() with the re files. values/ e fi XML files that contain simple values, such as strings, integers, and colors. For example, here are som in this directory − arrays.xml for resource arrays, and accessed from the R.array class. integers.xml for resource integers, and accessed from the R.integerclass. bools.xml for resource boolean, and accessed from the R.bool class. colors.xml for color values, and accessed from the R.color class. dimens.xml for dimension values, and accessed from the R.dimen class. strings.xml for string values, and accessed from the R.string class. styles.xml for styles, and accessed from the R.style class. 30 8 xml/ Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You can save various confi Alternative Resources Your application should provide alternative resources to support specific device configurations. For example, you should include alternative drawable resources ( i.e.images ) for different screen resolution and alternative string resources for different languages. At runtime, Android detects the current device configuration and loads the appropriate resources for your application. To specify configuration-specific alternatives for a set of resources, follow the following steps − Create a new directory in res/ named in the form -. Here resources_name will be any of the resources mentioned in the above table, like layout, drawable etc. The qualifier will specify an individual configuration for which these resources are to be used. You can check official documentation for a complete list of qualifiers for different type ofresources. Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files as shown in the below example, but these files will have content specific to the alternative. For example though image file name will be same but for high resolution screen, its resolution will be high. Below is an example which specifies images for a default screen and alternative images for high resolution screen. MyProject/ app/ manifest/ AndroidManifest.xm l java/ MyActivity.java res/ drawable/ icon.png background.png drawable-hdpi/ icon.png background.png layout/ activity_main.xm l info.xml values/ strings.xml Below is another example which specifies layout for a default language and alternative layout for Arabic 31 language. MyProject/ app/ manifest/ AndroidManifest.xm l java/ MyActivity.java res/ drawable/ icon.png background.png drawable-hdpi/ icon.png background.png layout/ activity_main.xm l info.xml layout-ar/ main.xml values/ strings.xml Accessing Resources During your application development you will need to access defined resources either in your code, or in your layout XML files. Following section explains how to access your resources in both the scenarios − Accessing Resources in Code When your Android application is compiled, a R class gets generated, which contains resource IDs for all the resources available in your res/ directory. You can use R class to access that resource using sub- directory and resource name or directly resource ID. Example To access res/drawable/myimage.png and set an ImageView you will use following code − ImageView imageView = (ImageView) findViewById(R.id.myimageview); Here first line of the code make use of R.id.myimageview to get ImageView defined with id myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get an image with name myimage available in drawable sub-directory under/res. Example Consider next example where res/values/strings.xml has following definition − Hello, World! Now you can set the text on a TextView object with ID msg using a resource ID as follows − TextView msgTextView = (TextView) findViewById(R.id.msg); msgTextView.setText(R.string.hello); 32 android:layout_width="fill_parent " android:layout_height="fill_paren t" android:orientation="vertical" >