Sie sind auf Seite 1von 179

The Android SDK includes a comprehensive set of development tools.

These include a debugger, libraries, a handset emulator (based on QEMU), documentation, sample code, and tutorials. Currently supported development platforms include x86- architecture computers running. Linux (any modern desktop Linux distribution),Mac OS X 10.4.8 or later, Windows XP or Vista. Requirements also include Java Development Kit, Apache Ant, and Python 2.2 or later. The officially supported integrated development environment (IDE) is Eclipse (3.2or later) using the Android Development Tools (ADT) Plug-in, though developers may use any text editor to edit Java and XML files then use command line tools to create, build and debug Android applications. In 26th October, 2009 the clair version (2.0) was released which featured better search, battery usage indicator and VPN control applet. New platform technologies included Optimized hardware speed Support for more screen sizes and resolutions New browser UI and HTML5 support New contact lists Better white/black ratio for backgrounds Microsoft Exchange support Built in flash support for Camera Digital Zoom Improved virtual keyboard Bluetooth 2.2 Android Applications are packaged in .apk format and stored under /data/app folder on the Android OS. The user can run the command adb root to access this folder as only the root has permissions to access this folder. There are four of the most significant tools are: Android Emulator A virtual mobile device that runs on our computer -use to design, debug, and test our applications in an actual Android run-time environment. The Android SDK includes a mobile device emulator a virtual mobile device that runs on your computer. The emulator lets you prototype, develop, and test Android applications without using a physical dev.

The Android emulator mimics all of the typical hardware and software features of a typical mobile device, except that it can place actual phone calls. It provides a variety of navigation and control keys, which you can press using your mouse or keyboard to generate events for your application. It also provides a screen in which your application is displayed, together with any other Android applications running. To let you model and test your application more easily, the emulator supports Android Virtual Device (AVD) configurations. AVDs let you specify the Android platform that you want to run on the emulator, as well as the hardware options and emulator skin fill you want to use. Once your application is running on the emulator, it can use the services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and themes. The emulator also includes a variety of debug capabilities, such as a console from which you can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data channel. Emulator Limitations: No support for placing or receiving actual phone calls. You can simulate phone calls (placed and received) through the emulator console, however. No support for USB connections No support for camera/video capture (input). No support for device-attached headphones No support for determining connected state No support for determining battery charge level and AC charging state No support for Bluetooth. No support for Voice Recognition ADT Plug-in The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications: It gives you access to other Android development tools from inside the Eclipse IDE. For example, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage port-forwarding, set breakpoints, and view thread and process information directly from Eclipse. It provides a New Project Wizard, which helps you quickly create and set up all of the basic files youll need for a new Android application.

It automates and simplifies the process of building your Android application. It provides an Android code editor that helps you write valid XML for your Android manifest and resource files. Android Development Tools Plugin For the Eclipse IDE is a multi-language software Development environment comprising an Integrated development enviroment (IDE) and an extensible plug-in system. Eclipse is a multi-language software development environment comprising an integrated development environment (IDE) and an extensible plug-in system. It is written mostly in Java. It can be used to develop applications in Java and, by means of various plug-ins, other programming languages including Ada, C, C++, COBOL, Haskell, Perl, PHP, Python, R, Ruby (including Ruby on Rails framework), Scala, Clojure, Groovy and Scheme. It can also be used to develop packages for the software Mathematica. Development environments include the Eclipse Java development tools (JDT) for Java, Eclipse CDT for C/C++, and Eclipse PDT for PHP, among others. The initial codebase originated from VisualAge. The Eclipse SDK (which includes the Java development tools) is meant for Java developers. Users can extend its abilities by installing plug-ins written for the Eclipse Platform, such as development toolkits for other programming languages, and can write and contribute their own plug-in modules. Released under the terms of the Eclipse Public License, Eclipse SDK is free and open source software. It was one of the first IDEs to run under GNU Classpath and it runs without issues under IcedTea. Dalvik Debug Monitor Server (DDMS) Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. Now we can discuss Architecture of android. Designed to be more fault-tolerant than many of its predecessors. The handset runs a Linux operating system upon which android applications are executed in a secure fashion. Each Android application runs in its own virtual machine. Android applications are managed code therefore; they are much less likely to cause the phone to crash.

The Linux Operating System :The Linux 2.6 kernel handles core system services and acts as a hardware abstraction layer (HAL) between the physical hardware of the handset and the Android software stack. Some of the core functions the kernel handles include Enforcement of application permissions and security Low-level memory management Process management and threading The network stack Display, keypad input, camera, Wi-Fi, Flash memory, audio Driver access Android Application Runtime Environment Each Android application runs in a separate process, with its own instance of the Dalvik virtual machine (VM). Based on the Java VM, the Dalvik design has been optimized for mobile devices. The Dalvik VM has a small memory footprint, and multiple instances of the Dalvik VM can run concurrently on the handset. How to Developing Android Applications The Android SDK provides an extensive set of application programming interfaces (APIs) that is both modern and robust. When granted the appropriate permissions, Android applications can share data among one another and access shared resources on the system securely. Android Programming Language Choices Android applications are written in Java , and is developers only choice on the Android platform for now. Other programming languages, such as C++, might be added in future versions of Android. If your application must rely on native code in another language such as C or C++, you might want to consider integrating it using the Android Native Development Kit (NDK). No Distinctions Made Between Native and Third-Party Applications Unlike other mobile development platforms, there is no distinction between native applications and developer-created applications on the Android platform. Provided the application is granted the appropriate permissions all applications have the same access to core libraries and the underlying hardware interfaces. Android handsets ship with a set of native applications such as a web browser and contact manager. Third-party applications might integrate with these core applications, extend them to provide a rich user experience, or replace them entirely with alternative applications.

Commonly Used Packages Developers use familiar class libraries exposed through Androids Java packages to perform common tasks such as Graphics, Database access, Network access, Secure communications, and Utilities (such as XML parsing). The Android packages include support for common user interface widgets (Buttons, Spin Controls, Text Input) User interface layout Secure networking and web browsing features (SSL,WebKit) Structured storage and relational databases (SQLite). Powerful 2D and 3D graphics (including SGL and OpenGL ES) Audio and visual media formats (MPEG4, MP3, Still Images) Access to optional hardware such as location-based services (LBS),Wi-Fi, Bluetooth, Hardware sensors. Android application lifecycle The Android application lifecycle involves the following key components: Activities are functions the application performs or an object that has a life cycle-is a chunk of code that does some work. Groups of views define the applications layout an object that knows how to draw itself to the screen. Intents inform the system about an applications plans or a simple message object that represents an intention to do something. Services allow for background processing without user interaction or is a body of code that runs in the background. Notifications alert the user when something interesting happens andis a small icon that appears in the status bar(SMS messages) for alerting the user Android applications can interact with the operating system and underlying hardware using a collection of managers.

Android Project Structure: AndroidManifest.xml Global application description file. Defines your applications capabilities permissions and how it runs. Default.properties Defines your applications build target other build system options src Folder Required folder where all source code for the application resides. src/com.androidbook.myfirstandroidapp/ MyFirstAndroidAppActivity.java Defines your applications build target other build system options. gen Folder Required folder where auto-generated resource files for the application reside. gen/com.androidbook.myfirstandroidapp/R.java Application resource management source file generated for you; it should not be edited. res Folder Required folder where all application resources are managed. Application resources include Animations, Drawable, Image assets, Layout files, XML files, Data resources such as strings Raw files. res/drawable-*/icon.png Resource folders that store different resolutions of the application icon. res/layout/main.xml Single screen layout file. res/values/strings.xml Application string resources. Assets Folder

Folder where all application assets are stored. Application assets are pieces of application data (files, directories) that you do not want managed as application resources. Methods in the android.util.Log class Add the appropriate import statement for the Log class: import android.util.Log; Method Log.e() Log.w() Log.i() Log.d() Log.v() Purpose Log Errors Log Warnings Log Informational Messages Log Debug Messages Log Verbose Messages

android.media package You can create MediaPlayer objects from existing application resources or by specifying a target file using a Uniform Resource Identifier (URI). Methods in the android.media.MediaPlayer and android.net.Uri classes. Method MediaPlayer.create() MediaPlayer.start() MediaPlayer.stop() MediaPlayer.release() Uri.parse() Purpose Creates a new Media Player with a given target to play Starts media playback Stops media playback Releases the resources of the Media Player object Instantiates a Uri object from an appropriately formatted URI addre

Lifecycle of an Android Activity Android applications can be multi-process. Android OS allows multiple applications to run concurrently, provide memory and processing power is

available. Application can have background processes, and application can be interrupted and paused when event such as phone call occurs. There can be only one active application visible to the user at a time. (Specifically a single application Activity is in the foreground at any given time.) Android OS keeps track of all activity objects running by placing them on Activity stacks. When a new Activity starts, the Activity on thetop of the stack (the current foreground Activity) pauses, and the new Activity pushes onto the top of the stack. When that Activity finishes that Activity is removed from the activity stack, and the previous Activity in the stack resumes. onCreate() An Activity first starts, the onCreate() method is called. Has a single parameter, a Bundle, which is null if this is a newly started Activity. Activity was killed for memory reasons and is now restarted, the Bundle contains the previous state information for this Activity so that it can reinitiate. Appropriate to perform any setup, such as layout and data binding in the onCreate() method. Calls to the setContentView() method. onResume() Method is called when Activity reaches the top of the activity stack and becomes the foreground process. Most appropriate place to retrieve any instances to resources. Resources are the most process-intensive, so we only keep these around while the Activity is in the foreground. The onResume() method is the appropriate place to start audio, video, and animations. onPause() When another Activity moves to the top of the activity stack, the current activity is informed that it is being pushed down the activity stack by way of the onPause() method. Activity should stop any audio, video, and animations it started in the onResume() method. Deactivate resources such as database Cursor objects if opted to manage them manually, as opposed to having them managed automatically. To clean up and release any resources it does not need while in the background. Need to save any uncommitted data here, in case your application does not resume. The new foreground Activity is not started until the onPause() method returns. Any resources and data retrieved in the onResume() method should be released in the onPause() method. If they arent, there is a chance that these resources cant be cleanly released if the process is terminated.

onSaveInstanceState() The more resources released by an Activity in the onPause() method, the less likely the Activity is to be killed while in the background. Activity can save state information to a Bundle object using the onSaveInstanceState() callback method. This call is not guaranteed under all circumstances, so use the onPause() method for essential data commits. When this Activity is returned to later, this Bundle is passed into the onCreate() method, allowing the Activity to return to the exact state it was in when the Activity paused. onRestoreInstanceState() read Bundle information after the onStart() callback method.

onDestroy() When an Activity is being destroyed, the onDestroy() method is called. The onDestroy() method is called for one of two reasons: The Activity has completed its lifecycle voluntarily Activity is being killed by the Android operating system because it needs the resources. The isFinishing() method returns false if the Activity has been killed by the Android operating system. Avoiding Activity Objects Being Killed Under low-memory conditions, the Android operating system can kill the process for any activity that has been Paused. Stopped. Destroyed. Any activity which is not in foreground is subject to shutdown. If the Activity is killed after onPause(), the onStop() and onDestroy() methods might not be called. Killing an Activity does not remove it from the activity stack. Instead, the activity state is saved into a Bundle object. When the user returns to the Activity later, the onCreate() method is called again, this time with a valid Bundle object as the parameter. How to Creating Intent in Android An Intent (android.content.Intent) is an asynchronous message mechanism used by android operating system to match task requests with the appropriate activity or

Service (launching it, if necessary) to dispatch broadcast Intents events to the system at large. Launching a New Activity by Class Name Activity can be started in many ways. Use the Application Context object to call the start Activity() method, which takes a single parameter, an Intent. This Intent requests the launch of the target Activity named MyDrawActivity by its class. This class is implemented elsewhere within the package. startActivity(new Intent(getApplicationContext(), MyDrawActivity.class)); code for transition from one Activity to the next. Intent structure to pass data between Activities. How to Creating Intents with Action and Data Intents need not specify the component or class they want to launch explicitly. The Android operating system attempts to resolve the Intent requirements and launch the appropriate activity based on the filter criteria. The guts of the Intent object are composed of two main parts: The action to be performed the data to be acted upon. Launching an Activity Belonging to another Application An Intent is basically saying do this (the action) to that (the Uri describing what resource to do the action to). Creating Intents with Action and Data With the appropriate permissions, applications might also launch external Activities within other applications apart from starting only Activities defined within its own package. For example, a Customer Relationship Management (CRM) application might launch the Contacts application to browse the Contact database, choose a specific contact, and return that Contacts unique identifier to the CRM application for use. Example of how to create a simple Intent with a predefined Action (ACTION_DIAL) to launch the Phone Dialer with a specific phone number to dial in the form of a simple Uri object: Uri number = Uri.parse(tel:5555551212); Intent dial = new Intent(Intent.ACTION_DIAL, number); startActivity(dial);

Passing Additional Information Using Intents You can also include additional data in an Intent. The Extras property of an Intent is stored in a Bundle object. The Intent class also has a number of helper methods for getting and setting name/value pairs for many common datatypes. For example, the following Intent includes two extra pieces of information a string value and a boolean: Intent intent = new Intent(this, MyActivity.class); intent.putExtra (SomeStringData,Foo); intent.putExtra (SomeBooleanData,false); Android ManiFest file: It is used to determine applications settings such as Application name and version what permissions the application requires to run what application components it is comprised of How to Configuring the Android Manifest File Specially formatted XML file with every android application. Important information about the application identity. Manifest file is named AndroidManifest.xml Must be included at the top level of any Android project The information in this file is used by the Android system to Install and upgrade the application package. Display the application details such as the application name, description, and icon to users. Specify application system requirements, including which Android SDKs are supported, what hardware configurations are required (for example, d-pad navigation), and which platform features the application relies upon (for example, uses multitouch capabilities). Launch application activities. Manage application permissions. Configure other advanced application configuration details, including acting as a service, broadcast receiver, or content provider. Enable application settings such as debugging and configuring instrumentation for application testing.

Editing the Manifest File Using Eclipse Eclipse Manifest File resource editor organizes the manifest information into categories: The Manifest tab The Application tab The Permissions tab The Instrumentation tab The AndroidManifest.xml tab Manifest Tab Contains package-wide settings including Package name Version information Supported android SDK Min SDK version Target SDK version Max SDK version. Hardware or feature requirement Application Tab Contains application-wide settings including Application Toggle Application Attributes Theme Label Icon Description Application Nodes Information about application component Activities Metadata Provider Services Permissions Tab Ccontains any permission rules required by application. Used to enforce custom permissions for application.

Instrumentation Tab To declare any instrumentation classes for monitoring the application. Editing the Manifest File Manually Generally include a single <manifest> tag with a single <application> tag. Sample android multimedia application code. Managing Your Applications Identity Android manifest file defines the application properties. The package name must be defined within the Android manifest file within the <manifest> tag using the package attribute: <manifest xmlns:android=http://schemas.android.com/apk/res/android package=com.androidbook.multimedia android:versionCode=1 android:versionName=1.0> Versioning the application It is vital to maintaining your application in the field. Versioning can help reduce confusion and make product support and upgrades simpler.There are two different version attributes defined within the <manifest> tag: The version name and The version code. The version name (android:versionName) is a user-friendly, developer-defined version attribute. This information is displayed to users when they manage applications on their devices and when they download the application from marketplaces. Developers use this version information to keep track of their application versions in the field. The Android operating system uses the version code (android: versionCode) that is a numeric attribute to manage application upgrades. Setting the Application Name and Icon Set information such as the application icon (android:icon) and friendly name (android:label). These settings are attributes of the <application> tag. For example, here we set the application icon to a drawable resource provided with the application package and the application label to a string resource:

<application android:icon=@drawable/icon android:label=@string/app_name> set optional application settings as attributes in the <application> tag, such as the application description (android:description) and the setting to enable the application for debugging on the device (android:debuggable=true). Enforcing Application System Requirements Android manifest file is also used to specify any system requirements necessary for the application to run properly. For example, an augmented reality application might require that the handset have GPS, a compass, and a camera. Similarly, an application that relies upon the Bluetooth APIs available within the Android SDK requires a handset with an SDK version of API Level 5 or higher (Android 2.0). Types of system requirements can be defined and enforced in the Android manifest file. When an application is listed on the Android Market, applications can be filtered by these types of information. The Android platform also checks these requirements when installing the application package on the system and errors out if necessary. Some of the application system requirements that developers can configure through the android manifest file include. The Android SDK versions supported by the application. The Android platform features used by the application. The Android hardware configurations required by the application. The screen sizes and pixel densities supported by the application. Any external libraries that the application links to. Targeting Specific SDK Versions Android devices run different versions of the Android platform. Developers must decide who their target audience is for a given application? Are they trying to support the largest population of users and therefore want to support as many different versions of the platform as possible? Are they developing advanced-edge game that requires the latest device hardware?

Specify which versions of the Android platform an application supports within its Android manifest file using the <uses-sdk> tag <uses-sdk> tag within an applications manifest file and is a required tag for applications that want to be published on the Android Market. This tag has three important attributes: The minSdkVersion attribute: This attribute specifies the lowest API level that the application supports. The targetSdkVersion attribute: The maxSdkVersion attribute: This attribute specifies the highest API level that the application supports. Each attribute of the <uses-sdk> tag is an integer that represents the API level associated with a given Android SDK. it is the revision of the API level associated with that SDK. The API level is set by the developers of the Android SDK. Specifying the Minimum SDK Version This value represents the lowest Android SDK version your application supports. For example, if your application requires APIs introduced in Android SDK 1.6, add the following to your Android Manifest file within the <manifest> tag block: <uses-sdk android:minSdkVersion=4 /> Use the lowest API level possible if you want your application to be compatible with the largest number of Android handsets. Specifying the Target SDK Version This value represents the Android SDK version your application was built for and tested against. For example, if your application was built using the APIs that are backwardcompatible to Android 1.6 (API Level 4), but targeted and tested using Android 2.2 SDK (API Level 8), then you would want to specify the targetSdkVersion attribute as 8. Therefore, add the following to your Android manifest file within the <manifest> tag block: <uses-sdk android:minSdkVersion=4 android:targetSdkVersion=8 /> The internals of that methodits behaviormight have changed slightly from SDK to SDK. The application should continue to behave in the old way

despite any new changes or improvements to the SDK that might cause unintended consequences in your application. Specifying the Maximum SDK Version This value represents the highest Android SDK version your application supports, in terms of API level. It restricts forward-compatibility of your application. if you want to limit who can install the application to exclude devices with the newest SDKs. For example, you might develop a free beta version of your application with plans for a paid version for the newest SDK. By setting the maxSdkVersion attribute of the manifest file for your free application, you disallow anyone with the newest SDK to install the free version of the application. Use maxSdkVersion only when absolutely necessary and when you understand the risks associated with its use. Resource file: What Are Resources? All Android applications are composed of two things: functionality (code instructions) and data (resources). The functionality is the code that determines how your application behaves. This includes any algorithms that make the application run. Resources include text strings, images and icons, audio files, videos, and other data used by the application. Storing Application Resources Android resource files are stored separately from the java class files in the Android project. Most common resource types are stored in XML. Store raw data files and graphics as resources.Understanding the Resource Directory Hierarchy Resources are organized in a strict directory hierarchy within the Android project. All resources must be stored under the /res project directory in specially named subdirectories that must be lowercase. Different resource types are stored in different directories. The resource sub-directories generated when you create an Android project using the Eclipse plug-in. Default Android Resource Directories

Each resource type corresponds to a specific resource subdirectory name. For example, all graphics are stored under the /res/drawable directory structure. For example, the /res/drawable-hdpi directory stores graphics for high-density screens /res/drawable-ldpi directory stores graphics for low-density screens, and the /res/drawable-mdpi directory stores graphics for medium-density screens. If you had a graphic resource that was shared by all screens, you would simply store that resource in the /res/drawable directory. Using the Android Asset Packaging Tool the plug-in detects new resources when you add them to the appropriate project resource directory under /res automatically. These resources are compiled, resulting in the generation of the R.java file, which enables you to access your resources programmatically. aapt tool in the /tools subdirectory of each specific Android SDK version command- line interface to compile your resources and package your application binaries to deploy to the phone or emulator. Resource Value Types Android applications rely on many different types of resourcessuch as text strings, graphics, and color schemesfor user interface design. These resources are stored in the /res directory of your Android project in a strict (but reasonably flexible) set of directories and files. All resources filenames must be lowercase and simple (letters, numbers, and underscores only). Storing Simple Resource Types Strings Each resource file under the /res/values directory should begin with the following XML header: <?xml version=1.0 encoding=utf-8?> root node is <resources> followed by specific resource type elements such as <string> or <color>. Storing Graphics, Animations, Menus, and Files store numerous other types of resources, such as animation sequences, graphics, arbitrary XML files, and raw files. These types of resources are not stored in the /res/values directory instead stored in specially named directories according to their type. E.g. animation sequence definitions in the /res/anim directory. How Resources Are Resolved An android project resources can be organized based upon more than a dozen different types of criteria, including language and region, screen characteristics, device modes (night mode, docked, and so on),

input methods, and many other device differentiators. Resources stored at the top of the resource hierarchy as default resources and the specialized versions of those resources as alternative resources common reasons that developers use alternative resources are: for internationalization and localization purposes and to design an application that runs smoothly on different device screens and orientations. Default resources example: The resources are stored in the top-level resource directories (for example, /res/values /strings.xml, /res/drawable/myLogo.png, and /res/layout/main.xml). No matter what Android device (huge hi-def screen, postage-stamp-sized screen, English or Chinese language or region, portrait or landscape orientation, and so on), you run this application on, the same resource data is loaded and used. Alternative resources example: Create alternative string resources in Chinese simply by adding a second strings.xml file in a resource subdirectory called /res/values-zh/strings.xml (note the zh qualifier). Provide different logos for different screen densities by providing three versions of myLogo.png: /res/drawable-ldpi/myLogo.png (low-density screens) /res/drawable-mdpi/myLogo.png (medium-density screens) /res/drawable-hdpi/myLogo.png (high-density screens) The application would look much better if the layout was different in portrait versus landscape modes change the layout around, moving controls around, in order to achieve a more pleasant user experience, and provide two layouts: /res/layout-port/main.xml (layout loaded in portrait mode) /res/layout-land/main.xml (layout loaded in landscape mode) Android behavior for alternative resources With these alternative resources in place, the Android platform behaves as follows: If the device language setting is Chinese, the strings in /res/values-zh/ strings.xml are used. In all other cases, the strings in /res/values/strings.xml are used. If the device screen is a low-density screen, the graphic stored in the /res/drawableldpi/myLogo.png resource directory is used. If its a medium-density screen, the mdpi drawable is used, and so on.

If the device is in landscape mode, the layout in the /res/layout-land/main.xml is loaded. If its in portrait mode, the /res/layout-port/main.xml layout is loaded. Text To Speech Android Example Here are some guide line how to work this android application is text to speech. In this application user enter any string and click speech button so that time speech that enter string. Here are some step follows. First of all implements OnInitListener Interface definition of a callback to be invoked indicating the completion of the TextToSpeech engine initialization. Method of OnInitListener is onInit(int status) Called to signal the completion of the TextToSpeech engine initialization. Intent Class is An intent is an abstract description of an operation to be performed. It can be used with startActivity. Example: Intent installIntent = new Intent(); installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); Method onActivityResult(int requestCode, int resultCode, Intent data) See Activitys onActivityResult it ReturnsWhether the request code was handled (in which case subsequent listeners will not be called. Example: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == MY_DATA_CHECK_CODE) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success, create the TTS instance tts = new TextToSpeech(this, this); } else { // missing data, install it Intent installIntent = new Intent(); installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); }

} } TextView : used to display fixed string / labels on the screen. Derived from View and within android.widget.TextView. Standard attributes: width height padding visibility etc. <TextView> : XML way to display text on the screen res/layout/main.xml. To display string 1) Raw text : android:text attribute 2) Reference to a string resource : @string/hello_world. [hello_world is a string defined in res/values/strings.xml file] 1) Raw text : android:text attribute <TextView android:id=@+id/TextView01 android:layout_width=wrap_content android:layout_height=wrap_content android:text=Some sample text here /> 2) Reference to a string resource <TextView android:id=@+id/TextView02 android:layout_width=wrap_content android:layout_height=wrap_content android:text=@string/sample_text /> setContentView() :To display view on the screen. (Must to call) setText() / getText() : To set/get text programmatically for TextView. Width can be controlled by ems rather than pixels (em is used for how much text is viewed rather than font size) maxEms / minEms : maximum & minimum width. Height can be set in terms of lines of text rather than pixels. android:lines : Attribute for how many lines TextView can display. maxLines, minLines : Maximumn & Minimum lines to display <TextView

android:id=@+id/TextView04 android:layout_width=wrap_content android:layout_height=wrap_content android:lines=2 android:ems=12 android:text=@string/autolink_test /> Attribute to refer email add., phone no., web page etc.Creating contextual links in a text android:autoLink Possible values None : Disable all linking Web :linking of URLs Email :linking of mail address to mail client Phone : linking of phone no. to dialer application Map :linking of street add., to map applicaiton All : Enable all type of linking <TextView android:id=@+id/TextView02 android:layout_width=wrap_content android:layout_height=wrap_content android:text=@string/autolink_test android:autoLink=web|email /> linksClickable: Attribute true / false False if dont want to user to click on the highlighted text. EditText : Is derived from TextView. android:hint: Attribute that puts some text in edit box, and goes away when user types in it. android:editable: Attribute if made false user cant edit. setSelection(): Highlight portion of the text selectAll(): Highlight the entire text field getText() & setText(): To read & write text programmatically. Example: <?xml version=1.0 encoding=utf-8?> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical

android:layout_width=fill_parent android:layout_height=fill_parent > <TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello /> <EditText android:layout_width=fill_parent android:layout_height=wrap_content android:id=@+id/EdtTxt android:hint=Enter Any No /> <Button android:layout_width=fill_parent android:layout_height=wrap_content android:id=@+id/btnClick android:text=Click Me /> </LinearLayout> What Is AutoCompleteTextView | MultiAutoCompleteTextView Android AutoComplete feature : To help user with entering commonly used data into forms. Two forms: AutoCompleteTextView control : If the user begins typing a string that matches a word in a developer-provided list, the user can choose to complete the word with just a tap. MultiAutoCompleteTextView control : Allows the user to enter a list of items, each of which has autocomplete functionality, items must be separated in some way by providing a Tokenizer. AutoCompleteTextView Example

final String*+ COLORS = {red, green, orange, blue, purple,black, yellow, cyan, magenta } ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line, COLORS); AutoCompleteTextView text = (AutoCompleteTextView) findViewById (R.id.AutoCompleteTextView01); text.setAdapter(adapter); xml File: <AutoCompleteTextView android:id=@+id/AutoCompleteTextView01 android:layout_width=fill_parent android:layout_height=wrap_content android:completionHint=Pick a color or type your own android:completionThreshold=1 /> MultiAutoCompleteTextView final String*+ COLORS = {red, green, orange, blue, purple,black, yellow, cyan, magenta } ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line, COLORS); MultiAutoCompleteTextView mtext = (MultiAutoCompleteTextView) findViewById(R.id.MultiAutoCompleteTextView01); mtext.setAdapter(adapter); mtext.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()) Simple AutoCompleteTextView Demo in Android AutoCompleteTextView control : If the user begins typing a string that matches a word in a developer-provided list, the user can choose to complete the word with just a tap.

MultiAutoCompleteTextView control : Allows the user to enter a list of items, each of which has autocomplete functionality, items must be separated in some way by providing a Tokenizer. The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key. The list of suggestions is obtained from a data adapter and appears only after a given number of characters defined by the threshold. Now we Start our project AutoCompleteTextViewDemo in API DEMO is 2.2 and Level versions 8so first of all. Open the res/Laout/main.xml <?xml version=1.0 encoding=utf-8?> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/androidandroid:layout_width =fill_parent android:layout_height=fill_parent android:orientation=vertical > <TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello /> <AutoCompleteTextView android:id=@+id/inputText android:layout_width=match_parent android:layout_height=wrap_content android:text=Enter the Text android:completionThreshold=1> <requestFocus /> </AutoCompleteTextView> </LinearLayout>

Open the res/Laout/strings.xml <?xml version=1.0 encoding=utf-8?> <resources><string name=hello>Hello World, AutoCompleteTextViewDemoActivity!</string> <string name=app_name>AutoCompleteTextViewDemo</string><string-array name = Fruits> <item> Apple </item> <item> Banana </item> <item> Grapes </item> <item> Mango Ripe </item> <item> Orange </item> <item> Pineapple </item> <item> Water melon </item> </string-array> </resources> AutoCompleteTextViewDemo/src/com/AutoCompleteTextViewDemo/AutoCompl eteTextViewDemActivity.java package com.theandroid.in;import android.app.Activity;import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class AutoCompleteTextViewDemoActivity extends Activity implements TextWatcher { /** Called when the activity is first created. */ AutoCompleteTextView actv; public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.main); actv= (AutoCompleteTextView)findViewById(R.id.inputText); String fruits[] = getResources().getStringArray(R.array.Fruits); actv.addTextChangedListener(this); actv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,fruits)); } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } What is RadioGroups & RadioButtons In Android Use radio buttons when a user should be allowed to only select one item from a small group of items. Have a text label next to them, set via the text attribute, and they have a state (checked or unchecked). Group RadioButton objects inside a

RadioGroup that handles enforcing their combined states so that only one RadioButton can be checked at a time. Example xml File: <RadioGroup android:id=@+id/RadioGroup01 android:layout_width=wrap_content android:layout_height=wrap_content> <RadioButton android:id=@+id/RadioButton01 android:layout_width=wrap_content android:layout_height=wrap_content android:text=Option 1></RadioButton> <RadioButton android:id=@+id/RadioButton02 android:layout_width=wrap_content android:layout_height=wrap_content android:text=Option 2></RadioButton> </RadioGroup> java code: final RadioGroup group = (RadioGroup)findViewById(R.id.RadioGroup01); final TextView tv = (TextView) findViewById(R.id.TextView01); group.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId != -1) { RadioButton rb = (RadioButton)findViewById(checkedId); if (rb != null) {

tv.setText(You chose: + rb.getText()); } } else { tv.setText(Choose 1); } } }); Clearing Radio Button Selection final Button clear_choice = (Button) findViewById(R.id.Button01); clear_choice.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { RadioGroup group = (RadioGroup)findViewById(R.id.RadioGroup01); if (group != null) { group.clearCheck(); } });

Example of ProgressBar In Android Progress Bar : a shows the completeness of an action. Can be used to show progress of some background action. Displays a bar to the user representing how far the operation has progressed; the application can change the amount of progress (modifying the length of the bar) as it moves forward. There is also a secondary progress displayable on a progress bar

which is useful for displaying intermediate progress, such as the buffer level during a streaming playback progress bar. A progress bar can also be made indeterminate. In indeterminate mode, the progress bar shows a cyclic animation without an indication of progress. This mode is used by applications when the length of the task is unknown. The indeterminate progress bar can be either a spinning wheel or a horizontal bar. Example show the completion of a downloading media file while that file plays, copying files etc. <ProgressBar android:id=@+id/progress_bar android:layout_width=wrap_content android:layout_height=wrap_content /> <ProgressBar android:id=@+id/progress_bar style=?android:attr/progressBarStyleHorizontal android:layout_width=fill_parent android:layout_height=wrap_content android:max=100 /> Style: Default style is medium size circular progress indicator Other two styles are progressBarStyleLarge& progressBarStyleSmall. Setting indicator progress programmatically. Example: mProgress = (ProgressBar) findViewById(R.id.progress_bar); mProgress.setProgress(75); 1)Progress bar on title 2)progressBarStyleHorizontal 3)progressBarStyleSmall 4)progressBarStyleLarge

Benefit of having ProgressBar on TitleBar. This can also make it easy to turn on and off an indeterminate progress indicator without changing the look of the screen. Used to display progress on pages where items need to be loaded before the page can finish drawing. To use the indeterminate indicator on your Activity objects title bar, Request the featureWindow.FEATURE_INDETERMINATE_PROGRESS. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); (Shows circular progress bar) requestWindowFeature(Window.FEATURE_PROGRESS); (Shows Horizontal progress bar) setContentView(R.layout.indicators); setProgressBarIndeterminateVisibility(true); setProgressBarVisibility(true); setProgress(5000); RatingBar In Android Progress bar shows the completeness of an action. Can be used to show progress of some background action. The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar. The smaller RatingBar style ( ratingBarStyleSmall) and the larger indicator-only style (ratingBarStyleIndicator) do not support user interaction and should only be used as indicators. When using a RatingBar that supports user interaction, placing widgets to the left or right of the RatingBar is discouraged. The number of stars set (via setNumStars(int) or in an XML layout) will be shown when the layout width is set to wrap content (if another layout width is set, the results may be unpredictable). Example show the completion of a downloading media file while that file plays, copying files etc. <RatingBar android:id=@+id/ratebar1 android:layout_width=wrap_content

android:layout_height=wrap_content android:numStars=4 android:stepSize=0.25 /> To show a numeric representation of this value to the user. RatingBar rate = (RatingBar) findViewById(R.id.ratebar1); rate.setOnRatingBarChangeListener (new RatingBar.OnRatingBarChangeListener() { public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromTouch) { ((TextView)findViewById(R.id.rating_text)) .setText(Rating: + rating); } });

Simple GridView Demo in Android GridView : A view that shows items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view. Now we Start our project GridViewDemo in API DEMO is 2.2 and Level versions 8 so first of all. The GridView is captured from the layout with findViewById(int). To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a new AdapterView.OnItemClickListener. This anonymous instance defines the onItemClick() callback method to show a Toast that displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task).

Open res/Layout/main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=vertical ><TextView android:id=@+id/text android:layout_width=fill_parent android:layout_height=wrap_content android:background=#ffff00? android:textSize=14pt android:textStyle=bold /> <GridView android:id=@+id/gridView1? android:layout_width=match_parent android:layout_height=wrap_content android:numColumns=2? android:columnWidth=100px android:stretchMode=columnWidth android:gravity=center android:background=#ff0000ff> </GridView> </LinearLayout> GridViewDemo/src/com/GridViewDemoActivity/GridViewDemoActivity.java package com.theandroid.in;import android.app.Activity; import android.os.Bundle;

import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.TextView;public class GridViewDemoActivity extends Activity implements OnItemClickListener { /** Called when the activity is first created. */ TextView textview; String[] stList = {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,saturday}; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textview =(TextView)findViewById(R.id.text); GridView gv = (GridView)findViewById(R.id.gridView1); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stList); gv.setAdapter(adapter); gv.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> arg0, View vi, int position, long id) { // TODO Auto-generated method stub textview.setText(stList[position]); } }

What Is Chronometer In Android ChronoMeter To show time passing instead of incremental progress. Useful if its the user who is taking time doing some task or In a game where some action needs to be timed. XML layout resource definition: <Chronometer android:id=@+id/Chronometer01 android:layout_width=wrap_content android:layout_height=wrap_content android:format=Timer: %s /> Wont show the passage of time until its start() method is called, stop() method is called to stop the timer. setBase() is to count from a particular time in the past instead of from the time its started. Handling the event final Chronometer timer = (Chronometer)findViewById(R.id.Chronometer01); timer.setBase(0); timer.start(); Listen for changes to the Chronometer by implementing the Chronometer.OnChronometerTickListener interface. Passing android.os.SystemClock.elapsedRealtime() in to the setBase() method starts the Chronometer control at 0. timer.setBase(android.os.SystemClock.elapsedRealtime()); Basic code for TabHost Layout in Android tutorial TabHost: There are two ways to create tabbing on the Android platform. Use the TabActivity, which simplifies a screen with tabs. Create your own tabbed screens from scratch. A screen layout with tabs consists of a TabActivityand a TabHost. The TabHost consists of TabSpecs, a nested class of TabHost, which contains the tab information including the tab title and the contents of the tab. Each tab is effectively a container for a View. In this project we need three separate activities for three tab screens. So lets get started by creating a simple project by opening eclipse IDE.

Now we Start our project TabActivityDemo in API DEMO is and Level versions 8 so first of all. There are two ways to create tabbing on the Android platform. Use the TabActivity, which simplifies a screen with tabs. Create your own tabbed screens from scratch. How to use tabhost A screen layout with tabs consists of a TabActivity and a TabHost. The TabHost consists of TabSpecs, a nested class of TabHost, which contains the tab information including the tab title and the contents of the tab. Each tab is effectively a container for a View. How to create TabHost Application Prepare layout file with <TabHost> as parent tag & <TabWidget> as sub tag. Main activity class should extend TabActivity. Create instance of TabHost using getTabHost() method. Use newTabSpec() method to add new tab. Use setContent() method to set the content to that tab, pass intent as arguments. Use addTab() method of TabHost. Create activity for Gallery specify following code: gallery = (Gallery) findViewById(R.id.gallery); // String array holding the values String[] text = new String[] { Hello, Hi, Alloha, Bonjour, Hallo, Hola }; // Array adapter to display our values in the gallery control ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, text); gallery.setAdapter(arr); How To Set TabHost At Bottom In Android

1. 2. 3. 4.

1. 2. 3. 4. 5.

TabHost : Container for a tabbed window view. This object holds two children: a set of tab labels that the user clicks to select a specific tab, and a FrameLayout object that displays the contents of that page. By default TabHost is Top of the screen on the devices. In your vertical LinearLayout, put the FrameLayout above the TabWidget. Set layout_height to wrap_content on both FrameLayout and TabWidget. Set FrameLayouts android:layout_weight=fill_parent . Set TabWidgets android:layout_weight=0 (0 is default, but for emphasis, readability, etc). Main.xml <?xml version=1.0? encoding=utf-8??> <TabHost xmlns:android=http://schemas.android.com/apk/res/android android:id=@android:id/tabhost android:layout_width=fill_parent android:layout_height=fill_parent > <RelativeLayout android:id=@+id/tab_relative_layout android:layout_width=fill_parent android:layout_height=fill_parent > <TabWidget android:id=@android:id/tabs android:layout_width=fill_parent android:layout_height=wrap_content > </TabWidget> <FrameLayout android:id=@android:id/tabcontent android:layout_width=fill_parent android:layout_height=fill_parent android:layout_below=@android:id/tabs> </FrameLayout> </RelativeLayout> </TabHost> Heres the simplest way to get tabs on the Bottom of the screen. In your vertical LinearLayout, put the FrameLayout above the TabWidget Set layout_height to wrap_content on both FrameLayout and TabWidget Set FrameLayouts android:layout_weight=fill_parent Set TabWidgets android:layout_weight=0 (0 is default, but for emphasis, readability, etc) Set TabWidgets android:layout_alignParentBottom=true Main.xml

<?xml version=1.0? encoding=utf-8??> <TabHost xmlns:android=http://schemas.android.com/apk/res/android android:id=@android:id/tabhost android:layout_width=fill_parent android:layout_height=fill_parent > <RelativeLayout android:id=@+id/tab_relative_layout android:layout_width=fill_parent android:layout_height=fill_parent > <TabWidget android:id=@android:id/tabs android:layout_width=fill_parent android:layout_height=wrap_content android:layout_alignParentBottom=true> </TabWidget> <FrameLayout android:id=@android:id/tabcontent android:layout_width=fill_parent android:layout_height=fill_parent android:layout_below=@android:id/tabs> </FrameLayout> </RelativeLayout> </TabHost> Open res/Layout/main.xml <?xml version=1.0? encoding=utf-8??><TabHost xmlns:android=http://schemas.android.com/apk/res/androidandroid:id=@androi d:id/tabhost android:paddingTop=@dimen/tab_space_top android:layout_width=fill_parent android:paddingLeft=@dimen/tab_space_gap android:layout_height=fill_parent android:paddingRight=@dimen/tab_space_gap ><RelativeLayout android:id=@+id/tab_relative_layout

android:layout_width=fill_parent android:layout_height=fill_parent> <TabWidget android:id=@android:id/tabs android:layout_width=fill_parent android:layout_height=wrap_content> </TabWidget><FrameLayout android:id=@android:id/tabcontent android:layout_width=fill_parent android:layout_height=fill_parent android:layout_below=@android:id/tabs> </FrameLayout> </RelativeLayout> </TabHost> Now we need 3 activities for three tabs. So create three activities by right click on your package folder and create classes and name them as Tab1Activity.java, Tab1Activity.java and Tab1Activity.java. Type the following code respectively. TabActivityDemo/src/com/TabActivityDemo/Tab1Activity.java package com.theandroid.in;import com.customs.tabs.R; import android.app.Activity; import android.os.Bundle;public class Tab1Activity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.tab1); } }

TabActivityDemo/src/com/TabActivityDemo/Tab2Activity.java package com.theandroid.in;import com.customs.tabs.R;import android.app.Activity; import android.os.Bundle;public class tab2Activity extends Activity{@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.tab2); } } TabActivityDemo/src/com/TabActivityDemo/Tab3Activity.java package com.theandroid.in;import com.customs.tabs.R;import android.app.Activity; import android.os.Bundle;public class tab3Activity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.tab3); } }

What is DigitalClock | AnalogClock DigitalClock: A is a compact text display of the current time in standard numeric format based on the users settings. It is a TextView, so anything you can do with a TextView you can do with this control, except change its text.

XML layout resource definition for a DigitalClock control: <DigitalClock android:id=@+id/DigitalClock01 android:layout_width=wrap_content android:layout_height=wrap_content /> AnalogClock: A is a dial-based clock with a basic clock face with two hands, one for the minute and one for the hour. It is a TextView, so anything you can do with a TextView you can do with this control, except change its text. XML layout resource definition for a AnalogClock control: <AnalogClock android:id=@+id/AnalogClock01 android:layout_width=wrap_content android:layout_height=wrap_content /> It can show only the current time in the current time zone of the device. Neither of these clock controls accepts a different time or a static time to display. What Is Menu In Android Android phones have the menu button which displays a menu with several items that provide navigation or more functionality or settings to your applications. Android has three types of menus: Options Menu Context Menu Sub menus Menu items can be grouped and each menu item can have submenu items. OptionsMenu: To bring up a menu by pressing the menu key from within the application. Each activity has a single menu. Use options menus in application to bring up help, to navigate, to provide additional controls, or to configure options. The OptionsMenu control can contain icons, submenus, and keyboard shortcuts. To show OptionsMenu when user presses Menu button from the device do: override the implementation of onCreateOptionsMenu() in activity. An options menu is to allow configuration options for a given screen.

OptionsMenu- Example 01 To bring OptionsMenu : public boolean onCreateOptionsMenu( android.view.Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Forms).setIcon(android.R.drawable.ic_menu_edit).setIntent(new Intent(this, FormsActivity.class)); menu.add(Indicators) .setIcon(android.R.drawable.ic_menu_info_details); .setIntent(new Intent(this, IndicatorsActivity.class)) menu.add(Containers) .setIcon(android.R.drawable.ic_menu_view).setIntent(new Intent(this, ContainersActivity.class)); return true; } OptionsMenu- Example 02 Menu menu; @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Item1?); menu.add(Item2?); return true; } }

OptionMenuDemo/src/com/OptionMenuDemo/OptionMenuDemoActivity.java package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast;

public class OptionMenuDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, 0, 0, Item 0); menu.add(0, 1, 1, Item 1); menu.add(0, 2, 2, Item 2); menu.add(0, 3, 3, Item 3); menu.add(0, 4, 4, Item 4); return true; } public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch(item.getItemId()){ case (0): Toast.makeText(getApplicationContext(), Item 0 Selected, Toast.LENGTH_LONG).show(); break; case (1): Toast.makeText(getApplicationContext(), Item 1 Selected, Toast.LENGTH_LONG).show(); break; case (2): Toast.makeText(getApplicationContext(), Item 2 Selected, Toast.LENGTH_LONG).show(); break; case (3): Toast.makeText(getApplicationContext(), Item 3 Selected, Toast.LENGTH_LONG).show(); break; case (4): Toast.makeText(getApplicationContext(), Item 4 Selected, Toast.LENGTH_LONG).show();

break; } return true; } } OptionsMenu- Example 03 public boolean onCreateOptionsMenu(Menu menu) { menu.add(1, 1, 0, Item1?); menu.add(1, 2, 1, Item2?); menu.add(1, 3, 2, Item3?); menu.add(1, 4, 3, Item4?); menu.add(1, 5, 4, Item5?); menu.add(2, 6, 0, Item6?); menu.add(2, 7, 1, Item7?); menu.add(2, 8, 2, Item8?); menu.add(2, 9, 3, Item9?); menu.add(2, 10, 4, Item10?); menu.add(2, 8, 7, Item3?).setNumericShortcut(3'); menu.add(1, 2, 1, DVD).setIcon(R.drawable.dvd); return true; } The menu.add(int GroupID,int ItemID,int Order,String Title) method has the parameters: GroupID: used to group related menu items to apply some configurations on all items of a certain group once at a time. ItemID: an integer to identify the menu item. Order: the sort order or the order ID, controls the order of menu items in a menu. Items with lower order id appear first. There are some constants defined for sort

order for different kinds of menu items Like Menu.CATEGORY_SECONDRY for secondry menu items, Menu.CATEGORY_SYSTEM for system menu items and Menu.CATEGORY_ALTERNATIVE for altenative menu items. Title: the text of the menu item. Grouping Menu Items The actions that can be applied on a group can be: Menu.removeGroup(int GroupID): to remove all menu items belonging to the same group. Menu.setGroupCheckable(int GroupID,Boolean Checakble,Boolean Exclusive): maked a group appear with a check mark beside each item. If the Boolean Exclusive is set to true then the items will appear as if they are in a radiobuttongroup and only one item can be selected at a time. If set to false then they will appear with check boxes beside each item and multiple items can be selected at a time. Menu.setGroupEnabled(int GroupID,Boolean Enabled): sets all items in a group to be enabled/disabled. Menu.setGroupVisible(int GroupID,Boolean Visible): sets all items in a group to be visible/invisible. How Many Types of Dialog In Android Dialog To organize information and react to user-driven events. E.g. an activity might display a dialog informing the user of a problem or ask the user to confirm an action such as deleting a data record. Types of Dialog: Dialog: The basic class for all Dialog types. AlertDialog: A Dialog with one, two, or three Button controls. CharacterPickerDialog: A Dialog for choosing an accented character associated with a base character. DatePickerDialog: A Dialog with a DatePicker control. ProgressDialog: A Dialog with a determinate or indeterminate ProgressBar control. TimePickerDialog: A Dialog with a TimePicker control. Custom Dialogs can also be created with specific layout requirements. Lifecycle of a Dialog: Must be defined within the Activity. May be launched once, or used repeatedly.

Key methods that activity must use to manage dialog: showDialog(): Used to display a Dialog. dismissDialog(): used to stop showing a Dialog. The Dialog is kept around in the Activitys Dialog pool. If the Dialog is shown again using showDialog(), the cached version is displayed once more. removeDialog(): used to remove a Dialog from the Activity objects Dialog pool. The Dialog is no longer kept around for future use. If you call showDialog() again, the Dialog must be re-created. steps to add dialog to an activity : Define a unique identifier for the Dialog within the Activity. Implement the onCreateDialog() method of the Activity to return a Dialog of the appropriate type, when supplied the unique identifier. Implement the onPrepareDialog() method of the Activity to initialize the Dialog as appropriate. Launch the Dialog using the showDialog() method with the unique identifier. Defining a Dialog: Each Dialog has a special identifier (an integer). Pass this identifier when showDialog() method is called. At this point, the onCreateDialog() method is called and must return a Dialog of the appropriate type. onCreateDialog() method may only be called once for initial Dialog creation. Initializing a Dialog: Dialog is often kept around by the Activity in its Dialog pool. To re-initialize a Dialog each time it is shown, instead of just when it is created the first time. Override the onPrepareDialog() method of the Activity. onPrepareDialog() method is called each time the showDialog() method is called, giving the Activity a chance to modify the Dialog before it is shown to the user. Launching a Dialog: Display any Dialog defined within an Activity by calling its showDialog() method and passing it a valid Dialog identifier. Dismissing a Dialog: Most types of dialogs have automatic dismissal circumstances. To force a Dialog to be dismissed, simply call the dismissDialog() method and pass in the Dialog identifier.

Removing dialog from use: Dismissing a Dialog does not destroy it. If the Dialog is shown again, its cached contents are redisplayed. To force an Activity to remove a Dialog from its pool and not use it again call the removeDialog() method, passing in the valid Dialog identifier. Custom Dialog: To create a custom dialog follow the steps: Design a custom layout resource to display in the AlertDialog. Define the custom Dialog identifier in the Activity. Update the Activitys onCreateDialog() method to build and return the appropriate custom AlertDialog.You should use a LayoutInflater to inflate the custom layout resource for the Dialog. Launch the Dialog using the showDialog() method. Simple way to create AlertDialog.Builder AlertDialog : If you would prefer something in the more classic dialog-box style, what you want is an AlertDialog. As with any other modal dialog box, an AlertDialog pops up, grabs the focus, and stays there until closed by the user. You might use this for a critical error, a validation message that cannot be effectively displayed in the base activity UI, or something else where you are sure that the user needs to see the message and needs to see it now. The simplest way to construct an AlertDialog is to use the Builder class. Following in true builder style, Builder offers a series of methods to configure an AlertDialog, each method returning the Builder for easy chaining. At the end, you call show() on the builder to display the dialog box. Now we Start our project ButtonClickActivity in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. setMessage() if you want the body of the dialog to be a simple textual message, from either a supplied String or a supplied string resource ID. setTitle() and setIcon() to configure the text and/or icon to appear in the title bar of the dialog box. setPositiveButton(), setNeutralButton(), and setNegativeButton() to indicate which. Once show() is called, the dialog box will appear and await user input. Open the AlertDialogDemo/res/layout/main.xml

<?xml version=1.0 encoding=utf-8?> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent android:weightSum=1> <TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello /> <Button android:id=@+id/btn android:layout_height=wrap_content android:layout_width=fill_parent android:text=Click Me android:background=#ffffff android:textColor=#ff0000 android:layout_weight=0.05 > </Button> </LinearLayout> AlertDialogDemo/src/com/AlertDialogDemoActivity/AlertDialogDemoActivity.ja va package com.theandroid.in; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; public class AlertDialogDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button)findViewById(R.id.btn); button.setOnClickListener(new Button.OnClickListener(){

@Override public void onClick(View v) { // TODO Auto-generated method stub new AlertDialog.Builder(AlertDialogDemoActivity.this).setTitle(AlertDialog).setMe ssage(Hello!).setPositiveButton(OK, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); }}); } } Simple DatePicker Demo in Android DatePicker : To provide a widget for selecting a date, use the DatePicker widget, which allows the user to select the month, day, and year, in a familiar interface. Finally, note that Android offers versions of these controls as modal windows, such as DatePickerDialog this controls is useful if you want to display the control to the user and force the user to make a selection. The preceding code sets the DatePicker.OnDateChangedListener by a call to the DatePicker.init()method. Now we Start our project DatePickerDemo in API DEMO is 2.2 and Level versions 8 so first of all. <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TextView android:textSize=12pt android:layout_height=wrap_content android:id=@+id/lblTime android:layout_width=wrap_content android:layout_below=@+id/datepick android:layout_alignLeft=@+id/datepick android:text=Date ->

</TextView> <TextView android:textSize=12pt android:layout_height=wrap_content android:text=DD/MM/YYYY android:id=@+id/tvGet android:layout_below=@+id/datepick android:layout_alignRight=@+id/datepick android:layout_width=wrap_content> </TextView> <DatePicker android:id=@+id/datepick android:layout_height=wrap_content android:layout_width=wrap_content> </DatePicker> </LinearLayout> DatePickerDemo/src/com/DatePickerDemoActivity/DatePickerDemoActivity.java package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; import android.widget.TextView; import android.widget.DatePicker.OnDateChangedListener; public class DatePickerDemoActivity extends Activity { /** Called when the activity is first created. */@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final DatePicker date=(DatePicker)findViewById(R.id.datepick); final TextView tvDate=(TextView)findViewById(R.id.tvGet); date.init(date.getYear(), date.getMonth(), date.getDayOfMonth(),new OnDateChangedListener() { public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub String date=Integer.toString(arg3); String month=Integer.toString(arg2);

String year=Integer.toString(arg1); tvDate.setText(month+/+date+/+year); } }); } } Simple TimePicker widget Demo in Android TimePicker : A view for selecting the time of day, in either 24 hour or AM/PM mode. The hour, each minute digit, and AM/PM (if applicable) can be conrolled by vertical spinners. The hour can be entered by keyboard input. Entering in two digit hours can be accomplished by hitting two digits within a timeout of about a second (e.g. 1 then 2 to select 12). The minutes can be entered by entering single digits. Under AM/PM mode, the user can hit a, A, p or P to pick. Now we Start our project TimePickerDemo in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTi meChangedListener) Set the callback that indicates the time has been adjusted by the user. use of onTimeChanged(TimePicker view, int hourOfDay, int minute) method on TimePicker class. Open res/Layout/main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/androidandroid:orientation= vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TimePicker android:id=@+id/timePicker android:layout_height=wrap_content android:layout_width=wrap_content android:layout_gravity=center> </TimePicker> </LinearLayout>

TimePickerDemo/src/com/TimePickerDemoActivity/TimePickerDemoActivity.jav a package com.timepicker;import android.app.Activity; import android.os.Bundle; import android.widget.*; import android.widget.TimePicker.*; public class TimePickerDemoActivity extends Activity {/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TimePicker tp=(TimePicker)findViewById(R.id.timePicker); tp.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Toast.makeText(getApplicationContext(), Time is=+hourOfDay+:+minute, Toast.LENGTH_SHORT).show(); } }); } } How To Apply Theme In Android Theme: Is a collection of one or more styles (as defined in the resources) but instead of applying the style to a specific control, the style is applied to all View objects within a specified Activity.

Applying a theme to a set of View objects all at once simplifies making the user interface look consistent. An Android theme is essentially a style that is applied to an entire screen. You can specify the theme programmatically by calling the Activity method setTheme() with the style resource identifier. Specify the theme programmatically by calling the Activity method setTheme() with the style resource identifier. Styles and attributes defined in the layout files explicitly override those in the theme. <style name=right> <item name=android:gravity>right</item> </style> Apply this as a theme to the whole screen, which causes any view displayed within that Activity to have its gravity attribute to be right-justified. Applying this theme : setTheme(R.style.right); You can also apply themes to specific Activity instances by specifying them as an attribute within the <activity> element in the AndroidManifest.xml file, as follows: <activity android:name=.myactivityname android:label=@string/app_name android:theme=@style/myAppIsStyling> Multiple themes can be applied to a screen. setTheme(R.style.right); setTheme(R.style.green_glow); Apply all themes before calling the method setContentView() or the inflate() method so that the themes attributes can take effect. Android comes with a number of built-in themes that can be a good starting point.These include such themes as Theme_Black, Theme_Light, and Theme_NoTitleBar_Fullscreen, as defined in the android.R.style class. How To Handling Events In Android Listening for Touch Mode ChangesAndroid screen can be in one of two states. When touch mode is on, typically only objects such as EditText get focus when selected. Other objects, because they can be selected directly by the user tapping on the screen, wont take focus but instead trigger their action.

When not in touch mode, however, the user can change focus between even more object types. In this case, the user uses the arrow keys, trackball, or wheel to navigate between items and select them with the Enter or select keys. Knowing what mode the screen is in is useful if you want to handle certain events. Application relies on the focus or lack of focus on a particular control, your application might need to know if the phone is in touch mode because the focus behavior is likely different. Example View all = findViewById(R.id.events_screen);ViewTreeObserver vto = all.getViewTreeObserver(); vto.addOnTouchModeChangeListener. new ViewTreeObserver.OnTouchModeChangeListener() { public void onTouchModeChanged( boolean isInTouchMode) { events.setText(Touch mode: + isInTouchMode); } }); Listening for events on the entire screenApplication can watch for changes to the touch mode state for the screen using the ViewTreeObserver class. The ViewTreeObserver also provides three other events that can be watched for on a full screen or an entire View and all of its children. PreDraw: Get notified before the View and its children are drawn to perform some actions before the screen is drawn Do this by calling the method addOnPreDrawListener() with an implementation of theViewTreeObserver.OnPreDrawListener class interface. GlobalLayout: Get notified when the layout of the View and its children might change, including visibility changes. Application can find out when the layout or visibility of a View has changed. It is useful if application is dynamically changing the display contents of a view and to check to see if a View still fits on the screen, application needs to provide an implementation of the

ViewTreeObserver.OnGlobalLayoutListener class interface to the addGlobalLayoutListener()method of the ViewTreeObserver object. GlobalFocusChange: Get notified when the focus within the View and its children changes Application can register to find out when the focus changes between a View control and any of its child View controls. Application might want to do this to monitor how a user moves about on the screen, When in touch mode, though, there might be fewer focus changes than when the touch mode is not set. In this case, application needs to provide an implementation of the ViewTreeObserver. OnGlobalFocusChangeListener class interface to the addGlobalFocusChangeListener() method. vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() { public void onGlobalFocusChanged( View oldFocus, View newFocus) { if (oldFocus != null && newFocus != null) { events.setText(Focus nfrom: + oldFocus.toString() + nto: + newFocus.toString()); }} }); Listening for Long Clicks Context menu can be added to a View that is activated when the user performs a long click on that view. A long click is typically when a user presses on the touch screen and holds his finger there until an action is performed. A long press event can also be triggered if the user navigates there with a nontouch method, such as via a keyboard or trackball, and then holds the Enter or Select key for a while.

This action is also often called a press-and hold action. If youve already added a context menu to a View, you might not want to listen for the long-click event as other actions or side effects might confuse the user or even prevent the context menu from showing. Application can listen to the long-click event on any View. Button long_press = (Button)findViewById(R.id.long_press); long_press.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { events.setText(Long click: + v.toString()); return true; } }); Listening for Focus Changes All View objects, though, can also trigger a call to listeners when their particular focus state changes. Provide an implementation of the View.OnFocusChangeListener class to thesetOnFocusChangeListener() method. TextView focus = (TextView)findViewById(R.id.text_focus_change); focus.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (mSaveText != null) { ((TextView)v).setText(mSaveText); } }else { mSaveText = ((TextView)v).getText().toString(); ((TextView)v).setText();

}} FrameLayout In Android FrameLayout: This view is designed to display a stack of child View items. Add multiple views to this layout, but each View is drawn from the top-left corner of the layout. Find the layout attributes available for FrameLayout child View objects in android.Control .FrameLayout.LayoutParams. Frame layouts are one of the simplest and most efficient types of layouts used by Android developers to organize view controls. They are used less often than some other layouts, simply because they are generally used to display only one view, or views which overlap. The frame layout is often used as a container layout, as it generally only has a single child view Important FrameLayout View Attributes. Attribute Name Applies Description To android:measureAll- Parent Restrict size of Children view layoutto all child views orjust the child views setto VISIBLE (and notthose set toINVISIBLE). android:layout_gravityChild A gravity constant view thatdescribes how to placethe child View withinthe parent. Value True or false.

android:foreground android:foregroundGravity

Parent view Parent view

Drawable to draw over the content. Gravity of One or more constants foregrounddrawable. separated by |. The constants available are top, bottom, left,

One or more constants separated by |. The constants available are top, bottom, left, right, center_vertical, fill_vertical, center_horizontal,fill_horizonta l, center,and fill. Drawable resource.

right, center_vertical, fill_vertical,center_horizontal, fill_horizontal, center, and fill. Example: <FrameLayout xmlns:android= http://schemas.android.com/apk/res/android android:id=@+id/FrameLayout01 android:layout_width=wrap_content android:layout_height=wrap_content android:layout_gravity=center> <ImageView android:id=@+id/ImageView01 android:layout_width=wrap_content android:layout_height=wrap_content android:src=@drawable/green_rect android:minHeight=200px android:minWidth=200px /> <ImageView android:id=@+id/ImageView02 android:layout_width=wrap_content android:layout_height=wrap_content android:src=@drawable/red_oval android:minHeight=100px android:minWidth=100px android:layout_gravity=center /> </FrameLayout>

LinearLayout In Android Android lover friends over previous article android tutorials frameLayout and we can discuss. LinearLayout view organizes its child View objects in a single row, or column, depending on whether its orientation attribute is set to horizontal or vertical. Find the layout attributes available for LinearLayout child View objects in android.control .LinearLayout.LayoutParams. Important LinearLayout View Attributes Attribute Name android:orientation Applies To Parent view Description Value

Layout is a single Horizontal or vertical. row(horizontal) or singlecolumn (vertical). Gravity of child One or more constants viewswithin separated by |. The constants layout. available are top,bottom, left, right, center_vertical, fill_vertical,center_horizontal, fill_horizontal, center, and fill. The gravity for a specificchild view. Used forpositioning of views. One or more constants separated by |. The constants available are top,bottom, left, right, center_vertical, fill_vertical,center_horizontal, fill_horizontal, center, and fill.

android:gravity

Parent view

android:layout_gravity Child view

android:layout_weight

Child view

The weight for a The sum of values across all specificchild childviews in a parent view

view. Used toprovide ratio of screenspace used within theparent control.

must equal 1.For example, one child control mighthave a value of .3 and another have a value of .7.

Example of LinearLayout in horizontally Now open your main.xml under res -layout folder and type the following code. <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=horizontal > <Button android:id=@+id/button1? android:layout_width=wrap_content android:layout_height=wrap_content android:text=One /> <Button android:id=@+id/button2? android:layout_width=wrap_content android:layout_height=wrap_content android:text=Two /> <Button android:id=@+id/button3? android:layout_width=wrap_content android:layout_height=wrap_content android:text=Three

android:layout_weight=1?/> <Button android:id=@+id/button3? android:layout_width=wrap_content android:layout_height=wrap_content android:text=Four android:layout_weight=1?/> <Button android:id=@+id/button3? android:layout_width=wrap_content android:layout_height=wrap_content android:text=Five android:layout_weight=1?/> </LinearLayout> RelativeLayout This view enables you to specify where the child view controls are in relation to each other. For instance, you can set a child View to be positioned above or below or to the left of or to the right of another View, referred to by its unique identifier. Child views can be also aligned in relative to one another or the parent layout edges. Find the layout attributes available for RelativeLayout child View objects in android.control .RelativeLayout.LayoutParams. Important RelativeLayout View Attributes Attribute Name android:gravity Applies Description To Parent view Value

Gravity of child One or more views constantsseparated by |.

withinlayout.

Theconstants availableare top, bottom,left, right, center_vertical,fill_vertical, center_horizontal,fill_horizo ntal, center, and fill.

android:layout_centerInParent Child view

Centers child True or false. view horizontallyand vertically withinparent view. Centers child True or false. view horizontallywithi n parent view. Centers child view vertically within parent view. Aligns child view with topedge of parent view. True or false.

android:layout_centerHorizont Child al view

android:Layout_centerVertical Child view

android:Layout_alignParentTo Child p view

True or false.

android:Layout_alignParentB Child ottom view

Aligns child True or false. view with bottom edge of parent view. Aligns child view with leftedge of parent view. Aligns child view with rightedge of parent view. True or false.

android:Layout_alignParentLe Child ft view

android:layout_alignParentRig Child ht view

True or false.

android:layout_alignRight

Child view

Aligns child view with rightedge of another child view,specified by ID. Aligns child view with leftedge of another child view,specified by ID. Aligns child view with topedge of another child view,specified by ID.

A view ID; for example,@id/Button1

android:layout_alignLeft

Child view

A view ID; for example,@id/Button1

android:layout_alignTop

Child view

A view ID; for example,@id/Button1

android:layout_ alignBottom Child view

Aligns child A view ID; for view with example,@id/Button1 bottom edge of another child view, specified by ID. Positions bottom A view ID; for edge ofchild example,@id/Button1 view above anotherchild view, specified by ID. Positions top A view ID; for edge of example,@id/Button1 childview below another childview, specified by ID.

android:Layout_Above

Child view

android:layout_ below

Child view

android:Layout_toLeftOf

Child view

Positions right A view ID; for edge of child example,@id/Button1 view to the left of another child view, specified by ID. Positions left A view ID; for edge of example,@id/Button1 childview to the right of anotherchild view, specified by ID.

android:Layout_toRightOf

Child view

Example of RelativeLayout in horizontally Now open your main.xml under res -layout folder and type the following code. <RelativeLayout xmlns:android= http://schemas.android.com/apk/res/androidandroid:id=@+id/RelativeLayout01 android:layout_height=fill_parent android:layout_width=fill_parent> <Button android:id=@+id/ButtonCenter android:text=Center android:layout_width=wrap_content android:layout_height=wrap_content android:layout_centerInParent=true /> <ImageView android:id=@+id/ImageView01 android:layout_width=wrap_content

android:layout_height=wrap_content android:layout_above=@id/ButtonCenter android:layout_centerHorizontal=true android:src=@drawable/arrow /> </RelativeLayout> TableLayout In Android This view organizes children into rows. Add individual View objects within each row of the table using a TableRow layout View (which is basically a horizontally oriented LinearLayout) for each row of the table. Each column of the TableRow can contain one View (or layout with child View objects). Place View items added to a TableRow in columns in the order they are added. Specify the column number (zero-based) to skip columns as necessary (the bottom row); otherwise, the View object is put in the next column to the right. Columns scale to the size of the largest View of that column. Find the layout attributes available for TableLayout child View objects inandroid.control.TableLayout.LayoutParams. Important TableLayout View Attributes Attribute Name android:collapseColumns Applies To TableLayout Description Value

A commaString or string delimitedlist of resource.For column example, 0,1,3,5 indicesto collapse (0based) A commadelimitedlist of column indicesto shrink String or string resource. Use * for all columns. For example,

android:shrinkColumns

TableLayout

(0-based) andriod:stretchColumns TableLayout A commadelimitedlist of column indicesto stretch (0-based)

0,1,3,5 String or string resource.Use * for all columns.For example, 0,1,3,5

android:layout_column

TableRowchild view

Index of column Integer or integer thischild view resource.For should example, 1 bedisplayed in (0-based) Number of columnsthis child view shouldspan across Integer or integer resourcegreater than orequal to 1.For example, 3

android:layout_span

TableRowchild view

Example of TableLayout and Now open your main.xml under res -> layout folder and type the following code. <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TableLayout android:layout_height=wrap_content android:id=@+id/tableLayout1? android:layout_width=match_parent> <TableRow android:layout_width=match_parent

android:layout_height=wrap_content android:addStatesFromChildren=true android:id=@+id/tableRow1?> <TextView android:id=@+id/txtUname android:layout_height=wrap_content android:layout_width=wrap_content android:text=User Name:> </TextView> <EditText android:width=350px android:id=@+id/edtUname android:layout_height=wrap_content android:layout_width=match_parent> </EditText> </TableRow> <TableRow android:layout_width=match_parent android:layout_height=wrap_content android:addStatesFromChildren=true android:id=@+id/tableRow1?> <TextView android:id=@+id/txtPwd android:layout_height=wrap_content android:layout_width=wrap_content android:text=Password:>

</TextView> <EditText android:inputType=textPassword android:id=@+id/edtPwd android:layout_width=match_parent android:layout_height=wrap_content> </EditText> </TableRow> </TableLayout> <Button android:layout_height=wrap_content android:text=Login android:layout_width=wrap_content android:id=@+id/btnLogin android:layout_gravity=center> </Button> </LinearLayout> What Is Gradient In Android You can create a gradient of colors using one of the gradient subclasses. The different gradient classes including LinearGradient, RadialGradient, and SweepGradient, are available under the superclass android.graphics.Shader. All gradients need at least two colorsa start color and an end colorbut might contain any number of colors in an array. Paint Gradient The different types of gradients are differentiated by the direction in which the gradient flows. Gradients can be set to mirror and repeat as necessary. You can set the Paint gradient using the setShader() method.

Gradient : Linear Gradient Working with Linear Gradients A linear gradient is one that changes colors along a single straight line. You can achieve this by creating a LinearGradient and setting the Paint method setShader() before drawing on a Canvas, as: Example Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); LinearGradient linGrad = new LinearGradient(0, 0, 25, 25, Color.RED, Color.BLACK, Shader.TileMode.MIRROR); circlePaint.setShader(linGrad); canvas.drawCircle(100, 100, 100, circlePaint); Gradient : Radial Gradient Working with Radial Gradients A radial gradient is one that changes colors starting at a single point and radiating outward in a circle. You can achieve this by creating a RadialGradient and setting the Paint method setShader() before drawing on a Canvas, as : Example Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); RadialGradient radGrad = new RadialGradient(250, 175, 50, Color.GREEN, Color.BLACK, Shader.TileMode.MIRROR); circlePaint.setShader(radGrad); canvas.drawCircle(250, 175, 50, circlePaint); Gradient : Sweep Gradient Working with Sweep Gradients A sweep gradient is one that changes colors using slices of a pie, this type of gradient is often used for a color chooser. You can achieve this by creating a SweepGradient and setting the Paint method setShader() before drawing on a Canvas, as: Example

Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); SweepGradient sweepGrad = new SweepGradient(canvas.getWidth()-175, canvas.getHeight()-175, new int[] { Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA }, null); circlePaint.setShader(sweepGrad); canvas.drawCircle(canvas.getWidth()-175,canvas.getHeight()-175, 100, circlePaint) How To Read Message In Android I am creating a android application in that application i want to check the new incoming message. A new message is received means i want to read the message in android. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name asReadMessagesActivity. Project name: ReadMessage Build Target: Android 2.2 Application name: Read Contacts Package name: com.android.ReadMessage Min SDK Version: 8 Now open your main.xml under res -> layout folder and type the following code. <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TextView

android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello android:textSize=20dip /> </LinearLayout> Now we are create activities by right click on your package folder and create classes and name them as ReadMessages Activity .java. Type the following code respectively. Right Click on package folder -> New -> Class ReadMessagesActivity.java package com.android.ReadMessages; import android.app.Activity; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.widget.TextView; public class ReadMessagesActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = new TextView(this); Uri uriSMS = Uri.parse(content://sms); Cursor c = getContentResolver().query(uriSMS, null, null, null,null);

String sms = ; while (c.moveToNext()) { sms += From : + c.getString(2) + : + c.getString(11)+n; } view.setText(sms); view.setBackgroundColor(Color.RED); view.setTextColor(Color.YELLOW); view.setTextSize(20); setContentView(view); } } How To Create Frame By Frame Animation The developer must provide all graphics frames of the animation. What is Frame-by-Frame Animation? Think of frame-by-frame animation as a digital flipbook in which a series of similar images display on the screen in a sequence, each subtly different from the last. When you display these images quickly, they give the illusion of movement. This technique is called frame-by-frame animation and is often used on the Web in the form of animated GIF images. The smoothness of the animation is controlled by providing an adequate number of frames and choosing the appropriate speed on which to swap them. How to create frame by frame animation

Images with minor differences are rotated fast to feel as animation. Best used for complicated graphics transformations that are not easily implemented programmatically.

Create instance of BitmapDrawable and get resources from resources folder (All bmp / jpg files) Create instance of AnimationDrawable and use addFrame() method with 2 argument, where 1st arg. Is BitmapDrawable instance & 2nd arg. Is duration. Set AnimationDrawable object as backround to imageview using setBackgroundDrawable()method. Start the animation using start() method of AnimationDrawable. This android application Frame-by-Frame implement frame animation and animate images. When click on Anim button and then animation start in three images. Example ImageView img = (ImageView)findViewById(R.id.ImageView1);BitmapDrawable frame1 = (BitmapDrawable)getResources().getDrawable(R.drawable.f1); BitmapDrawable frame2 = (BitmapDrawable)getResources(). getDrawable(R.drawable.f2); BitmapDrawable frame3 = (BitmapDrawable)getResources(). getDrawable(R.drawable.f3); int reasonableDuration = 250; AnimationDrawable mAnimation = new AnimationDrawable(); mAnimation.addFrame(frame1, reasonableDuration); mAnimation.addFrame(frame2, reasonableDuration); mAnimation.addFrame(frame3, reasonableDuration); img.setBackgroundDrawable(mAnimation); mAnimation.setOneShot(false); mAnimation.start(); mAnimation.stop(); How To Make a Phone Call Number In Android Android application which allows user to enter any number and when user clicks on dial button, phone call should be made to that number. So lets get started by creating a simple project by opening eclipse IDE.

Create a new project File -> New -> Android Project and give activity name as Callnumber Project name: CallNumber Build Target: Android 2.2 Application name: Read Contacts Package name: com. com.android.test Min SDK Version: 8 Final Out Put : Call Number: Write permission tag in manifest file to place a call. android.permission.CALL_PHONE. Create instance of URI, provide phone no. to dial as argument of parse. Create instance of Intent pass arguments Intent action (Inte nt.ACTION_DIAL : launches dialer / Intent.ACTION_CALL places call directly). Uri instance. Example : Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse(tel:+edt.getText())); startActivity(intent); Frame By Frame Animation Example In Android Frame-by-frame Animation Images with minor differences are rotated fast to feel as animation. Best used for complicated graphics transformations that are not easily implemented programmatically. Create instance of BitmapDrawable and get resources from resources folder (All bmp / jpg files) Create instance of AnimationDrawable and use addFrame() method with 2 argument, where 1st arg. Is BitmapDrawable instance & 2nd arg. Is duration. Set AnimationDrawable object as backround to imageview using setBackgroundDrawable()method. Start the animation using start() method of AnimationDrawable. This android application Frame-by-Frame implement frame animation and animate images. When click on Anim button and then animation start in three images. Final Out Put : Button btnStart = (Button) findViewById(R.id.btnStart);

final ImageView imgView = (ImageView)findViewById(R.id.img); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub startAnimation(); } class Starter implements Runnable { public void run() { anim.start(); } } private void startAnimation() { // TODO Auto-generated method stub anim =new AnimationDrawable(); anim.addFrame(getResources().getDrawable(R.drawable.greenstar), 200); anim.addFrame(getResources().getDrawable(R.drawable.redstar), 200); anim.addFrame(getResources().getDrawable(R.drawable.yellowstar), 200); anim.setOneShot(true); ImageView imageView = (ImageView) findViewById(R.id.img); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80, 90); params.alignWithParent = true; params.addRule(RelativeLayout.CENTER_IN_PARENT);

imageView.setLayoutParams(params); imageView.setImageDrawable(anim); imageView.post(new Starter()); } }); imgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); Example of How To Send And Receive Message In Android Android application that sends text message provided by user to given no. I am creating a android application in that application i want to check the new incoming message and Sending SMS is one of the basic features every phone has. In this tutorial well create a SMS Sending Application for Android. You application can also Intercept any incoming SMS and perform task based on predefined rules, well use Broadcast receiver for the listening purpose. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name as ReadMessagesActivity. Project name: SendandReceiveMessage Build Target: Android 2.2 Application name: SendandReceiveMessage Package name: com.android.ReadMessage Min SDK Version: 8 Sending Message: Create SmsManager instance using getDefault() method.

Use sendTextMessage() method SmsManager with five arguments where 1st arg. Is the phone no., 3rd arg. Is the text message to send. Take permission using <uses-permission> android.permission.SEND_SMS.tag, android:name attribute, value private void sendSMS(String phoneNumber, String message) { String SENT = SMS_SENT; String DELIVERED = SMS_DELIVERED; PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); //when the SMS has been sent registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), SMS sent, Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), Generic failure, Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), No service, Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), Null PDU, Toast.LENGTH_SHORT).show();

break; case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), Radio off, Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(SENT)); Receive Message: public void onReceive(Context context, Intent intent) { //get the SMS message passed in Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ; if (bundle != null) { //retrieve the SMS message received Object[] pdus = (Object[]) bundle.get(pdus); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += SMS from + msgs[i].getOriginatingAddress(); str += :; str += msgs[i].getMessageBody().toString(); str += n;

} //display the new SMS message Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } } How To Draw Line On The Screen As User Drag His Finger In Android Android application to draw line on the screen as user drag his finger. So lets get started by creating a simple project by opening eclipse IDE. Project name: Touch Event Build Target: Android 2.2 Application name: Read Contacts Package name: package com.touchevent Min SDK Version: 8 Paint: The Paint class holds the style and color information about how to draw geometries, text and bitmaps. Exmaple: private Paint paint = new Paint(); private Path path = new Path(); public ExploreTouchEvent(Context context, AttributeSet attrs) { super(context, attrs); paint.setAntiAlias(true); paint.setStrokeWidth(6f); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeJoin(Paint.Join.ROUND); } onDraw() Method: If you set a background drawable for a View, then the View will draw it for you before calling back to its onDraw() method. Exmaple: protected void onDraw(Canvas canvas) { canvas.drawColor(Color.BLUE); canvas.drawPath(path, paint); }

onTouchEvent Method: public boolean onTouchEvent (MotionEvent event). Implement this method to handle touch screen motion events. Parameters event The motion event. Returns True if the event was handled, false otherwise. Exmaple: public boolean onTouchEvent(MotionEvent event) { float eventX = event.getX(); float eventY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: path.moveTo(eventX, eventY); return true; case MotionEvent.ACTION_MOVE: path.lineTo(eventX, eventY); break; case MotionEvent.ACTION_UP: // nothing to do break; default: return false; } Tweened Animation In Android Only a single graphic is needed, upon which transforms can be programmatically applied. With tweened animation, you can provide a single Drawable resourceit is a Bitmap graphic, a ShapeDrawable, a TextView or any other type of View

objectand the intermediate frames of the animation are rendered by the system. Developer can provide single drawable resource which may be (Bitmap graphics, ShapeDrawable or any other view.) Tweened animation can be define both programmatically and as xml resource. Programmatically Different transformation available in android.view.animation package, for rotation animation use RotateAnimation class with appropriate arguments, use setDuration() method of otateAnimation class to define duration of animation. XML Way Define animation as resource in /res/anim/spin.xml and <set> is a parent tag, <rotate> / <scale> etc. can be sub tag for various transformation, use android:duration attribute to define duration of animation. Android provides tweening support for several common image transformations, including alpha, rotate, scale, and translate animations. Defining Tweened Animations as XML Resources <?xml version=1.0 encoding=utf-8 ?> <set xmlns:android= http://schemas.android.com/apk/res/android android:shareInterpolator=false> <rotate android:fromDegrees=0 android:toDegrees=360 android:pivotX=50% android:pivotY=50% android:duration=5000 /> </set> Defining Tweened Animations Programmatically The different types of transformations are available as classes within the android.view .animation package. RotateAnimation rotate = new RotateAnimation( 0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); rotate.setDuration(5000);

Defining Simultaneous and Sequential Tweened Animations Animation transformations can happen simultaneously or sequentially when you set the startOffset and duration properties, which control when and for how long an animation takes to complete. Loading Animations ImageView iView = (ImageView)findViewById(R.id.ImageView1); iView.setImageResource(R.drawable.green_rect); Animation an = AnimationUtils.loadAnimation(this, R.anim.grow); iView.startAnimation(an); Example: Button buttonRotateCenter = (Button)findViewById(R.id.rotatecenter); Button buttonRotateCorner = (Button)findViewById(R.id.rotatecorner); final ImageView floatingImage = (ImageView)findViewById(R.id.floatingimage); final Animation animationRotateCenter = AnimationUtils.loadAnimation(this, R.anim.rotate_center); buttonRotateCenter.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub floatingImage.startAnimation(animationRotateCenter); }}); final Animation animationRotateCorner = AnimationUtils.loadAnimation(this, R.anim.rotate_corner); buttonRotateCorner.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub floatingImage.startAnimation(animationRotateCorner); }}); Four Different Tweening Transformations: Transparency changes (Alpha) Rotations (Rotate)

Scaling (Scale) Movement (Translate)

Basic Animation Demo like alpha, rotate, translate and scale In Android We have create an application that will have spinner with list of animation names. On selecting animation name like alpha, rotate translate and scale that animation should affect on the images displayed below. AplhaAnimation : An animation that controls the alpha level of an object. Useful for fading things in and out. This animation ends up changing the alpha property of a Transformation. RotateAnimation : An animation that controls the rotation of an object. This rotation takes place int the X-Y plane. You can specify the point to use for the center of the rotation, where (0,0) is the top left point. If not specified, (0,0) is the default rotation point. TranslateAnimation : An animation that controls the position of an object. See the full package description for details and sample code. ScaleAnimation : An animation that controls the scale of an object. You can specify the point to use for the center of scaling. Open res/Layout/main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <Spinner android:layout_width=match_parent android:id=@+id/spinner1? android:layout_height=wrap_content android:entries=@array/animation> </Spinner> <ImageView android:id=@+id/imageView1? android:layout_width=wrap_content android:src=@drawable/icon android:layout_height=wrap_content> </ImageView> </LinearLayout> Open res/values/strings.xml

<?xml version=1.0? encoding=utf-8??><resources> <string name=hello>Hello World, Prog_10Activity!</string> <string name=app_name>Prog_10</string> <string-array name=animation> <item>Alpha</item> <item>Rotate</item> <item>Translate</item> <item>Scale</item> </string-array> </resources> Now we need 3 xml layouts for the AnimationDemo. So create One anim folder under res resource name them as alpha.xml, rotate.xml, translate.xml and scale.xml and type the following code in respective files. open/res/anim/alpha.xml <?xml version=1.0? encoding=utf-8??><set xmlns:android=http://schemas.android.com/apk/res/android> <alpha android:fromAlpha=0.0? android:toAlpha=1.0? android:duration=5000? android:repeatMode=reverse android:repeatCount=infinite /> </set> open/res/anim/rotation.xml <?xml version=1.0? encoding=utf-8??> <set xmlns:android=http://schemas.android.com/apk/res/android> <rotate android:fromDegrees=0? android:toDegrees=360? android:pivotX=50% android:pivotY=50% android:duration=5000? android:repeatMode=reverse android:repeatCount=infinite/> </set> open/res/anim/translate.xml <?xml version=1.0? encoding=utf-8??><set xmlns:android=http://schemas.android.com/apk/res/android>

<translate android:fromXDelta=0? android:toXDelta=200? android:fromYDelta=0? android:toYDelta=200? android:duration=5000? android:repeatMode=reverse android:repeatCount=infinite/> </set> open/res/anim/scale.xml <?xml version=1.0? encoding=utf-8??><set xmlns:android=http://schemas.android.com/apk/res/android> <scale android:fromXScale=0? android:toXScale=1? android:fromYScale=0? android:toYScale=1? android:pivotX=50% android:pivotY=50% android:duration=5000? android:repeatMode=reverse android:repeatCount=infinite/> </set> Now open AnimationDemo/src/com/AnimationDemoActivity/AnimationDemoActivity.java package com.theandroid.in;import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; public class AnimationDemo extends Activity implements OnItemSelectedListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Spinner sp = (Spinner) findViewById(R.id.spinner1); sp.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub ImageView img = (ImageView)findViewById(R.id.imageView1); if(arg3==0) { Animation an = AnimationUtils.loadAnimation(this, R.anim.alpha); img.startAnimation(an); } if(arg3==1) { Animation an = AnimationUtils.loadAnimation(this, R.anim.rotation); img.startAnimation(an); } if(arg3==2) { Animation an = AnimationUtils.loadAnimation(this, R.anim.translate); img.startAnimation(an); } if(arg3==3) { Animation an = AnimationUtils.loadAnimation(this, R.anim.scale); img.startAnimation(an); } } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } } Working with Alpha Transparency Transformations: Transparency is controlled using Alpha transformations. Alpha transformations can be used to fade objects in and out of view or to layer them on the screen. Alpha values range from 0.0 (fully transparent or invisible) to 1.0 (fully opaque or visible).

Alpha animations involve a starting transparency (fromAlpha) and an ending transparency (toAlpha). A transparency-change animation, taking five seconds to fade in from fully transparent to fully opaque: <alpha android:fromAlpha=0.0 android:toAlpha=1.0 android:duration=5000> </alpha> Programmatically, you can create this same animation using the AlphaAnimation class within the android.view.animation package. Working with Rotating Transformations: You can use rotation operations to spin objects clockwise or counterclockwise around a pivot point within the objects boundaries. Rotations are defined in terms of degrees. For example, you might want an object to make one complete clockwise rotation. set the fromDegrees property to 0 and the toDegrees property to 360. To rotate the object counterclockwise instead set the toDegrees property to -360. By default, the object pivots around the (0,0) coordinate, or the top-left corner of the object. This is great for rotations such as those of a clocks hands. To pivot from the center of the object; set the pivot point, which can be a fixed coordinate or a percentage. Defines a rotation animation, taking five seconds to make one full clockwise rotation, pivoting from the center of the object: <rotate android:fromDegrees=0 android:toDegrees=360 android:pivotX=50% android:pivotY=50% android:duration=5000 /> Programmatically, you can create this same animation using the RotateAnimation class within the android.view.animation package. Working with Scaling Transformations Scaling operations to stretch objects vertically and horizontally. Scaling operations are defined as relative scales. scale value of 1.0 as 100 percent, or fullsize.

To scale to half-size, or 50 percent, set the target scale value of 0.5. Scale horizontally and vertically on different scales or on the same scale. You need to set four values for proper scaling: starting scale(fromXScale, fromYScale) and target scale (toXScale, toYScale). Again, you can use a pivot point to stretch your object from a specific (x,y) coordinate such as the center or another coordinate. The following XML resource file excerpt defines a scaling animation, taking five seconds to double an objects size, pivoting from the center of the object: <scale android:pivotX=50% android:pivotY=50% android:fromXScale=1.0 android:fromYScale=1.0 android:toXScale=2.0 android:toYScale=2.0 android:duration=5000 /> Programmatically, you can create this same animation using the ScaleAnimation class within the android.view.animation package. Working with Moving Transformations You can move objects around using translate operations. Translate operations move an object from one position on the (x,y) coordinate to another coordinate. To perform a translate operation, you must specify the change, or delta, in the objects coordinates. You can set four values for translations: starting position (fromXDelta, fromYDelta) and relative target location (toXDelta, toYDelta). The following XML resource file excerpt defines a translate animation, taking 5 seconds to move an object up (negative) by 100 on the y-axis. Set the fillAfter property to be true, so the object doesnt jump back to its starting position when the animation finishes: <translate android:toYDelta=-100 android:fillAfter=true android:duration=2500 /> Programmatically, you can create this same animation using the TranslateAnimation class within the android.view.animation package. Working with Different Interpolators The animation interpolator determines the rate at which a transformation happens in time :

AccelerateDecelerateInterpolator: Animation starts slowly, speeds up, and ends slowly AccelerateInterpolator: Animation starts slowly and then accelerates AnticipateInterpolator: Animation starts backward, and then flings forward AnticipateOvershootInterpolator: Animation starts backward, flings forward, overshoots its destination, and then settles at the destination BounceInterpolator: Animation bounces into place at its destination CycleInterpolator: Animation is repeated a certain number of times smoothly transitioning from one cycle to the next DecelerateInterpolator: Animation begins quickly, and then decelerates LinearInterpolator: Animation speed is constant throughout OvershootInterpolator: Animation overshoots its destination, and then settles at the destination. Specify the interpolator used by an animation programmatically using the setInterpolator() method or in the animation XML resource using the android:interpolator attribute. What is Application Preferences In Android Many applications need a lightweight data storage mechanism called shared preferences Shared preferences are used for storing application state, simple user information, configuration options, and other such information. Android provides a simple preferences system for Storing primitive application data at the Activity level Preferences shared across all of an applications activities. Preferences cant be shared outside of the package. Preferences are stored as groups of key/value pairs. The following data types are supported as preference settings Boolean values Float values Integer values Long values String values

1. 2. 3. 4.

Preference functionality can be found in the SharedPreferences interface of the android.content package. To add preferences support to your application, you must take the following steps Retrieve an instance of a SharedPreferences object. Create a SharedPreferences.Editor to modify preference content. Make changes to the preferences using the Editor. Commit your changes. How To Creating Private & Shared Preferences Individual activities can have their own private preferences. These preferences are for the specific Activity only and are not shared with other activities within the application. The activity gets only one group of private preferences. Private preference example SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE); There are two differences while creating sharedpreferences Provide name to preference. Use a different call to get the preference instance. Shared preference example SharedPreferences settings = getSharedPreferences(MyCustomSharedPreferences, 0); Searching & Reading Preference To read a preference retrieve the SharedPreferences instance you want to read. You can check for a preference by name, retrieve strongly typed preferences, and register to listen for changes to the preferences. Important android.content.SharedPreferences Methods Method Purpose SharedPreferences.contains() Sees whether a specific preference exists by name SharedPreferences.edit() SharedPreferences.getAll() SharedPreferences.getBoolean() SharedPreferences.getFloat() SharedPreferences.getInt() Retrieves the editor to change these preferences Retrieves a map of all preference key/value pairs Retrieves a specific Boolean-type preference by name Retrieves a specific Float-type preference by name Retrieves a specific Integer-type preference by

name SharedPreferences.getLong() SharedPreferences.getString() Retrieves a specific Long-type preference by name Retrieves a specific String-type preference by name

Adding, Updating & Deleting Preferences To change preferences, open the preference Editor, make changes, and commit them. Important android.content.SharedPreferences.Editor Methods. Methods SharedPreferences.Editor.clear() Purpose Removes all preferences. This operation happens first, regardless of when it is called within an editing session; then all other changes are made and committed. Removes a specific preference by name. This operation happens first, regardless of when it is called within an editing session; then all other changes are made and committed. Sets a specific Boolean-type preference by name. Sets a specific Float-type preference by name. Sets a specific Integer-type preference by name. Sets a specific Long-type preference by name. Sets a specific String-type preference by name. Commits all changes from this editing session.

SharedPreferences.Editor.remove()

SharedPreferences.Editor.putBoolean() SharedPreferences.Editor.putFloat() SharedPreferences.Editor.putInt() SharedPreferences.Editor.putLong() SharedPreferences.Editor.putString() SharedPreferences.Editor.commit()

Searching & Reading Preference The following block of code retrieves the activitys private preferences, opens the preference editor, adds a long preference called SomeLong, and saves the change: Example SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE); SharedPreferences.Editor prefEditor = settingsActivity.edit(); prefEditor.putLong(SomeLong, java.lang.Long.MIN_VALUE); prefEditor.commit(); Android File System Internally, application preferences are stored as XML files. You can access the preferences file using DDMS using the File Explorer. Find these files on the Android file system in the following directory: /data/data/<package name>/shared_prefs/<preferences filename>.xml The preferences filename is the Activitys class name for private preferences or the name you give for the shared preferences. How to Working with Files and Directories Each Android application is its own user on the underlying Linux operating system. It has its own private application directory and files. Exploring with the Android Application Directories. Android application data is stored on the Android file system in the following toplevel directory: /data/data/<package name>/ Several default subdirectories are created for storing databases, preferences, and files as necessary. You can also create other custom directories as needed. File operators all begin by interacting with the application Context object. Use all the standard java.io package utilities to work with FileStream objects and such. Important android.content.Context File and Directory Management Methods. Methods Purpose Context.openFileInput() Opens an application file for reading.These files are located in the /files subdirectory. Context.openFileOutput() Creates or opens an application file for writing.These files are located in the /files

Context.deleteFile() Context.fileList() Context.getFilesDir() Context.getCacheDir() Context.getDir()

subdirectory. Deletes an application file by name.These files must be located in the /files subdirectory. Gets a list of all files in the /files subdirectory. Retrieves the application /files subdirectory object. Retrieves the application /cache subdirectory object. Creates or retrieves an application subdirectory byname.

Creating and Writing to Files to the Default Application Directory. openFileOutput() Use this method to create files in the default location under the application data directory: /data/data/<package name>/files/ For example, the following code snippet creates and opens a file called Filename.txt, It writes a single line of text to the file and then close the file: FileOutputStream fos;String strFileContents = Some text to write to the file.; fos = openFileOutput(Filename.txt, MODE_PRIVATE); fos.write(strFileContents.getBytes()); fos.close(); Data can be appended to the file by opening it with the mode set to MODE_APPEND: FileOutputStream fos;String strFileContents = More text to write to the file.; fos = openFileOutput(Filename.txt, MODE_APPEND); fos.write(strFileContents.getBytes()); fos.close(); The file we created has the path on the Android file system: /data/data/<package name>/files/Filename.txt. Reading from Files in the Default Application Directory. Following code snippet opens a file called Filename.txt for read operations: String strFileName = Filename.txt; FileInputStream fis = openFileInput(strFileName); Reading Raw Files Byte-by-Byte DataInputStream is useful for reading one line at a time. Heres a simple example of how to read a text file, line by line, and store it in a StringBuffer:

FileInputStream fis = openFileInput(filename);StringBuffer sBuffer = new StringBuffer(); DataInputStream dataIO = new DataInputStream(fis); String strLine = null; while ((strLine = dataIO.readLine()) != null) { sBuffer.append(strLine + n); } dataIO.close(); fis.close(); Reading XML Files The Android SDK includes several utilities for working with XML files, including SAX, an XML Pull Parser, and limited DOM, Level 2 Core support. Important XML Utility Packages Methods Purpose android.sax.* Framework to write standard SAX handlers. android.util.Xml.* XML utilities including the XMLPullParser. org.xml.sax.* Core SAX functionality. Project: www.saxproject.org/. javax.xml.* SAX and limited DOM, Level 2 Core support. org.w3c.dom Interfaces for DOM, Level 2 Core. org.xmlpull.* XmlPullParser and XMLSerializer interfaces as well as aSAX2 Driver class. Project: www.xmlpull.org/. Using Context.openFileOutput() and Context.openFileInput() are good enough if a few files and you want them stored in the /files subdirectory. To interact with the Android file system using the standard java.io.File class methods. The following code gets a File object for the /files application subdirectory and retrieves a list of all filenames in that directory: File pathForAppFiles = getFilesDir();String[] fileList = pathForAppFiles.list(); File fileDir = getFilesDir(); String strNewFileName = myFile.txt; String strFileContents = Some data for our file; File newFile = new File(fileDir, strNewFileName); newFile.createNewFile();

FileOutputStream fo = new FileOutputStream(newFile.getAbsolutePath()); fo.write(strFileContents.getBytes()); fo.close(); Use File objects to manage files within a desired directory and create subdirectories. For example, To store track files within album directories. Or To create a file in a directory other than the default. To cache some data to speed up your applications performance and how often it accesses the network. In this instance, you might want to create a cache file. There is also a special application directory for storing cache files. Cache files are stored in the following location on the Android file system: /data/data/<package name>/cache/ The following code gets a File object for the /cache application subdirectory, creates a new file in that specific directory, writes some data to the file, closes the file, and then deletes it: File pathCacheDir = getCacheDir();String strCacheFileName = myCacheFile.cache; String strFileContents = Some data for our file; File newCacheFile = new File(pathCacheDir, strCacheFileName); newCacheFile.createNewFile(); FileOutputStream foCache = new FileOutputStream(newCacheFile.getAbsolutePath()); foCache.write(strFileContents.getBytes()); foCache.close(); newCacheFile.delete(); File Read/Write Demo In android This android application shows you how write and read a file from SD Card in Android. In this program two buttons are shown and an Edit box. When you type some text into the editText and click to Write Button the text is saved to a text file and saved to the SD Card. When you click Read Button the file is read from the SD card and the display. Now we Start our project FileReadWriteDemo in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages.

When create and write a private File. Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. Write to the file with write(). Close the stream with close() When read a File. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close(). Open res/layout/main.xml <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=Enter Message : /> <EditText android:id=@+id/message android:layout_width=fill_parent android:layout_height=wrap_content /> <Button android:id=@+id/write android:layout_width=match_parent android:layout_height=wrap_content android:text=Write /> <Button android:id=@+id/read android:layout_width=match_parent android:layout_height=wrap_content android:text=Read />

<TextView android:id=@+id/display android:layout_width=fill_parent android:layout_height=wrap_content android:text=" /> </LinearLayout> FileReadWriteDemo/src/com/FileReadWriteDemoActivity/FileReadWriteDemoAc tivity.java package com.theandroid.in; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.androidbook.filewritedemo.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class FileReadWriteDemoActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ Button wr,rd; EditText msg; TextView disp; FileOutputStream fos=null; FileInputStream fis=null; @Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wr=(Button) findViewById(R.id.write); wr.setOnClickListener(this); rd=(Button) findViewById(R.id.read); rd.setOnClickListener(this); msg=(EditText) findViewById(R.id.message); disp=(TextView) findViewById(R.id.display); } @Override public void onClick(View v) { if(v.getId()==wr.getId()){ try{ fos=openFileOutput(test.txt, Context.MODE_PRIVATE); String message=new String(msg.getText().toString()); fos.write(message.getBytes()); fos.close(); } catch (FileNotFoundException e) { } catch (IOException e){ } Toast.makeText(getApplicationContext(), File Written, Toast.LENGTH_SHORT).show(); } if(v.getId()==rd.getId()){ try{ int i; char ch; fis=openFileInput(test.txt); String str=";

do{ i=fis.read(); ch=(char)i; if(i!=-1) str=str+ch; }while(i!=-1); disp.setText(str); } catch (Exception e) { }}}} What is SQLite in Android SQLite is a very popular embedded database, as it combines a clean SQL interface with a very small memory footprint and decent speed. Moreover, it is public domain, so everyone can use it. Lots of firms (Adobe, Apple, Google, Sun, Symbian) and open-source projects (Mozilla, PHP, Python) all ship products with SQLite. The Android file system includes support for application-specific relational databases using SQLite. SQLite databases are lightweight and file-based, making them ideally suited for embedded devices. These databases and the data within them are private to the application. To share application data with other applications, it must be exposed, the data can be shared by making it as content provider. The Android SDK includes a number of useful SQLite database management classes, these classes are found in the android.database.sqlite package. The classes for managing database creation and versioning, database management, and query builder helper classes to help you format proper SQL statements and queries. The package also includes specialized Cursor objects for iterating query results, can also find all the specialized exceptions associated with SQLite The Android SDK includes a number of useful SQLite database management classes, these classes are found in the android.database.sqlite package.

1) Create the SQLiteDatabase object: Before you use any SQLiteDatabase class APIs, of course you need to create an object of that class (say, dbTest in this case). First, declare the object at appropriate place. In this example I have declared it at Activity level so that its visible to all Activity life cycle functions. This is just one way of doing, you can declare based on your application need. SQLiteDatabase mDatabase; Next logical step is to create the object. Again, the object can be created at different time as per need. I would suggest to defer it till you require it. There are many options based on which Class you are using to create the database. openDatabase() openOrCreateDatabase() Searching for API listed above at Androids SDK reference shows various classes which publish these two APIs to create a SQLite database. Here, I have used android.app.ListActivitys openOrCreateDatabase() to create the database. This needs three arguments: String : Name of the database, int : Database mode. There are three self-explanatory modes MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE SQLiteDatabase.CursorFactory : Factory object to instantiate a cursor when query is called Note : As many of the SQLiteDatabase APIs throw android.database.SQLException, use of try block becomes essential. mDatabase = openOrCreateDatabase(my_sqlite_database.db, SQLiteDatabase.CREATE_IF_NECESSARY,null); How to create SQLite Database in Android SQLiteOpenHelper : A helper class to manage database creation and version management. You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state. The Android SDK includes a number of useful SQLite database management classes, these classes are found in the android.database.sqlite package.

Now we Start our project SQLite Test in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. The Use of SQLiteOpenHelper class to manage database creation and version management. onCreate(SQLiteDatabase db) method Called when the database is created for the first time. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) method Called when the database needs to be upgraded. SQLite Test/src/com/DBManager/DBManager.java package com.theandroid.in.db;import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; public abstract class DBManager extends SQLiteOpenHelper{ private static final String DB_FILE_NAME = test.db; private String tableName; private String[] columns; public DBManager(Context context,String tableName, String [] columns) { super(context, DB_FILE_NAME, null, 1); this.tableName = tableName; this.columns = columns; } @Override public void onCreate(SQLiteDatabase db) { String sql = create table + tableName + ( + BaseColumns._ID + integer primary key autoincrement ; for (int i=0;i<columns.length; i++) { sql+=, +columns[i]; } sql+= ) ; db.execSQL( sql );

} @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } public void insert(ContentValues values){ getWritableDatabase().insert(tableName, null, values); } public Cursor getAll(){ return getReadableDatabase().query(tableName, null, null, null, null, null, null); } } SQLite Test/src/com/TestsDBManager/TestsDBManager.java package com.theandroid.in.db;import android.content.ContentValues; import android.content.Context; public class TestsDBManager extends DBManager { private static final String TABLE_NAME = TESTS; private static final String [] COLUMNS = {NAME text not null,VALUE text}; public TestsDBManager(Context context) { super(context, TABLE_NAME, COLUMNS); } public void insert(String name, String value) { ContentValues values = new ContentValues(); values.put(NAME, name); values.put(VALUE, value); super.insert(values); } } SQLite Test/src/com/SQLiteTest/SQLiteTest.java package com.theandroid.in.sqlite;import android.app.Activity; import android.database.Cursor;

import android.os.Bundle; import android.util.Log; import com.aviyehuda.sqlite.R; import com.theandroid.in.db.TestsDBManager; public class SQLiteTest extends Activity { TestsDBManager aviDB; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); aviDB = new TestsDBManager(this); aviDB.insert(test1?,xxxx); aviDB.insert(test2?,yyyy); Cursor cursor = aviDB.getAll(); while(cursor.moveToNext()){ Log.d(>>>, cursor.getString(0)+ -+cursor.getString(1)+ =+cursor.getString(2)); } } @Override public void onDestroy() { aviDB.close(); } } 2) Execute Structure Query Language (SQL) statements: SQLiteDatabase class has execSQL() API which executes a single SQL statement that is not a query, like, CREATE, DELETE, INSERT, etc. Create a table: Following statement creates a table in the database. Example

String s = CREATE TABLE tbl_authors (id INTEGER PRIMARY KEY AUTOINCREMENT,firstname TEXT,lastname TEXT);; mDatabase.execSQL(s); Insert a record: Following statement inserts a record in the table. There are tow method in Inserting data to the table : Method : 1 mDatabase.execSQL( insert into tbl_authors(firstname, lastname) values (Yashvant, Kanetkar ); ); Method : 2 ContentValues values = new ContentValues(); values.put(firstname, Yashvant); values.put(lastname, Kanetkar); mDatabase.insert(tbl_authors, null, values); Delete a record: Following statement would delete all records from the table. There are two method in Deleting data to the table : Method : 1 mDatabase.execSQL(delete from tbl_authors where firstname=I'); Method : 2 mDatabase.delete(tbl_authors, firstname=?, new String[]{Y}); 3 Execute Structure Query Language (SQL) Queries: Executing an SQL query may result in some data output, commonly known as result set. SQLiteDatabase class has rawQuery() API which runs the provided SQL query and returns a android.database.Cursor over the result set. Using Cursor we can iterate through the result set. Example of performing the simple query and then hand over Cursor management to the parent Activity: // SIMPLE QUERY: select * from tbl_books Cursor c = mDatabase.query(tbl_books,null,null,null,null,null,null); startManagingCursor(c); 4 Using Cursor to iterate the result set: Cursor class has very useful APIs to navigate the result set, like moveToFirst(), moveToLast(), moveToNext(), etc. and retrieve data of various standard data types, like, getString(), getShort(), getInt(), getFloat(), getLong(), etc.

In below snippet while I retrieve the data that I need, I add it to an ArrayList object (queryResult) of String type. Later I use a simple_list_item_1 list (available by default) to show the data. ArrayList<String> queryResult = new ArrayList<String>(); if(cursor != null) {if(cursor.moveToFirst()) { do {String fName = cursor.getString(cursor.getColumnIndex(FirstName)); int age = cursor.getInt(cursor.getColumnIndex(Age)); queryResult.add( + fName + , Age: + age); } while (cursor.moveToNext()); } } this.setListAdapter(new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, queryResult)); 5 Closing the database: Finally.Close your database when you are not using it. You can close the database using the close() method of your SQLiteDatabase instance, like this: mDatabase.close();

Cursor In Android SQLite The columns in the query results are defined by the query, not necessarily by the database columns. These might include calculated columns, column aliases, and composite columns. // SIMPLE QUERY: select * from tbl_books Cursor c = mDatabase.query(tbl_books,null,null,null,null,null,null); // Do something quick with the Cursor here c.close(); Managing cursor as a part of application life cycle When cursor returns multiple records or does some intensive tasks then consider running this operation as a separate thread other than UI Thread.

Cursor object must be managed as a part of application life cycle. When the application pauses or shuts down, the Cursor must be deactivated with a call to thedeactivate() method. When the application restarts, the Cursor should refresh its data using the requery() method. When the Cursor is no longer needed, a call to close() must be made to release its resources. Developer can hand off the responsibility of managing Cursor objects to the parent Activity by using the Activity method called startManagingCursor(). Calling above method: the Activity handles the rest i.e. deactivating and reactivating the Cursor as necessary and destroying the Cursorwhen the Activity is destroyed. You can always begin manually managing the Cursor object again later by simply calling stopManagingCursor(). Example of performing the simple query and then hand over Cursor management to the parent Activity: // SIMPLE QUERY: select * from tbl_booksCursor c = mDatabase.query(tbl_books,null,null,null,null,null,null); startManagingCursor(c); Iterating Rows of Query Results and Extracting Specific Data Use the Cursor to iterate those results, one row at a time using various navigation methods such asmoveToFirst(), moveToNext(), and isAfterLast(). Because SQLite is not strongly typed, you can always pull fields out as Strings using the getString()method, but you can also use the type-appropriate extraction utility function to enforce type safety in your application. The following method takes a valid Cursor object, prints the number of returned results, and then prints some column information (name and number of columns) & it iterates through the query results, printing each record. Executing simple queries query() method is available in SQLiteDatabase class. This method queries the database and returns any results as in a Cursor object. The query() method we mainly use takes the following parameters: 1. [String]:The name of the table to compile the query against. 2. [String Array]: List of specific column names to return (use null for all).

3. [String] The WHERE clause: Use null for all; might include selection args as ?s. 4. [String Array]:Any selection argument values to substitute in for the ?s in the earlier parameter. 5. [String] GROUP BY clause: null for no grouping. 6. [String] HAVING clause: null unless GROUP BY clause requires one. 7. [String] ORDER BY clause: If null, default ordering used. 8. [String] LIMIT clause: If null, no limit. Cursor c = mDatabase.query(tbl_books,null,null,null,null,null,null); SELECT * FROM tbl_books; Cursor c = mDatabase.query(tbl_books, null, id=?, new String*+,9-, null, null, null); SELECT * tbl_books WHERE id=9; String asColumnsToReturn*+ = , title, id -; String strSortOrder = title ASC; Cursor c = mDatabase.query(tbl_books, asColumnsToReturn, null, null, null, null, strSortOrder); SELECT title, id FROM tbl_books ORDER BY title ASC; The individual parameters for the clauses (WHERE, GROUP BY, HAVING, ORDER BY, LIMIT) are all Strings, but you do not need to include the keyword, such as WHERE. Instead, you include the part of the clause after the keyword. Selecting all results might be fine for tiny databases, but it is not terribly efficient. Always tailor your SQL queries to return only the results you require with no extraneous information included. Executing More Complex Queries Using SQLiteQueryBuilder As your queries get more complex and involve multiple tables, you should leverage the SQLiteQueryBuilder convenience class, which can build complex queries (such as joins) programmatically. When more than one table is involved, you need to make sure you refer to columns within a table by their fully qualified names. Use a SQLiteQueryBuilder to build and execute a simple INNER JOIN between two tables to get a list of books with their authors: Query with a inner join SELECT tbl_books.title, tbl_books.id,

tbl_authors.firstname, tbl_authors.lastname, tbl_books.authorid FROM tbl_books INNER JOIN tbl_authors on tbl_books.authorid=tbl_authors.id ORDER BY title ASC; SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); queryBuilder.setTables(tbl_books, tbl_authors); queryBuilder.appendWhere(tbl_books.authorid=tbl_authors.id); String asColumnsToReturn[] = { tbl_books.title, tbl_books.id, tbl_authors.firstname, tbl_authors.lastname, tbl_books.authorid -; String strSortOrder = title ASC; Cursor c = queryBuilder.query(mDatabase, asColumnsToReturn, null, null, null, null,strSortOrder); Executing Raw Queries Without Builders and Column-Mapping All these helpful Android query utilities can sometimes make building and performing a nonstandard or complex query too verbose. In this case consider the rawQuery() method. The rawQuery() method simply takes a SQL statement String (with optional selection arguments if you include ?s) and returns a Cursor of results. A UNION query is feasible with the QueryBuilder, but their implementation is cumbersome when you start using column aliases and the like. To execute the following SQL UNION query, which returns a list of all book titles and authors whose name contains the substring ow (that is Hallows, Rowling), as in the following: SELECT title AS Name, tbl_books AS OriginalTable FROM tbl_books WHERE Name LIKE %ow% UNION SELECT (firstname|| || lastname) AS Name, tbl_authors AS OriginalTable FROM tbl_authors WHERE Name LIKE %ow% ORDER BY Name ASC;

String sqlUnionExample = SELECT title AS Name, tbl_books AS OriginalTable from tbl_books WHERE Name LIKE ? UNION SELECT (firstname|| || lastname) AS Name, tbl_authors AS OriginalTable from tbl_authors WHERE Name LIKE ? ORDER BY Name ASC;; Cursor c = mDatabase.rawQuery (sqlUnionExample, new String*+, %ow%, %ow%-); How to use of AndroidManifest xml Applications identity Versioning (<manifest> tag, android:versionCode & android:versionName attributes). Application name & icon (<application tag, android:icon & android:label attributes) System requirements

Target SDK Version (<manifest> parent tag, <uses-sdk> child tag, android:minSdkVersion, android:maxSdkVersion, android:targetSdkVersion attributes, values integer no. specifying api level). Application platform requirement Supported Input Methods (<manifest> parent tag, <uses-configuration> child tag, android:reqTouchScreen, android:reqKeyboardType, android:reqHardKeyboard, android:reqNavigation, android:reqFiveWayNav attributes, values true/false) Required device features (<manifest> parent tag, <uses-feature> child tag, android:name attributes, values appropriate values as per application requirement). Supported screen size (<manifest> parent tag, <supports-screen> child tag, android:smallScreens, android:normalScreens, android:largeScreens, android:resizable, android:anyDensity, values true/false). Specifying external library reference (<manifest> parent tag, <uses-library child tag, android:name attribute, values library name that application uses). Registering applications activity, service, broadcast receiver & Intnet-filters Activity (<manifest> parent tag, <activity> child tag, android:name attributes, values name of the activity class). Service (<manifest> parent tag, <service> child tag). Broadcast Receiver (<manifest> parent tag, <receiver> child tag). Intent-filters (<manifest> parent tag, <intent-filter> child tag, specify <action>, <category> & <data> as sub tags of <intent-filter>).

Granting & taking permissions o Grant permission (<permission> tag) o Taking/ receiving permission (<uses-permission tag, android:name attribute).

MediaStore Content Provider: To access media on the phone and on external storage devices. The primary types of media that you can access are audio, images, and video. Access these different types of media through their respective content provider classes underandroid.provider.MediaStore. MediaStore classes allow full interaction with the data i.e. retrieve, add, and delete media files from the device. Some commonly used classes under android.provider.MediaStore. Class Video.Media Images.Media Images.ThumbNails Audio.Media Audio.Albums Audio.Artists Audio.Genres Audio.Playlists Purpose Manages video files on the device Manages image files on the device Retrieves thumbnails for the images Manages audio files on the device Manages audio files organized by the album Manages audio files by the artist who created them Manages audio files belonging to a particular genre Manages audio files that are part of a particular playlist

The following code demonstrates how to request data from a content provider. String[] requestedColumns = {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION }; Cursor cur = managedQuery( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, requestedColumns, null, null, null); Log.d(DEBUG_TAG, Audio files: + cur.getCount()); Log.d(DEBUG_TAG, Columns: + cur.getColumnCount()); String[] columns = cur.getColumnNames(); int name = cur.getColumnIndex(MediaStore.Audio.Media.TITLE); int size = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);

cur.moveToFirst(); while (!cur.isAfterLast()) { Log.d(DEBUG_TAG, Title + cur.getString(name)); Log.d(DEBUG_TAG, Length: + cur.getInt(size) / 1000 + seconds); cur.moveToNext(); } A query is made to the MediaStore to retrieve the titles of all the audio files on the SD card of the handset and their respective durations. This code requires that you load some audio files onto the virtual SD card in the emulator. The MediaStore.Audio.Media class has predefined strings for every data field (or column) exposed by the content provider. Limit the audio file data fields requested as part of the query by defining a string array with the column names required. managedQuery() Method: The first parameter is the predefined URI of the content provider you want to query (in most cases, the primary external storage is the SD card). The second parameter is the list of columns to return (audio file titles and durations). The third and fourth parameters control any selection filtering arguments. The fifth parameter provides a sort method for the results.We leave these null, as we want all audio files at this location. By using the managedQuery() method, we get a managed Cursor as a result. Examine our Cursor for the results. Android CallLog Content Provider Example To access the call log on the handset via the class android.provider.CallLog. Use the CallLog to filter recently dialed calls, received, and missed calls. The date and duration of each call is logged and tied back to the Contact application for caller identification purposes. Your application needs a special permission to access the information provided by the CallLog content provider. Android allows for custom labels on these numbers, which we leverage for this example. String[] requestedColumns = { CallLog.Calls.CACHED_NUMBER_LABEL, CallLog.Calls.DURATION }; Cursor calls = managedQuery( CallLog.Calls.CONTENT_URI, requestedColumns, CallLog.Calls.CACHED_NUMBER_LABEL + = ?, new String[] { HourlyClient } , null); Log.d(DEBUG_TAG, Call count: + calls.getCount()); int durIdx = calls.getColumnIndex(CallLog.Calls.DURATION);

int totalDuration = 0; calls.moveToFirst(); while (!calls.isAfterLast()) { Log.d(DEBUG_TAG, Duration: + calls.getInt(durIdx)); totalDuration += calls.getInt(durIdx); calls.moveToNext(); } Log.d(DEBUG_TAG, HourlyClient Total Call Duration: + totalDuration); Accessing Content Providers That Require Permissions <uses-permission xmlns:android=http://schemas.android.com/apk/res/android android:name=android.permission.READ_CONTACTS> </uses-permission> Android Browser Content Provider Example Purpose: The Browser content provider For users browser history and bookmarked websites. URI: Browser.BOOKMARKS_URI. Columns: E.g. to view the name of the website url : Browser.Bookmarkcolumns.TITLE, no. of visits to site : Browser.Bookmarkcolumns.VISITS, whether it is bookmarked : Browser.Bookmarkcolumns.BOOKMARK etc. You access this content provider via the android.provider.Browser class. Use the Browser content provider to add a bookmark for your application support website. Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns, Browser.BookmarkColumns.BOOKMARK + =1, null, Browser.BookmarkColumns.VISITS + DESC limit 5); String[] requestedColumns = {Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.VISITS, Browser.BookmarkColumns.BOOKMARK }; Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns, Browser.BookmarkColumns.BOOKMARK + =1, null, Browser.BookmarkColumns.VISITS + DESC limit 5); Log.d(DEBUG_TAG, Bookmarks count: + faves.getCount()); int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE); int visitsIdx = faves.getColumnIndex(Browser.BookmarkColumns.VISITS);

int bmIdx = faves.getColumnIndex(Browser.BookmarkColumns.BOOKMARK); faves.moveToFirst(); while (!faves.isAfterLast()) { Log.d(SimpleBookmarks, faves.getString(titleIdx) + visited + faves.getInt(visitsIdx) + times : + (faves.getInt(bmIdx) != 0 ? true : false)); faves.moveToNext(); } In this example,we query the Browser content provider to find the top five most frequently visited bookmarked sites. Use managedQuery() method to retrieve info. for various columns with 5 arguments. 1st Browser.BOOKMARKS_URI, is a URI for all browser history, not only the Bookmarked items. 2nd Efines the requested columns for the query results. 3rd Specifies that the bookmark property must be true.This parameter is needed in order to filter within the query. Now the results are only browser history entries that have been bookmarked. 4th Selection arguments, is used only when replacement values are used, which is not used in this case, so the value is set to null. 5th Specifies an order to the results (most visited in descending order). Android Contacts Content Provider Example Using the Contacts database is one of the most commonly used applications on the mobile phone. People always want phone numbers handy for calling friends, family, coworkers, and clients. Additionally, most phones show the identity of the caller based on the contacts application, including nicknames, photos, or icons. Retrieve the primary email and primary phone number for this contact. int nameIdx = oneContact.getColumnIndex(Contacts.People.NAME); int emailIDIdx = oneContact.getColumnIndex(Contacts.People.PRIMARY_EMAIL_ID); int phoneIDIdx = oneContact.getColumnIndex(Contacts.People.PRIMARY_PHONE_ID); oneContact.moveToFirst(); int emailID = oneContact.getInt(emailIDIdx); int phoneID = oneContact.getInt(phoneIDIdx);

Now that we have the column index values for the contacts name, primary email address, and primary phone number, we need to build the Uri objects associated with those pieces of information and query for the primary email and primary phone number. Uri emailUri = ContentUris.withAppendedId( Contacts.ContactMethods.CONTENT_URI,emailID); Cursor primaryEmail = managedQuery(emailUri, new String[] { Contacts.ContactMethods.DATA},null, null, null); Uri phoneUri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, phoneID); Cursor primaryNumber = managedQuery(phoneUri, new String[] {Contacts.Phones.NUMBER},null, null, null); Take a shortcut with the requested columns String array because each query only has one column: String name = oneContact.getString(nameIdx); primaryEmail.moveToFirst(); String email = primaryEmail.getString(0); primaryNumber.moveToFirst(); String number = primaryNumber.getString(0); If an email or phone number doesnt exist, an exception called android.database.CursorIndexOutOfBoundsException is thrown. This can be caught, or you can check to see that a result was actually returned in the Cursor first. Querying for specific contact If that seemed like quite a lot of coding to get a phone number, youre not alone. For getting a quick piece of data, there is a faster way. The following block of code demonstrates how we can get the primary number and name for one contact.The primary number for a contact is designated as the default number within the contact manager on the handset. It might be useful to use the primary number field if you dont get any results back from the query. String[] requestedColumns = { Contacts.Phones.NAME, Contacts.Phones.NUMBER,

}; Cursor contacts = managedQuery( Contacts.Phones.CONTENT_URI, requestedColumns, Contacts.Phones.ISPRIMARY + <>0, null, name desc limit 1); Log.d(debugTag, Contacts count: + contacts.getCount()); int nameIdx = contacts .getColumnIndex(Contacts.Phones.NAME); int phoneIdx = contacts .getColumnIndex(Contacts.Phones.NUMBER); contacts.moveToFirst(); Log.d(debugTag, Name: + contacts.getString(nameIdx)); Log.d(debugTag, Phone: + contacts.getString(phoneIdx)); State Persistence Demo using SharedPreferences This is a simple application which shows How to use of persist the state of the data i.e. if you save something on first launch it checks those setting when you relaunch the application. Now we Start our project StatePersistenceDemo in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. Under onPause() method use SharedPreferences.Editor Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply(). Under onResume() method use SharedPreferences Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Open res/layout/main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent >

<TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello /> <EditText android:id=@+id/DataSaved android:layout_width=fill_parent android:layout_height=wrap_content android:freezesText=true /> </LinearLayout> StatePersistenceDemo/src/com/StatePersistenceDemoActivity/StatePersistenceDe moActivity.java package com.theandroid.in;import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; public class StatePersistenceDemoActivity extends Activity { /** Called when the activity is first created. */ EditText edtText; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); edtText = (EditText)findViewById(R.id.DataSaved); } protected void onPause() { // TODO Auto-generated method stub super.onPause(); SharedPreferences.Editor edt = getPreferences(0).edit(); edt.putString(Text, edtText.getText().toString()); edt.putInt(Start, edtText.getSelectionStart()); edt.putInt(End, edtText.getSelectionEnd()); edt.commit(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume();

SharedPreferences pref = getPreferences(0); String oldData = pref.getString(Text,null); if(oldData != null) { edtText.setText(oldData,TextView.BufferType.EDITABLE); int selectionStart = pref.getInt(Start, -1); int selectionEnd = pref.getInt(End, -1); if (selectionStart != -1 && selectionEnd != -1) { edtText.setSelection(selectionStart, selectionEnd); } } } } How To Inserts Contacts, Update Contacts And Delete Contacts In Android Content providers are not only static sources of data. They can also be used to add, update, and delete data, if the content provider application has implemented this functionality. Your application must have the appropriate permissions (that is, WRITE_CONTACTS as opposed to READ_CONTACTS) to perform some of these actions. Insert new contact Create instance of ContentValues. Use put method to put key/value pair for new contact. Create uri instance to locate default contacts along with value stored inside ContentValues. Create uri instance to make new uri that points to this newly created contact. Use ContentValues instance to insert further information for new contact using newly created uri. Use insert() method of getContentResolver() to insert new contact. Content providers are not only static sources of data. They can also be used to add, update, and delete data, if the content provider application has implemented this functionality. ContentValues values = new ContentValues(); values.put(Contacts.People.NAME, Sample User);

Insert the data in the database found at the Contacts.People.CONTENT_URI Use a call to getContentResolver() to retrieve the ContentResolver associated with our Activity. Uri uri = getContentResolver().insert(Contacts.People.CONTENT_URI, values); Uri phoneUri = Uri.withAppendedPath(uri,Contacts.People.Phones.CONTENT_DIRECTORY); The return value is the Uri of our new contact, use it for adding phone numbers to our new contact. Reuse the ContentValues instance by clearing it and adding a Contacts.Phones.NUMBER and the Contacts.Phones.TYPE for it. Using the ContentResolver,we insert this data into the newly created Uri. values.clear(); values.put(Contacts.Phones.NUMBER, 2125551212); values.put(Contacts.Phones.TYPE, Contacts.Phones.TYPE_WORK); getContentResolver().insert(phoneUri, values); Updating contact Create new uri to point to contact that needs to be updated. Create instance of ContentValues & use put() method for the columns where data needs to be updated. Use update() method of getContentResolver() to update contact. An instance of the ContentValues object to map the data field to update with the data value in this case, the note field. Replaces any current note stored in the NOTES field currently stored with the contact. ContentValues values = new ContentValues(); values.put(People.NOTES, This is my boss); Create the Uri for the specific contact we are updating, a simple call to the update() method of the ContentResolver class completes our change. Uri updateUri = ContentUris.withAppendedId(People.CONTENT_URI, rowId); int rows = getContentResolver().update(updateUri, values, null, null); Log.d(debugTag, Rows updated: + rows); Deleting Records Deleting All Records Deletes all rows at the given URI, execute operations like this with extreme care.

The delete() method deletes all rows at a given URI filtered by the selection parameters, which, in this case, includes all rows at the People.CONTENT_URI location; in other words, all contact entries. int rows = getContentResolver().delete(People.CONTENT_URI, null, null); Log.d(debugTag, Rows: + rows); Deleting Specific Records To select specific rows to delete by adding the unique identifier index to the end of the URI or remove rows matching a particular pattern. For example, the following deletion matches all contact records with the name Sample User. int rows = getContentResolver().delete(People.CONTENT_URI, People.NAME + =?, new String*+ ,Sample User-); Log.d(debugTag, Rows: + rows); Android Live Folder Example Live folders, introduced in Android 1.5 (API Level 3), let you display any source of data on the Home screen without forcing the user to launch an application. A live folder is simply a real-time view of a ContentProvider. As such, a live folder can be used to display all of the users contacts or bookmarks, email, playlists, an RSS feed, and so on. A LiveFolder (android.provider.LiveFolders) is a powerful feature that complements the content provider interface. A LiveFolder is a special folder containing content generated by a content provider. For example, a user might want to create a LiveFolder with favorite contacts (Fave Five), most frequently viewed emails in a custom email application, or high-priority tasks in a task management application. When the user chooses to create a LiveFolder, the Android system provides a list of all activities that respond to the ACTION_CREATE_LIVE_FOLDER Intent. If the user chooses your Activity, that Activity creates the LiveFolder and passes it back to the system using the setResult() method. The LiveFolder consists of the following components. Folder name Folder icon Display mode (grid or list) Content provider URI for the folder contents

The first task when enabling a content provider to serve up data to a LiveFolder is to provide an <intent-filter> for an Activity that handles enabling the LiveFolder. This is done within the AndroidManifest.xml file as follows: <intent-filter> <action android:name= android.intent.action.CREATE_LIVE_FOLDER /> <category android:name=android.intent.category.DEFAULT /> </intent-filter> Next, this action needs to be handled within the onCreate() method of the Activity it has been defined for. final Intent intent = getIntent(); final String action = intent.getAction(); if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) { final Intent resultIntent = new Intent(); resultIntent.setData(TrackPointProvider.LIVE_URI); resultIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, GPX Sample); resultIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon)); resultIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST); setResult(RESULT_OK, resultIntent); } // This defines the core components of the LiveFolder: its name, icon, display mode, and Uri. The Uri is not the same as one that already existed because it needs certain specific fields to work properly. This leads directly to the next task: modifying the content provider to prepare it for serving up data to the LiveFolder. First, you define a new Uri. In this case, you add /live to the end of the existing CONTENT_URI. For Example: public static final Uri LIVE_URI = Uri.parse(content:// + AUTHORITY + / + TrackPointDatabase.TRACKPOINTS_TABLE+ /live);

Add this new Uri pattern the UriMatcher. Next, modify the query() implementation to recognize this new Uri and add a projection. switch (sURIMatcher.match(uri)) { case TRACKPOINT_ID: qBuilder.appendWhere(_id= + uri.getLastPathSegment()); break; case TRACKPOINTS_LIVE: qBuilder.setProjectionMap(TRACKPOINTS_LIVE_FOLDER_PROJECTION_M AP); break; // other cases } Cursor c = qBuilder.query( // The projection is critical for a working LiveFolder provider. There are two mandatory fields that must be in the resulting Cursor: LiveFolder._ID and LiveFolder.NAME. In addition to these, other fields, such as LiveFolder.DESCRIPTION, are available to modify the look and behavior of the view. In this Example,we use TIMESTAMP for the name, as shown here in the following projection implementation. private static final HashMap<String,String> TRACKPOINTS_LIVE_FOLDER_PROJECTION_MAP; static { TRACKPOINTS_LIVE_FOLDER_PROJECTION_MAP = new HashMap<String,String>(); TRACKPOINTS_LIVE_FOLDER_PROJECTION_MAP.put( LiveFolders._ID, _ID + as + LiveFolders._ID); TRACKPOINTS_LIVE_FOLDER_PROJECTION_MAP.put( LiveFolders.NAME, TIMESTAMP + as + LiveFolders.NAME); } How To Parsing XML File In Android

A large portion of data transmitted between network resources is stored in a structured fashion in Extensible Markup Language (XML). In particular, RSS feeds are provided in a standardized XML format, and many web services provide data using these feeds. Parsing XML from the network is similar to parsing an XML resource file or a raw file on the file system. The following code demonstrates how to use the XML Pull Parser to read an XML file from flickr.com and extract specific data from within it. A TextView called status is assigned before this block of code is executed and displays the status of the parsing operation. import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; URL text = new URL( http://api.flickr.com/services/feeds/photos_public.gne + ? id=26648248@N04&lang=en-us&format=atom); Retrieve an XmlPullParser instance from the XmlPullParserFactory, a Pull Parser has a main method that returns the next event. XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance(); XmlPullParser parser = parserCreator.newPullParser(); parser.setInput(text.openStream(), null); The only event that we check for is the START_TAG event, which signifies the beginning of an XML tag. int parserEvent = parser.getEventType(); Loop is iterated through the end of the document. while (parserEvent != XmlPullParser.END_DOCUMENT) { switch(parserEvent) { case XmlPullParser.START_TAG; Attribute values are queried and compared, example looks specifically for image URLs within the XML from a flickr feed query. String tag = parser.getName(); if (tag.compareTo(link) == 0) {

String relType = parser.getAttributeValue(null, rel); if (relType.compareTo(enclosure) == 0 ) { String encType =parser.getAttributeValue(null, type); if (encType.startsWith(image/)) { String imageSrc = parser.getAttributeValue(null, href); Log.i(Net,image source = + imageSrc); } } } break; } parserEvent = parser.next(); XML Pull Parser events START_TAG: Returned when a new tag is found (that is, <tag>). TEXT: Returned when text is found (that is, <tag>text</tag> where text has been found). END_TAG: Returned when the end of tag is found (that is, </tag>). END_DOCUMENT: Returned when the end of the XML file is reached. How to play video file using VideoView in Android VideoView : Displays a video file. The VideoView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting. MediaController: A view containing controls for a MediaPlayer. Typically contains the buttons likePlay/Pause, Rewind, Fast Forward and a progress slider. It takes care of synchronizing the controls with the state of the MediaPlayer. The way to use this class is to instantiate it programatically. The MediaController will create a default set of controls and put them in a window floating above your application. Specifically, the controls will float above the view specified with setAnchorView(). The window will disappear if left idle for three seconds and reappear when the user touches the anchor view.

Functions like show() and hide() have no effect when MediaController is created in an xml layout. MediaController will hide and show the buttons according to these rules. The previous and next buttons are hidden until setPrevNextListeners() has been called The previous and next buttons are visible but disabled if setPrevNextListeners() was called with null listeners The rewind and fastforward buttons are shown unless requested otherwise by using the MediaController(Context, boolean) constructor with the boolean set to false. Now we Start our project VideoViewDemo in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. VideoView use class of Displays a video file. MdediaController use class of view containing controls for a MediaPlayer To force focus to a specific view, call requestFocus() . The start() method should be called to actually execute the new Thread. Open res/layout/main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent> <VideoView android:id=@+id/ViewVideo android:layout_width=320px android:layout_height=240px/> </LinearLayout> VideoViewDemo/src/com/VideoViewDemoActivity/VideoViewDemoActivity.java package com.theandroid.in;import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class VideoViewDemoActivity extends Activity { /** Called when the activity is first created. */ private VideoView videoView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

videoView = (VideoView)findViewById(R.id.ViewVideo); videoView.setVideoURI(Uri.parse(android.resource:// + getPackageName() +/+R.raw.video)); videoView.setMediaController(new MediaController(this)); videoView.requestFocus(); videoView.start(); } } What Is AsyncTask In Android With Example In Android Tutorials AsyncTask is an abstract helper class for managing background operations that eventually post back to the UI thread. It creates a simpler interface for asynchronous operations than manually creating a Java Thread class. Instead of creating threads for background processing and using messages and message handlers for updating the UI. You can create a subclass of AsyncTask and implement the appropriate event methods. The onPreExecute() method runs on the UI thread before background processing begins. The doInBackground() method handles background processing, whereas publishProgress()informs the UI thread periodically about the background processing progress. When the background processing finishes, the onPostExecute() method runs on the UI thread to give a final update. The following code AsyncTask with example implementation of AsyncTask to perform the same functionality as the code for the Thread. private class ImageLoader extends AsyncTask<URL, String, String> { @Override protected String doInBackground(URL params) { // just one param try { URL text = params[0]; // parsing code { publishProgress(imgCount = + curImageCount); // end parsing code }} catch (Exception e ) {

Log.e(Net,Failed in parsing XML, e); return Finished with failure.; protected void onCancelled() { Log.e(Net, Async task Cancelled); } protected void onPostExecute(String result) { mStatus.setText(result); } protected void onPreExecute() { mStatus.setText(About to load URL); } protected void onProgressUpdate(String values) { // just one value, please mStatus.setText(values[0]); }} When launched with the AsyncTask.execute() method, doInBackground() runs in a background thread while the other methods run on the UI thread. There is no need to manage a Handler or post a Runnable object to it. This simplifies coding and debugging. How To Using threads for network calls In Android In this android tutorials using threads for network calls that Executing both the parsing code and the networking code on a separate thread allows the user interface to continue to behave in a responsive fashion while the network and parsing operations are done behind the scenes, resulting in a smooth and friendly user experience. This also allows for handling of interim actions by the user, such as canceling the transfer. The following android code example how to launch a new thread that connects to a remote server, retrieves and parses some XML, and posts a response back to the UI thread to change a TextView. import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory;

new Thread() { public void run() { try { URL text = new URL( http://api.flickr.com/services/feeds/photos_public.gne? id=26648248@N04&lang=en-us&format=atom); XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance(); XmlPullParser parser = parserCreator.newPullParser(); parser.setInput(text.openStream(), null); mHandler.post(new Runnable() { public void run() { status.setText(Parsing); } }); int parserEvent = parser.getEventType(); while (parserEvent != XmlPullParser.END_DOCUMENT) { // Parsing code here parserEvent = parser.next(); } mHandler.post(new Runnable() { public void run() { status.setText(Done); } }); } catch (Exception e) { Log.e(Net, Error in network call, e); } }

}.start(); How to Retrieving Android Network Status In This Android Tutorials How to retrieving android network status The Android SDK provides utilities for gathering information about the current state of the network. This is useful to determine if a network connection is even available before trying to use a network resource. The ConnectivityManager class provides a number of methods to do this. The following code determines if the mobile (cellular) network is available and connected. In addition, it determines the same for the Wi-Fi network. First, an instance of the ConnectivityManager object is retrieved with a call to the getSystemService() method, available as part of your application Context. ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVI CE); Then this instance retrieves NetworkInfo objects for both TYPE_WIFI and TYPE_MOBILE (for the cellular network). NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); These objects are queried for their availability but can also be queried at a more detailed status level to learn exactly what state of connection (or disconnection) the network is in. boolean isWifiAvail = ni.isAvailable();boolean isWifiConn = ni.isConnected(); ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isMobileAvail = ni.isAvailable(); boolean isMobileConn = ni.isConnected(); status.setText(WiFinAvail = + isWifiAvail + nConn = + isWifiConn + nMobilenAvail = + isMobileAvail + nConn = + isMobileConn); If the network is available, this does not necessarily mean the server that the network resource is on is available. Call to the ConnectivityManager method requestRouteToHost() can answer this question. This way, the application can give the user better feedback when there are network problems. For your application to read the status of the network, it needs explicit permission in itsAndroidManifest.xml file.

<usespermissionandroid:name=android.permission.ACCESS_NETWORK_STATE/> Displaying Image from Network Resource in Android In these android tutorials you have learns how to displaying image from network resource. Now that we have covered how you can use a separate thread to parse XML, lets take our example a bit deeper and talk about working with nonprimitive data types. Continuing with the previous example of parsing for image locations from a flickr feed, lets display some images from the feed. The following example reads the image data and displays it on the screen, demonstrating another way you can use network resources. import java.io.InputStream; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.os.Handler; // final String imageSrc = parser.getAttributeValue(null, href); final String currentTitle = new String(title); imageThread.queueEvent(new Runnable() { public void run() { InputStream bmis; try { bmis = new URL(imageSrc).openStream(); final Drawable image = new BitmapDrawable( BitmapFactory.decodeStream(bmis)); mHandler.post(new Runnable() { public void run() { imageSwitcher.setImageDrawable(image); info.setText(currentTitle); } }); } catch (Exception e) {

Log.e(Net, Failed to grab image, e); } } }); In this networking example, a new URL object is created and an InputStream retrieved from it. You need a Drawable object to assign to the ImageSwitcher. Then you use theBitmapFactory.decodeStream() method, which takes an InputStream. Finally, from this Runnable object, which runs on a separate queuing thread, spacing out image drawing, another anonymous Runnable object posts back to the main thread to actually update the ImageSwitcher with the new image. This is to be expected on current mobile devices because most have only a single thread of execution available for applications. You need to use careful design to provide a reasonably smooth and responsive experience to the user. Simple Android Webview Example Code In this android tutorial how to open any URL inside the application and clicking on any link from that URL should not open Native browser but that URL should open the same screen. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name as WebViewExample. Project name: WebViewExample Build Target: Android 2.2 Application name: WebViewExample Package name: com.theandroid.in Min SDK Version: 8 Out Put of this Android Application: Now open your main.xml under res -> layout folder and type the following code. <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:id=@+id/LinearLayout01? android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=vertical android:gravity=center android:padding=10px> <WebView android:id=@+id/webView android:layout_width=fill_parent

android:layout_height=fill_parent /> </LinearLayout> Now we are create activities by right click on your package folder and create classes and name them as WebViewExample.java. Type the following code respectively. Right Click on package folder -> New -> Class package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class WebViewExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.main); WebView webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(http://www.google.com); webView.setWebViewClient(new HelloWebViewClient()); } } Now we are create activities by right click on your package folder and create classes and name them as HelloWebViewClient.java. Type the following code respectively. Right Click on package folder -> New -> Class package com.theandroid.in; import android.webkit.WebView; import android.webkit.WebViewClient; public class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }

Now everything is ready and before running your project make sure that you an entry of new activity name in Android Manifest .xml file. Open you AndroidManifest.xml file and modify the code as below. <?xml version=1.0? encoding=utf-8??> <manifest xmlns:android=http://schemas.android.com/apk/res/android android:versionCode=1? android:versionName=1.0? package=com.theandroid.in> <uses-sdk android:minSdkVersion=8? /> <uses-permission android:name=android.permission.INTERNET></usespermission> <application android:icon=@drawable/icon android:label=@string/app_name> <activity android:name=.WebViewExample android:label=@string/app_name> <intent-filter> <action android:name=android.intent.action.MAIN /> <category android:name=android.intent.category.LAUNCHER /> </intent-filter> </activity> </application> </manifest> How to Display HTML Content in Android In Android tutorials How to display HTML content in webview. So you can simply use the WebView control to display web content to the screen, which can think of the WebView control as a browser-like view. The WebView control uses the WebKit rendering engine to draw HTML content on the screen. You can also dynamically formulate an HTML string and load it into the WebView, using the loadData() method. It takes three arguments. String htmlData String mimeType String encoding So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name asWebViewExample.

Project name: WebViewExample Build Target: Android 2.2 Application name: WebViewExample Package name: com.theandroid.in Min SDK Version: 8 Now open your main.xml under res -> layout folder and type the following code. <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:id=@+id/LinearLayout01? android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=vertical android:gravity=center android:padding=10px> <WebView android:id=@+id/webView android:layout_width=fill_parent android:layout_height=fill_parent /> </LinearLayout> Now we are create activities by right click on your package folder and create classes and name them as WebViewExample.java. Type the following code respectively. Right Click on package folder -> New -> Class package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class WebViewExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true);

String customHtml = <html><body><h1>Hello, WebView Demo </h1></body></html>; webView.loadData(customHtml, text/html, UTF-8?); } } Now you can also create your custom HTML file and save it in assets folder, you can also load it into the WebView using the loadUrl() method. First of all you create a test.html file and save it into assets folder. <html> <Body bgcolor=yellow> <H1>Hello HTML</H1> <font color=red>WebView Example by Android Devloper</font> </Body> </html> Now we are create activities by right click on your package folder and create classes and name them as WebViewExample.java. Type the following code respectively. Right Click on package folder -> New -> Class package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class WebViewExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(file:///android_asset/test.html); } } Simple Calculator In Android Source Code

In this Android tutorial you can learn how to make simple calculator in android application. In this application four simple operation performed like that addition, subtraction, multiple and last division. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name as ReadActivity. Project name: CalcDemo Build Target: Android 2.2 Application name: CalcDemoActivity Package name: com.theandroid.in Min SDK Version: 8 Now open your main.xml under res -> layout folder and type the following code. main.xml <?xml version=1.0? encoding=utf-8??> <RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width=fill_parent android:layout_height=fill_parent android:background=#FFFFFF> <EditText android:id=@+id/txtResultId android:layout_width=fill_parent android:layout_height=wrap_content android:editable=false android:gravity=right /> <TableLayout android:id=@+id/tableId android:layout_width=fill_parent android:layout_height=wrap_content android:layout_below=@id/txtResultId > <TableRow> <Button android:id=@+id/btnNum7Id android:text=7? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button

android:id=@+id/btnNum8Id android:text=8? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnNum9Id android:text=9? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnDivId android:text= android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> </TableRow> <TableRow> <Button android:id=@+id/btnNum4Id android:text=4? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnNum5Id android:text=5? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnNum6Id android:text=6? android:layout_width=fill_parent android:layout_height=wrap_content

android:layout_weight=1? /> <Button android:id=@+id/btnMulId android:text= android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> </TableRow> <TableRow> <Button android:id=@+id/btnNum1Id android:text=1? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnNum2Id android:text=2? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnNum3Id android:text=3? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnSubId android:text=- android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> </TableRow> <TableRow> <Button

android:id=@+id/btnNum0Id android:text=0? android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnClearId android:text=C android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnEqualId android:text== android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> <Button android:id=@+id/btnAddId android:text=+ android:layout_width=fill_parent android:layout_height=wrap_content android:layout_weight=1? /> </TableRow> </TableLayout> </RelativeLayout> Now we are creating activities by right click on your package folder and create classes and name them as CalcDemoActivity.java. Type the following code respectively. Right Click on package folder -> New -> Class CalcDemoActivity.java package com.theandroid.in; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;

import android.widget.EditText; public class CalcDemoActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ private EditText txtResult; private int result = 0; private String inStr = 0?; private char lastOperator = ; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtResult = (EditText)findViewById(R.id.txtResultId); txtResult.setText(0?); ((Button)findViewById(R.id.btnNum0Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum1Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum2Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum3Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum4Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum5Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum6Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum7Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum8Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnNum9Id)).setOnClickListener(this); ((Button)findViewById(R.id.btnAddId)).setOnClickListener(this); ((Button)findViewById(R.id.btnSubId)).setOnClickListener(this); ((Button)findViewById(R.id.btnMulId)).setOnClickListener(this); ((Button)findViewById(R.id.btnDivId)).setOnClickListener(this); ((Button)findViewById(R.id.btnClearId)).setOnClickListener(this); ((Button)findViewById(R.id.btnEqualId)).setOnClickListener(this); } // On-click event handler for all the buttons public void onClick(View view) { switch (view.getId()) { // Number buttons: 0' to 9' case R.id.btnNum0Id: case R.id.btnNum1Id: case R.id.btnNum2Id:

case R.id.btnNum3Id: case R.id.btnNum4Id: case R.id.btnNum5Id: case R.id.btnNum6Id: case R.id.btnNum7Id: case R.id.btnNum8Id: case R.id.btnNum9Id: String inDigit = ((Button)view).getText().toString(); if (inStr.equals(0?)) { inStr = inDigit; // no leading zero } else { inStr += inDigit; // accumulate input digit } txtResult.setText(inStr); // Clear buffer if last operator is = if (lastOperator == =) { result = 0; lastOperator = ; } break; // Operator buttons: +, -, *, / and = case R.id.btnAddId: compute(); lastOperator = +; break; case R.id.btnSubId: compute(); lastOperator = -; break; case R.id.btnMulId: compute(); lastOperator = *; break; case R.id.btnDivId: compute(); lastOperator = /;

break; case R.id.btnEqualId: compute(); lastOperator = =; break; // Clear button case R.id.btnClearId: result = 0; inStr = 0?; lastOperator = ; txtResult.setText(0?); break; } } private void compute() { int inNum = Integer.parseInt(inStr); inStr = 0?; if (lastOperator == ) { result = inNum; } else if (lastOperator == +) { result += inNum; } else if (lastOperator == -) { result -= inNum; } else if (lastOperator == *) { result *= inNum; } else if (lastOperator == /) { result /= inNum; } else if (lastOperator == =) { // Keep the result for the next operation } txtResult.setText(String.valueOf(result)); } } How to capture Image From Camera in Android

In this android tutorials you can learn how to capturing still images using the camera API. So android application Camera object (android.hardware.Camera) controls the camera on handsets that have camera support enabled. The preview feature of the camera relies on the assignment of a SurfaceHolder of an appropriate type. This enables applications to control the placement and size of the preview area that the camera can use. Follow these steps to add camera capture capability to an application without having to draw preview frames (the CameraSurfaceView displays the camera view). Create a new class extending SurfaceView and implement SurfaceHolder.Callback. For this example,we name this class CameraSurfaceView. In the surfaceCreated() method, get an instance of the Camera object. In the surfaceChanged() method, configure and apply the Camera.Parameters; then call thestartPreview() method. Add a method in CameraSurfaceView for capturing images. Add the CameraSurfaceView to an appropriate layout. Include some way, such as a button, for the user to trigger the capturing of images. Implement a PictureCallback class to handle storing of the captured image. Add the android.permission.CAMERA permission to the AndroidManifest.xml file. Release the Camera object in the surfaceDestroyed() method. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name as CamaraView. Project name: CameraExample Build Target: Android 2.2 Application name: CamaraView Package name: com.theandroid.in Min SDK Version: 8 Now open your main.xml under res -> layout folder and type the following code. main.xml <?xml version=1.0? encoding=utf-8??> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=vertical <SurfaceView android:id=@+id/surface_camera android:layout_width=fill_parent android:layout_height=10dip

android:layout_weight=1?> </SurfaceView> </LinearLayout> Now we are creating activities by right click on your package folder and create classes and name them as CamaraView.java. Type the following code respectively. Right Click on package folder -> New -> Class CamaraView.java package com.theandroid.in; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.graphics.Bitmap.CompressFormat; import android.hardware.Camera; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; public class CamaraView extends Activity implements SurfaceHolder.Callback, OnClickListener { static final int FOTO_MODE = 0; private static final String TAG = CameraTest;

Camera mCamera; boolean mPreviewRunning = false; private Context mContext = this; public void onCreate(Bundle icicle) { super.onCreate(icicle); Log.e(TAG, onCreate); Bundle extras = getIntent().getExtras(); getWindow().setFormat(PixelFormat.TRANSLUCENT); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera); mSurfaceView.setOnClickListener(this); mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() { public void onPictureTaken(byte[] imageData, Camera c) { if (imageData != null) { Intent mIntent = new Intent(); StoreByteImage(mContext, imageData, 50, ImageName); mCamera.startPreview(); setResult(FOTO_MODE, mIntent); finish(); } } }; protected void onResume() { Log.e(TAG, onResume);

super.onResume(); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } protected void onStop() { Log.e(TAG, onStop); super.onStop(); } public void surfaceCreated(SurfaceHolder holder) { Log.e(TAG, surfaceCreated); mCamera = Camera.open(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.e(TAG, surfaceChanged); // XXX stopPreview() will crash if preview is not running if (mPreviewRunning) { mCamera.stopPreview(); } Camera.Parameters p = mCamera.getParameters(); p.setPreviewSize(w, h); mCamera.setParameters(p); try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mCamera.startPreview(); mPreviewRunning = true; } public void surfaceDestroyed(SurfaceHolder holder) { Log.e(TAG, surfaceDestroyed); mCamera.stopPreview(); mPreviewRunning = false;

mCamera.release(); } private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; public void onClick(View arg0) { mCamera.takePicture(null, mPictureCallback, mPictureCallback); } public static boolean StoreByteImage(Context mContext, byte[] imageData, int quality, String expName) { File sdImageMainDirectory = new File(/sdcard); FileOutputStream fileOutputStream = null; String nameFile; try { BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length,options); fileOutputStream = new FileOutputStream( sdImageMainDirectory.toString() +/image.jpg); BufferedOutputStream bos = new BufferedOutputStream( fileOutputStream); myImage.compress(CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml <?xml version=1.0? encoding=utf-8??> <manifest xmlns:android=http://schemas.android.com/apk/res/android android:versionCode=1? android:versionName=1.0? package=com.theandroid.in> <application android:icon=@drawable/icon android:label=@string/app_name> <activity android:name=com.theandroid.in.CamaraView android:label=@string/app_name> <intent-filter> <action android:name=android.intent.action.MAIN /> <category android:name=android.intent.category.LAUNCHER /> </intent-filter> </activity> </application> <uses-permission android:name=android.permission.CAMERA></usespermission> </manifest> Video Recording Example in Android In this android tutorials how to video recording android applications can record video using the MediaRecorder class. Using MediaRecorder is a matter of following a few simple steps. Instantiate a new MediaRecorder object. Set the video source. Set the video output format. Set the video size to record (optional). Set the video frame rate (optional). Set the video encoder. Set the file to record to. (The extension must match output format.) Set the preview surface. Prepare the object for recording. Start the recording. Stop and release the recording object when finished. Using some standard button controls, you can create an Activity to record and play back video using the preceding steps. The onClick() method for a record button might look like this.

public void onClick(View v) { if (videoRecorder == null) { videoRecorder = new MediaRecorder(); } String pathForAppFiles = getFilesDir().getAbsolutePath(); pathForAppFiles += RECORDED_FILE; videoRecorder.setVideoSource( MediaRecorder.VideoSource.CAMERA); videoRecorder.setOutputFormat( MediaRecorder.OutputFormat.MPEG4 ); videoRecorder.setVideoSize(640, 480); videoRecorder.setVideoFrameRate(30); videoRecorder.setVideoEncoder( MediaRecorder.VideoEncoder.H264); videoRecorder.setOutputFile(pathForAppFiles); videoRecorder.setPreviewDisplay(surface); videoRecorder.prepare(); videoRecorder.start(); // button handling and other behavior here } The videoRecorder object is instantiated and given some video configuration values for the recording source.There are several values for each video configuration setting; however, supported values can vary by device. A stop button configured with an onClick() handler might look like this. public void onClick(View v) { if (videoRecorder!= null) { videoRecorder.stop(); videoRecorder.release(); videoRecorder = null; } // button handling and other behavior here } Finally, applications wanting to record video require the explicit permission android.permission.CAMERA set within the AndroidManifest.xml file. Now it is time to add the playback functionality, so we can watch the video we just recorded.

Audio Recording in Android Example In these Android tutorials you can learn how to audio recording in android application the Android SDK provides methods for audio playback and recording. Audio files can be resources, local files, or Uri objects to shared or network resources. Audio recording takes place through the built-in microphone on the device. The MediaRecorder object of the Android SDK provides audio recording functionality. Using it is a matter of following a few simple steps you should now find familiar: Instantiate a new MediaRecorder object. Set the audio source. Set the audio format to record with. Set the file format to store the audio in. Set the file to record to. Prepare the object for recording. Start the recording. Stop and release the recording object when finished. Using a couple simple buttons, you can create a simple Activity to record and play back audio using the preceding steps. The onClick() method for a record button might look like this. public void onClick(View v) { if (audioRecorder == null) { audioRecorder = new MediaRecorder(); } String pathForAppFiles = getFilesDir().getAbsolutePath(); pathForAppFiles += RECORDED_FILE; audioRecorder.setAudioSource( MediaRecorder.AudioSource.MIC); audioRecorder.setOutputFormat( MediaRecorder.OutputFormat.DEFAULT); audioRecorder.setAudioEncoder( MediaRecorder.AudioEncoder.DEFAULT); audioRecorder.setOutputFile(pathForAppFiles);

audioRecorder.prepare(); audioRecorder.start(); // button handling and other behavior here } The Audio Recorder object is instantiated, if necessary. The default values for the recording source and output file work fine for our purposes. Of note are the values for CAMCORDER, which uses a microphone in the direction of the camera, and various voice values that can be used to record calls and choose the proper microphone for voice recognition uses. If you find that recording does not start, check the file extension used. For instance, when using theMPEG4 container, the Android SDK requires that the file extension is .mp4; otherwise, the recording does not start. A stop button is configured with an onClick() handler that looks like this: public void onClick(View v) { if (audioRecorder != null) { audioRecorder.stop(); audioRecorder.release(); audioRecorder = null; } // button handling and other behavior here } Finally, applications wanting to record audio require the explicit permission android.permission.RECORD_AUDIO set within the AndroidManifest.xml file. Now it is time to add the playback functionality, so we can listen to the audio we just recorded. Login Application Using WebView in Android In Android tutorials create sample of login application if user enters correct username and password on successful login; go to next screen open browser with any URL. WebView : View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. So lets get started by creating a simple project by opening eclipse IDE. Login Application

Now we Start our project PassData in API DEMO is 2.2 and Level versions 8 so first of all. Import appropriate packages. View.onClickListener : Interface definition for a callback to be invoked when a view is clicked. Use onClick(View v) method to Called when a view has been clicked. create an object of Intent go to next screen open browser with any URL. Now open your main.xml under res -> layout folder and type the following code. main.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent > <TableLayout android:layout_height=wrap_content android:id=@+id/tableLayout1? android:layout_width=match_parent> <TableRow android:layout_width=match_parent android:layout_height=wrap_content android:addStatesFromChildren=true android:id=@+id/tableRow1?> <TextView android:id=@+id/txtUname android:layout_height=wrap_content android:layout_width=wrap_content android:text=User Name:></TextView> <EditText android:width=350px android:id=@+id/edtUname android:layout_height=wrap_content android:layout_width=match_parent>

</EditText> </TableRow> <TableRow android:layout_width=match_parent android:layout_height=wrap_content android:addStatesFromChildren=true android:id=@+id/tableRow1?> <TextView android:id=@+id/txtPwd android:layout_height=wrap_content android:layout_width=wrap_content android:text=Password:></TextView> <EditText android:inputType=textPassword android:id=@+id/edtPwd android:layout_width=match_parent android:layout_height=wrap_content> </EditText> </TableRow> </TableLayout> <Button android:layout_height=wrap_content android:text=Login android:layout_width=wrap_content android:id=@+id/btnLogin android:layout_gravity=center> </Button> </LinearLayout> main2.xml <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/androidandroid:orientation= vertical

android:layout_width=fill_parent android:layout_height=fill_parent > <FrameLayout android:layout_weight=1? android:id=@+id/frameLayout1? android:layout_gravity=center_horizontal android:layout_width=wrap_content android:layout_height=wrap_content> <WebView android:id=@+id/webView android:layout_width=fill_parent android:layout_height=fill_parent /> </FrameLayout> </LinearLayout> Now we need 4 activities by right click on your package folder and create classes and name them asPassDataActivity.java and Activity2.java. Type the following code respectively. PassDataActivity.java package com.theandroid.in;import android.app.Activity;import android.content.Intent;import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class PassDataActivity extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b= (Button) findViewById(R.id.btnLogin);

b.setOnClickListener(this); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent i = new Intent(this, Activity2.class); EditText t1= (EditText) findViewById(R.id.edtUname); EditText t2= (EditText) findViewById(R.id.edtPwd); String s1= t1.getText().toString(); String s2= t2.getText().toString(); if(s1.equals(xyz) && s2.equals(abc)) { i.putExtra(Param, s1); startActivity(i); } else { Toast t= Toast.makeText(this, Invalid UserName or Password.., Toast.LENGTH_LONG); t.show(); } } } Activity2,java packagecom.theandroid.in; importandroid.app.Activity; importandroid.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; public class Activity2 extends Activity implements OnClickListener {

protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main2); Intent i= getIntent(); String str=i.getStringExtra(Param); WebView webView = (WebView) findViewById(R.id.webView); webView.loadUrl(http://www.google.com); } } } Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below. <?xml version=1.0? encoding=utf-8??><manifest xmlns:android=http://schemas.android.com/apk/res/androidpackage=com.thean droid.in android:versionCode=1? android:versionName=1.0?> <uses-sdk android:minSdkVersion=8? /> <uses-permission android:name=android.permission.INTERNET></usespermission> <application android:icon=@drawable/icon android:label=@string/app_name> <activity android:name=.PassDataActivity android:label=@string/app_name> <intent-filter> <action android:name=android.intent.action.MAIN /> <category android:name=android.intent.category.LAUNCHER /> </intent-filter> </activity> <activity android:name=Activity2?></activity> </application>

</manifest> Spinner in Android Example In this Android Tutorial, we will create a simple spinner widget that an item from desired items. Spinner is a widget similar to a drop-down list for selecting items. A view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view. So lets get started by creating a simple project by opening eclipse IDE. Create a new project File -> New -> Android Project and give activity name asSpinnerDemoActivity Project name: SpinnerDemoActivity Build Target: Android 2.2 Application name: SpinnerDemo Package name: com.theandroid.in Min SDK Version: 8 Now open your main.xml under res -> layout folder and type the following code. <?xml version=1.0? encoding=utf-8??><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width=fill_parent android:layout_height=fill_parent android:orientation=vertical > <TextView android:layout_width=fill_parent android:layout_height=wrap_content android:text=@string/hello /> <Spinner android:layout_height=wrap_content android:id=@+id/spinner1? android:layout_width=match_parent> </Spinner> </LinearLayout> Now we are create activities by right click on your package folder and create classes and name them as ReadContactActivity.java. Type the following code respectively.

Right Click on package folder -> New -> Class packagecom.theandroid.in;import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class SpinnerDemoActivity extends Activity { /** Called when the activity is first created. */ private static final String[] nameOfTheMonth = {Jan,Feb,march,April, May,Jun,july,Aug, Sept,Oct,Nov,Dec}; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner sp = (Spinner)findViewById(R.id.spinner1); ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_i tem,nameOfTheMonth); sp.setAdapter(adapter); } } Loan Calculator in Android This example is a simple loan calculator application which shows monthly payment and total loan of the values entered. Algorithm: 1.) Create a new project by File-> New -> Android Project name it LoanCalculator. 2.) Write following into main.xml: <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1" android:shrinkColumns="1">

<TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/loan_amount_prompt" android:gravity="right"/> <EditText android:id="@+id/loan_amount" android:inputType="numberDecimal" android:layout_height="wrap_content"> <requestFocus></requestFocus> </EditText> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/interest_rate_prompt" android:gravity="right"/> <EditText android:id="@+id/interest_rate" android:inputType="numberDecimal" android:layout_height="wrap_content"/> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/loan_period_prompt" android:gravity="right"/> <EditText android:id="@+id/loan_period" android:inputType="number" android:layout_height="wrap_content"/> </TableRow> <TableRow> <Button android:text="@string/loan_button_text" android:layout_span="2"

android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="showLoanPayments"/> </TableRow> <TableRow android:layout_marginTop="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/monthly_payment_prompt" android:gravity="right"/> <TextView android:id="@+id/monthly_payment_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:gravity="left"/> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/total_payments_prompt" android:gravity="right"/> <TextView android:id="@+id/total_payments_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:gravity="left"/> </TableRow> </TableLayout> 3.) Write following into values/strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LoanCalculator</string>

<string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="loan_amount_prompt">Loan amount:&#160;&#160;</string> <string name="interest_rate_prompt">Interest rate:&#160;&#160;</string> <string name="loan_period_prompt">Months:&#160;&#160;</string> <string name="loan_button_text">Calculate Payments</string> <string name="monthly_payment_prompt">Monthly payment:&#160;&#160;</string> <string name="total_payments_prompt">Total payments:&#160;&#160;</string> </resources> 4.) Run for output. Steps: 1.) Create a project named LoanCalculator and set the information as stated in the image. Build Target: Android 4.0 Application Name: LoanCalculator Package Name: com. example. LoanCalculator Activity Name: LoanCalculatorActivity Min SDK Version: 2.2 2.) Open LoanCalculatorActivity.java file and write following code there: package com.example.loancalculator; import java.text.DecimalFormat; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class LoanCalculatorActivity extends Activity { private EditText mLoanAmount, mInterestRate, mLoanPeriod; private TextView mMontlyPaymentResult, mTotalPaymentsResult; /** Initializes the app when it is first created. */ @Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.main); mLoanAmount = (EditText)findViewById(R.id.loan_amount); mInterestRate = (EditText)findViewById(R.id.interest_rate); mLoanPeriod = (EditText)findViewById(R.id.loan_period); mMontlyPaymentResult = (TextView)findViewById(R.id.monthly_payment_result); mTotalPaymentsResult = (TextView)findViewById(R.id.total_payments_result); } public void showLoanPayments(View clickedButton) { double loanAmount = Integer.parseInt(mLoanAmount.getText().toString()); double interestRate = (Integer.parseInt(mInterestRate.getText().toString())); double loanPeriod = Integer.parseInt(mLoanPeriod.getText().toString()); double r = interestRate/1200; double r1 = Math.pow(r+1,loanPeriod); double monthlyPayment = (double) ((r+(r/(r1-1))) * loanAmount); double totalPayment = monthlyPayment * loanPeriod; mMontlyPaymentResult.setText(new DecimalFormat("##.##").format(monthlyPayment)); mTotalPaymentsResult.setText(new DecimalFormat("##.##").format(totalPayment)); } } SplitTouch Example in Android programming This example shows two menus one for movies and other for actors. The Movie option shows a list of movies. The user can select one movie and some info can be shown to user about that movie on a dialog box, similarly the actor menu choice will list some actors and actresses and selecting will show mini bio data on a dialog box. Algorithm:

1.) Create a new project by File-> New -> Android Project name it SplitTouchExample. 2.) Write following into main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:splitMotionEvents="true"> <ListView android:id="@+id/list1" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> <ListView android:id="@+id/list2" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> </LinearLayout> 3.) Create and write following into res/layout/simple_list_item_1.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceListItemSmall" android:gravity="center_vertical" android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" android:paddingRight="?android:attr/listPreferredItemPaddingRight"

android:minHeight="?android:attr/listPreferredItemHeightSmall" /> 4.) Create and write following into res/values/arrays.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="actor_responses"> <item>Sylvester Gardenzio Stallone ( born July 6, 1946), commonly known as Sylvester Stallone, and nicknamed Sly Stallone, is an American actor, filmmaker, screenwriter, film director and occasional painter.Stallone is known for his machismo and Hollywood action roles. </item> <item>Aamir Khan (born March 14, 1965) is an Indian film actor, director, and producer who has established himself as one of the leading actors of Hindi cinema.</item> <item>Kareena Kapoor (born on 21 September 1980),often informally referred to as Bebo, is an Indian actress who appears in Bollywood films.</item> <item>Salman Khan (born on 27 December 1965) is an Indian film actor. He has starred in more than 80 Hindi films.</item> <item>Priyanka Chopra (born 18 July 1982)is an Indian actress, singersongwriter and former Miss World. Before starting her acting career, she worked as a model and gained fame after winning the Miss World title in 2000.</item> </string-array> <string-array name="movie_responses"> <item>A romantic story about a hilarious and dramatic summer in the lives of three strangers in London who inadvertently become best friends and start living together. Everything seems to be perfect until love comes to town. It is a contemporary story about the interplay between friendship and more.</item> <item>Players is a 2012 Indian action thriller heist film directed by duo Abbas-Mustan and jointly produced by Viacom 18 Motion Pictures and Burmawala Partners. The film has an all-star ensemble cast, featuring Abhishek Bachchan, Sonam Kapoor, Neil Nitin Mukesh, Bipasha Basu, Bobby Deol, Sikander Kher and Omi Vaidya in the lead roles, while Aftab Shivdasani appears in a cameo.</item> <item>Over the Top is a 1987 action drama film starring Sylvester Stallone. It was produced and directed by Menahem Golan, and its screenplay was written by Stirling Silliphant and Stallone. The original music score was composed by Giorgio Moroder.</item>

<item>Rocky is a boxing saga of popular films all written by and starring Sylvester Stallone, who plays the character Rocky Balboa. The films are, by order of release date: Rocky (1976), Rocky II (1979), Rocky III (1982), Rocky IV (1985), Rocky V (1990) and Rocky Balboa (2006).</item> <item>Rambo is an action film series based on the David Morrell novel First Blood and starring Sylvester Stallone as John Rambo, a troubled Vietnam War veteran and former Green Beret who is skilled in many aspects of survival, weaponry, hand to hand combat and guerrilla warfare.</item> </string-array> </resources> 5.) Run for output. Steps: 1.) Create a project named SplitTouchExample and set the information as stated in the image. Build Target: Android 4.0 Application Name: SplitTouchExample Package Name: com. example. SplitTouchExample Activity Name: SplitTouchExample Min SDK Version: 11 2.) Open SplitTouchExample.java file and write following code there: package com.example.splittouchexample; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; public class SplitTouchExample extends Activity { public static final String[] sMovieStrings = { "Cocktail", "Players", "Over the Top", "Rocky", "Rambo"}; public static final String[] sActorStrings = {

"Sylvester Stallone", "Amir Khan", "Kareena Kapoor", "Salmaan Khan", "Priyanka Chopra"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView list1 = (ListView) findViewById(R.id.list1); ListView list2 = (ListView) findViewById(R.id.list2); ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, sMovieStrings); ListAdapter adapter2 = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, sActorStrings); list1.setAdapter(adapter); list2.setAdapter(adapter2); list1.setOnItemClickListener(itemClickListener); list2.setOnItemClickListener(itemClickListener2); } private final OnItemClickListener itemClickListener2 = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String[] responses = getResources().getStringArray(R.array.actor_responses); String response = responses[position]; AlertDialog.Builder dlgAlert = new AlertDialog.Builder( SplitTouchExample.this); dlgAlert.setMessage(response); dlgAlert.setTitle("Biodata"); dlgAlert.setPositiveButton("OK", null); dlgAlert.setCancelable(true); dlgAlert.create().show(); } };

private final OnItemClickListener itemClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String[] responses = getResources().getStringArray(R.array.movie_responses); String response = responses[position]; AlertDialog.Builder dlgAlert = new AlertDialog.Builder( SplitTouchExample.this); dlgAlert.setMessage(response); dlgAlert.setTitle("MovieDetail"); dlgAlert.setPositiveButton("OK", null); dlgAlert.setCancelable(true); dlgAlert.create().show(); } }; } Messenger Activity in Android This example is a simple messenger activity. Algorithm: 1.) Create a new project by File-> New -> Android Project name it MessengerActivity. 2.) Write following into main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView

android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/message_prompt" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/message_field" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="@string/message_hint" > <requestFocus /> </EditText> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/add_message_button_label" android:onClick="addMessageButtonHandler" /> </LinearLayout> 3.) Write following into values/strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MessangerActivity</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_rotations_exercises">Rotations Exercises</string> <string name="message_prompt">Message:</string> <string name="font_size_prompt">Font size:</string> <string name="add_message_button_label">Add Message</string> <string name="message_hint">Your Message</string> </resources> 4.) Run for output. Steps:

1.) Create a project named MessangerActivity and set the information as stated in the image. Build Target: Android 4.0 Application Name: MessangerActivity Package Name: com. example. MessangerActivity Activity Name: MessangerActivity Min SDK Version: 2.3 2.) Open MessengerActivity.java file and write following code there: package com.example.messangeractivity; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class MessangerActivity extends Activity { private LinearLayout mMainLayout; private EditText mMessageField; private ArrayList<String> mMessages = new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mMainLayout = (LinearLayout)findViewById(R.id.mainLayout); mMessageField = (EditText)findViewById(R.id.message_field); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putStringArrayList("messages", mMessages); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mMessages = savedInstanceState.getStringArrayList("messages"); for(String message: mMessages) {

addMessage(message); } } public void addMessageButtonHandler(View clickedButton) { String message = mMessageField.getText().toString(); if (!message.isEmpty()) { mMessages.add(message); addMessage(message); } } private void addMessage(String message) { TextView textV = new TextView(this); textV.setText(message); mMainLayout.addView(textV); } } Create a Toggle Button This is a sample activity which shows How to create a Toggle Button in android. Last topic published on this forum is Read Contacts from device. Underlying Algorithm: Basic description of algorithm in step by step form: 1.) Create a Project ToggleButtonDemo. 2.) Put the following code snippet in res/layout/main.xml : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="yello" android:textOff="red"> </ToggleButton> </LinearLayout> 3.) Run the application. Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. ToggleButtonDemo. Enter following information: Project name: ToggleButtonDemo Build Target: Android APIs2.1 Application name: ToggleButtonDemo Package name: com.app.ToggleButtonDemo Create Activity: ToggleButtonDemo On Clicking Finish ToggleButtonDemo code structure is generated with the necessary Android Packages being imported along with ToggleButtonDemo.java. ToggleButtonDemo class will look like following: package com.app.ToggleButtonDemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.ToggleButton; public class ToggleButtonDemo extends Activity implements OnClickListener { ToggleButton tg; TextView tv; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv); tv.setBackgroundColor(0xfff00000); tg = (ToggleButton) findViewById(R.id.toggleButton1); tg.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub if((tg.isChecked())) { System.out.println("checked");

tv.setBackgroundColor(0xffffff00); } else { System.out.println("Unchecked"); tv.setBackgroundColor(0xfff00000); } } } Registering Broadcast Receiver in Android Programing This example will show how to register and unregister broadcast receiver programmatically. Its always suggested to register and unregister broadcast receiver programmatically as it saves system resources. Algorithm: 1.) Create a new project by File-> New -> Android Project name it BroadcastReceiverExample. 2.) Write following into main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="@dimen/padding_medium" android:text="@string/register_broadcast_receiver" android:onClick="registerBroadcastReceiver" tools:context=".RegisterUnregister" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="@dimen/padding_medium" android:text="@string/unregister_broadcast_receiver" android:onClick="unregisterBroadcastReceiver" tools:context=".RegisterUnregister" /> </LinearLayout> 3.) Create and write following into values/dimen.xml:

<resources> <dimen name="padding_small">8dp</dimen> <dimen name="padding_medium">8dp</dimen> <dimen name="padding_large">16dp</dimen> </resources> 4.) Write following into values/strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">BroadcastReceiverExample</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_enable_disable">EnableDisable</string> <string name="register_broadcast_receiver">Register Broadcast Receiver</string> <string name="unregister_broadcast_receiver">Unregister Broadcast Receiver</string> </resources> 5.) Create and write following into activity_enable_disable.xml: <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_settings" android:title="@string/menu_settings" android:orderInCategory="100" android:showAsAction="never" /> </menu> 6.) Create and write following into src/UserDefinedBroadcastReceiver.java: package com.example.broadcastreceiverexample; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast;

public class UserDefinedBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //You can do the processing here update the widget/remote views. StringBuilder msgStr = new StringBuilder("Current time : "); Format formatter = new SimpleDateFormat("hh:mm:ss a"); msgStr.append(formatter.format(new Date())); Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show(); } } 7.) Run for output. Steps: 1.) Create a project named BroadcastReceiverExample and set the information as stated in the image. Build Target: Android 4.0 Application Name: BroadcastReceiverExample Package Name: com. example. BroadcastReceiverExample Activity Name: BroadcastReceiverExample Min SDK Version: 2.2 2.) Open BroadcastReceiverExample.java file and write following code there: package com.example.broadcastreceiverexample; import android.app.Activity; import android.content.IntentFilter; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Toast; public class BroadcastReceiverExample extends Activity { UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver(); @Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_enable_disable, menu); return true; } /** * This method enables the Broadcast receiver for * "android.intent.action.TIME_TICK" intent. This intent get * broadcasted every minute. * * @param view */ public void registerBroadcastReceiver(View view) { this.registerReceiver(broadCastReceiver, new IntentFilter( "android.intent.action.TIME_TICK")); Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT) .show(); } /** * This method disables the Broadcast receiver * * @param view */ public void unregisterBroadcastReceiver(View view) { this.unregisterReceiver(broadCastReceiver); Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT) .show(); } }

Logcat Viewer Demo in Android Programming This application displays logcat messages into your activity. Algorithm: 1.) Create a new project by File-> New -> Android Project name it LogcatViewerDemo. 2.) Write following into main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@android:id/list"/> </LinearLayout> 3.) Create and write following into res/layout/logitem.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/txtLogString" android:layout_width="fill_parent" android:layout_height="wrap_content"/> 4.) Add following permission into your manifest file: <uses-permission android:name="android.permission.READ_LOGS" /> 5.) Run for output. Steps: 1.) Create a project named LogcatViewerDemo and set the information as stated in the image. Build Target: Android 4.0 Application Name: LogcatViewerDemo Package Name: com. example. LogcatViewerDemo Activity Name: LogcatViewerDemoActivity Min SDK Version: 2.2

2.) Open LogcatViewerDemoActivity.java file and write following code there: package com.example.logcatviewerdemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class LogcatViewerDemoActivity extends ListActivity{ private LogStringAdaptor adaptor = null; private ArrayList<String> logarray = null; private LogReaderTask logReaderTask = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); logarray = new ArrayList<String>(); adaptor = new LogStringAdaptor(this, R.id.txtLogString, logarray); setListAdapter(adaptor); logReaderTask = new LogReaderTask(); logReaderTask.execute(); } @Override protected void onDestroy() { logReaderTask.stopTask(); super.onDestroy(); }

@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); final AlertDialog.Builder builder = new AlertDialog.Builder(LogcatViewerDemoActivity.this); String text = ((String) ((TextView)v).getText()); builder.setMessage(text); builder.show(); } private int getLogColor(String type) { int color = Color.BLUE; if(type.equals("D")) { color = Color.rgb(0, 0, 200); } else if(type.equals("W")) { color = Color.rgb(128, 0, 0); } else if(type.equals("E")) { color = Color.rgb(255, 0, 0);; } else if(type.equals("I")) { color = Color.rgb(0, 128, 0);; } return color; } private class LogStringAdaptor extends ArrayAdapter<String>{ private List<String> objects = null; public LogStringAdaptor(Context context, int textviewid, List<String> objects) { super(context, textviewid, objects); this.objects = objects; } @Override

public int getCount() { return ((null != objects) ? objects.size() : 0); } @Override public long getItemId(int position) { return position; } @Override public String getItem(int position) { return ((null != objects) ? objects.get(position) : null); } public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if(null == view) { LayoutInflater vi = (LayoutInflater)LogcatViewerDemoActivity.this.getSystemService(Context.LAYO UT_INFLATER_SERVICE); view = vi.inflate(R.layout.logitem, null); } String data = objects.get(position); if(null != data) { TextView textview = (TextView)view.findViewById(R.id.txtLogString); String type = data.substring(0, 1); String line = data.substring(2); textview.setText(line); textview.setTextColor(getLogColor(type)); } return view; } } private class LogReaderTask extends AsyncTask<Void, String, Void> { private final String[] LOGCAT_CMD = new String[] { "logcat" };

private final int BUFFER_SIZE = 1024; private boolean isRunning = true; private Process logprocess = null; private BufferedReader reader = null; private String[] line = null; @Override protected Void doInBackground(Void... params) { try { logprocess = Runtime.getRuntime().exec(LOGCAT_CMD); } catch (IOException e) { e.printStackTrace(); isRunning = false; } try { reader = new BufferedReader(new InputStreamReader( logprocess.getInputStream()),BUFFER_SIZE); } catch(IllegalArgumentException e){ e.printStackTrace(); isRunning = false; } line = new String[1]; try { while(isRunning) { line[0] = reader.readLine(); publishProgress(line); } } catch (IOException e) { e.printStackTrace(); isRunning = false; } return null; } @Override protected void onCancelled() {

super.onCancelled(); } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); adaptor.add(values[0]); } public void stopTask(){ isRunning = false; logprocess.destroy(); } } }