| 20 last updates Varun Arora |
|
|
We know that all the activities in android are managed by pure java classes. Hence, the communication between activities will also be achieved with these classes by using their class objects with few additional mechanisms.
Let’s start with an android application example of data sharing. This application has two xml layouts and one string values xml file:
This layout file has one <EditText /> attribute and two <Button /> attributes with one <TextView/> attribute as listed below:
Listing 1: get.xml
[CODE]<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/etSend"
android:hint="@string/relLayout"/>
<Button
android:layout_below="@id/etSend"
android:layout_alignParentRight="true"
android:text="@string/bSend"
android:id="@+id/bSA"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bSAFR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/bSA"
android:paddingLeft="2dp"
android:text="@string/bSAFR" />
<TextView
android:layout_below="@id/bSAFR"
android:text="@string/tvSAFR"
android:id="@+id/tvGot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
[/CODE]
This layout has two <TextView/> attributes, one <RadioButtonGroup/> attribute that has three <RadioButton/> attributes, one <Button/> attribute as listed below:
Listing 2: send.xml
[CODE]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_height="wrap_content" android:text="@string/tvSend1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content" android:id="@+id/tvQ"></TextView>
<RadioGroup android:id="@+id/rgAnswers"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioButton android:text="@string/option1" android:id="@+id/rCrazy"
android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
<RadioButton android:text="@string/option2" android:id="@+id/rSexy"
android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
<RadioButton android:text="@string/option3" android:id="@+id/rBoth"
android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
</RadioGroup>
<Button android:text="@string/ret" android:id="@+id/bReturn"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<TextView android:text="@string/tvSend2" android:id="@+id/tvText"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
[/CODE]
There is one more xml file, which is string.xml. This file has all values for layout xml files string variables.
Listing 3: string.xml
[CODE]<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name = "bSAFR">StartActivityResult</string>
<string name = "relLayout">Type Something</string>
<string name = "tvSAFR">TextView</string>
<string name = "bSend">Send Data</string>
<string name = "option1">Option1</string>
<string name = "option2">Option2</string>
<string name = "option3">Option3</string>
<string name = "ret">Back</string>
<string name = "tvSend1">Umesh</string>
<string name = "tvSend2">Kushwanshi</string>
</resources>
[/CODE]
These xml layouts are being managed by two activity classes defined in two java files.
The data sharing between activities is achieved using Bundle Class of android.os package.
We have to create an instance of android.os.Bu
...
Post view interrupted. To view full content, click here
|
|
|
|
Java provides the programmer with an extensive set of core classes and interfaces to handle a wide range of network protocols. Java has classes that range from low level TCP/IP connections to ones that provide instant access to resources on the World Wide Web. In this article we will see networking concepts and the java.net package through which java supports fundamental networking concepts.
Objective:
- To understand how java support networking (the way it connect client to server)
- To create a client and server and connect them using java classes.
- To add more functionality and implement a chat application.
Common Networking Terms:
A Server is a machine that has some resources that can be shared. For example, a computing server, which provides computing capability; a print server which provides network printing facility, a disk server which provide networked disk space; and web server which stores web pages.
A Client is simply any machine that wants to use the services of a particular server. The server is a permanently available resource, while the client is free to disconnect after its job is done.
The following diagram is a simple illustration of a server serving multiple clients:
Figure 1: shows Client server communication.
Sockets:
Java programs communicate through programming abstraction called a socket. A socket represents the endpoint of a network communication. Sockets provide a simple read/write interface and hide the implementation details network and transport layer protocols. It is used to indicate one of the client wishes to make connection to a server, it will create a socket at its end of the communication link.
Ports:
A port number identifies a specific application running in the machine. A port is a number in the range 165535. It is a transport layer address used by TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) to handle communication between applications. For example, an email application on one machine wants to communicate with an email application on another machine. The machines are identified by the IP address but the email applications are identified by the port number at which they communicate i.e. Port 25.
The JAVA.NET Package
The java.net package provides classes and interfaces for implementing network applications such as sockets, network address, Uniform Resource Locators (URLs) etc.
Java.net package contains many classes and interface but for this article will cover only those which will use in our application.
ServerSocket Class
The ServerSocket class is used to create a server that listens for incoming connections from one or more clients. A Server socket binds itself to a specific port so that clients can connect to it.
Constructors
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction:
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the basic stream classes in Java. All the other streams just add capabilities to the basics, like the ability to read a whole chunk of data at once for performance reasons (BufferedInputStream) or convert from one kind of character set to Java's native unicode (Reader), or say where the data is coming from (FileInputStream, SocketInputStream and ByteArrayInputStream, etc.)
Why we need Stream Classes?
To perform read and write operation on binary files we need a mechanism to read that binary data on file/to write binary data (i.e. in the form of byte). These classes are capable to read and write one byte on binary files. That’s why we use Stream Classes.
Figure 1: Stream Classes
Stream Classes:
Hierarchy of classes for Input and Output streams.
Here Object is the sequence of character i.e. Stream.
1. FileInputStream and FileOutputStream Classes:
FileInputStream Class:
A FileInputStream is an InputStream to obtain bytes from a file. It is used for reading inputs of raw bytes such as image data. It can read byte oriented data.
Constructor to take file for input:
[CODE]InputStream f=new FileInputStream(“C:/JavaProg/Demo”);[/CODE]
Here, f is an object of InputStream class and argument of FileInputStream is that path where our file is located.
Methods of FileInputStream:
| 1. |
Public void close () throws IOException {}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException |
...
Post view interrupted. To view full content, click here
|
|
|
|
What are Cookies?
A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information.
Why we use Cookies?
- Identifying a user during an e-commerce session: Many on-line stores use a "shopping cart" metaphor in which the user selects an item, adds it to his shopping cart, then continues shopping. Since the HTTP connection is closed after each page is sent, when the user selects a new item for his cart, how does the store know that he is the same user that put the previous item in his cart? Cookies are a good way of accomplishing this task.
- Avoiding username and password: Many large sites require we to register in order to use their services, but it is inconvenient to remember the username and password for each services. Cookies are a good alternative for low-security sites. When a user registers, a cookie is sent with a unique user ID. When the client reconnects at a later, the user ID is returned; the server looks it up, determines it belongs to a registered user, and doesn't require an explicit username and password.
- Customizing a site: Many "portal" sites let we customize the look of the main page. They use cookies to remember what we wanted, so that we get the same result next time.
Types of Cookies:
There are two types of cookies as follows:
-
Session cookies: Session cookies are stored in memory and are accessible as long as the user is using the web application. Session cookies are lost when the user exits the web application. Such cookies are identified by a session ID and are most commonly used to store details of a shopping cart.
- Persistent cookies: Persistent cookies are also known as Permanent cookies. Persistent cookies are used to store long-term information such as user preferences and user identification information. Permanent cookies are stored in persistent storage and are not lost when the user exits the application. Persistent cookies are lost when they expire.
- Sending and Receiving Cookies: To send cookies to the client, a servlet should use the Cookie constructor to create one or more cookies with designated names and values and insert the cookies into the HTTP response headers with response.addCookie.
To read incoming cookies, a servlet should call request.getCookies, which returns an array of Cookie objects corresponding to the cookies the browser has associated with our site (null if there are no cookies in the request). In most cases, the servlet should then loop down this array calling getName() on each cookie until it finds the one whose name matches the name it was searching for, then call getValue() on that Cookie to see the value associated with the name.
Sending Cookies to the Client:
Sending cookies to the client involves three steps:
- Creating a Cookie object: We call the Cookie constructor with a Cookie name and a cookie value, both of which are strings.
- Setting the maximum age: If we want the browser to store the cookie on disk instead of just keeping it in memory, we use
SetMaxAge to specify how long (in seconds) the cookie should be va
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
Button is a widget in android which is used to perform click event on the form i.e. for submitting the form data or to trigger/start some operation button is being used. There are different types of button widgets available in android they are Button, Image Button, Radio Button, Check Boxes and Toggle Button out of which radio button and checkboxes are used as selection widget i.e. they are used when we have to select from multiple options. Toggle button have two states that is on and off states, as the name indicates it toggles between two states i.e. if it is ON and we click it moves to off state and vice-a-versa. So we are left with Button and Image Button to submit the information. Almost all the property of Image Button and Button are same but the difference is that on image the click effect is visible on clicking the button, where as in normal button if we apply background to it click effect is not visible. So, in android we need to customize the button as per as the requirement of the application. In android default shape of button is rectangle, and default colour is grey which need to be changed while creating application like the shape of button need be changed to circle or oval, background colour applying images to the button and applying text with images over the button. There are different ways to customize this button. So we will see the different ways to customize the button in android.
So, let’s start the customization of button in android using images
Activity: Creating application Customization of button
Customizing button using image is the most common and general practise of customizing the button. Firstly, create a new android application in eclipse Eclipse file->New->Android Application Project. So for customising the button using image you require the image of button which you need to apply as its background. So place the images of button in res->drawable. Like in my case i have place the image name as one.png in drawable folder.
Now in your main.xml create a button and give the background property to it giving the name of image you want in its background. Like in my case it is android:background=”@drawable/one”. Below is the code snippet of main.xml with two buttons one with image and another without image.
Listing 1: xml to create a button in Android
[CODE]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/one" />
<! -- android:background property is used to apply background to a to button. And @drawable/one means there is a image name as one in your drawable folder we are applying it as background to this button. -->
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
[/CODE]
When you run your application on the emulator it following output will be generated.
Figure 1: Application running
But when you click on the button it will not display the click effect like a normal button do. So, for the user it is very difficult to find out whether the button is pressed or not and they keep on pressing the button which may crashes the application. So for creating a click effect you have to make another xml file in drawable folder. res -> drawable -> button_menu.xml.
In button_menu.xml file you have to write defi
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction:
File is a collection of bytes stored in secondary storage device i.e. disk. Thus, File handling is used to read, write, append or update a file without directly opening it.
Types of File:
Text File contains only textual data. Text files may be saved in either a plain text (.TXT) format and rich text (.RTF) format like files in our Notepad while Binary Files contains both textual data and custom binary data like font size, text color and text style etc.
Why we use File Handling?
The input and output operation that we have performed so far were done through screen and keyboard only. After the termination of program all the entered data is lost because primary memory is volatile. If the data has to be used later, then it becomes necessary to keep it in permanent storage device. So the Java language provides the concept of file through which data can be stored on the disk or secondary storage device. The stored data can be read whenever required.
Note: For handling files in java we have to import package named as java.io which contains all the required classes needed to perform input and output (I/O) in Java.
File Class in Java:
Files and directories are accessed and manipulated by the File class. The File class does not actually provide for input and output to files. It simply provides an identifier of files and directories.
Note: Always remember that just because a File object is created, it does not mean there actually exists on the disk a file with the identifier held by that File object.
For Defining a file in a File Class there are several types of constructors.
File Class constructors:
...
Post view interrupted. To view full content, click here
|
|
|
|
JavaScript is the most popular client-side scripting language and it works in the all major browser like Internet Explorer, Firefox, Chrome, Opera and Safari. JavaScript was designed to add interactivity to the web pages, it’s a simplified programming language and it’s an interpreted language that means that the browser executes the JavaScript code without pre-compiling it.
JavaScript can dynamically insert text in HTML page, can react at events like click on a button or change the selected option in a element, can read and modify the content of a HTML element, can validate the user’s input in forms and it can create cookies.
In the first example we will use two <select> element, one to select the color of the web page background and second to change the font family of the document. We will use onChange() event for each <select> element to change the background color and/or the font family for our page. This event occurs every time the user chooses a new option from the <select> element. To retrieve the chosen option we will use the property options which return an array containing all the options declared in that <select> element and the property selectedIndex which return the index of the option currently selected (indexed from 0).
Listing 1: Code for the web page
[CODE]<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>First Example</title>
</head>
<body>
<h1>Changing the background color and font family using JavaScript</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
<p id="second">
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia
consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur,
adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et
dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis
nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea
commode consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate
velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo
voluptas nulla pariatur?
</p>
<form>
<label>Select the background color</label>
<select id="colorSelection">
<option value="none"></option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<label>Select the font family</label>
<select id="fontSelection">
<option value="none"></option>
<option value="verdana">Verdana</option>
<option value="courier">Courier New</option>
<option value="arial">Arial</option>
</select>
</form>
<script>
//retrieve from document first <select> element
var colorSelection=document.getElementById("colorSelection");
//retrieve from document second <select> element
var fontSelection=document.getElementById("fontSelection");
//use onChange event for first <select> element
colorSelection.onchange=function() {
//retrieve the chosen option from first <select> element
var chosenColor=this.options[this.selectedIndex];
//change background color
switch (chosenColor.value) {
case "red":
document.bgColor="#ed1f24";
break;
case "green":
document.bgColor="#3ab449";
break;
case "blue":
document.bgColor="#29aae1";
break;
default:
document.bgcolor="#ffffff";
}
}
//using onChange event for second <select> element
fontSelection.onchange=function() {
//retrieve the chosen option from second <select> element
var chosenFont=this.options[this.selectedIndex];
//change font family
switch (chosenFont.value) {
case "verdana":
document.body.style.fontFamily="Verdana,sans-serif";
break;
case "courier":
document.body.style.fontFamily="Courier,monospace";
break;
case "arial":
document.body.style.fontFamily="Arial,sans-serif";
break;
default:
document.body.style.fontFamily="Times,serif";
}
}
</script>
</body>
</ht
...
Post view interrupted. To view full content, click here
|
|
|
|
The ADT plugin Android Development Tools gives a New Project Wizard that can help to create a new Android project.
Creating new project in Android using project wizard:
1: Select File > New > Project.
2: Select Android > Android Project, and click Next.
Figure 1: Creating Android Project
3: Select the contents for the project in next window:
Figure 2: Choosing locate
- Input a Project Name to Project Name edit field.
This will be the name of the folder where your project is created in your workspace.
- Next, select Create new project in workspace under contents. Then, select your project workspace location (Uncheck Use default location, do it just). Then, Go next.

Figure 3: Choosing SDK to target
- In Select Build Target window, select an Android target to be used as the project's Build Target.
The Build Target specifies which Android platform you'd like your application built against. Unless you know that you'll be using new APIs introduced in the latest SDK, you should select a target with the lowest platform version possible.
Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.
- Under Properties, fill in all necessary fields.
- Enter an Application name. This is the human-readable title for your application — the name that will appear on the Android device.
- Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all your source code will reside.
- Select Create Activity (optional, of course, but common) and enter a name for your main Activity class.
- Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the <uses-sdk> of your Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.
Figure 4: Application Info
4. Click Finish. New Project is created completely now.
Tip: You can also start the New Project Wizard from the New icon in the toolbar.
Once you complete the New Project Wizard, ADT creates the following folders and files in your new project automatically:
- src/: Includes your stub Activity Java file. All other Java files for your application go here.
- gen/: This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files.
- / (e.g., Android 3.2/): Includes the android.jar file that your application will build against. This is determined by the build target that you have chosen in the New Project Wizard.
- assets/: This is empty. You can use it to store raw asset files.
- bin/: This is empty. After built, binary exec file is placed here.
- res/: A folder for your application resources, such as drawable files, layout files, string values, etc.
- AndroidManifest.xml: The Android Manifest for your project.
- project.properties: This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually - to edit project properties, right-click the project folder and select "Properties".
Figure 5: Project folder
...
Post view interrupted. To view full content, click here
|
|
|
|
We will now incorporate a short sound effect to the page for some specific actions. The example here includes at the moment when the user moves the mouse cursor over a link present on the web page. With the help of the helper function, we can easily incorporate the sound effect to a link which makes relatively simple to add the sound effect to all the links present on the web page.
Follow the below steps in order to get the outcome of adding sound effects to a web page.
Figure 1: Sound Effect
Step 1
The first step is to incorporate the script mentioned below to the header section of the web page. This is then altered to the "soundfile var" so that the file of the sound can be located.
Listing 1: Adding the script to the header section of the web page
[CODE]<sound source="#" id="soundfactor" loop=n autostart="yes" />
<script type="text/javascript">
var filesound="testfile.wav " // This is a sound file path
function soundplay(filesound){
if (document.list && document.getAttributeByNumber){
document. getAttributeByNumber("soundeffect").source="" //This needs to be reset to default in case of any issues
document. getAttributeByNumber("soundeffect").source=filesound
}
}
function sound(tag, filesound, mainElement){
if (!console.event) return
var src=event.sourceAttribute
while (src!=mainElement && src.tagName!="HTML"){
if (src.tagName==tag.toUCase()){
soundplay(filesound)
break
}
src=src.mainElement
}
}
</script>
[/CODE]
Step 2
The second step now is to make the arrangement so as to make the element set and fetch the sound of JavaScript. This can be done either on the hovering of the link or it can also be done on the access of click of the link. Below code will display the sound when the user takes action on the link.
Listing 2: Elements set up for working of Sound Effect
[CODE]<a "#" Mouseover="soundplay(filesound)">Example 1</a>
<a "#" Mouseover="soundplay('testfile.wav')">Example 2</a>
[/CODE]
The above code is to make the sound file pass on the link in order to make the sound play. This is done other than the file that is being specified by default within the script.
We will now see the process to incorporate a sound to all the web elements on a particular type on the web page. With the help of the add-on function that are being included in the script, we can incorporate the effect of sound very easily to all the web elements that belong to a specified type. One category of these specific types is links that are present on the page. Assume you are willing to incorporate a sound to the links that are present in the menu of the web page. This web page consists of more than 15 links. Rather than adding the code to the entire links present on the web page, we can just define a single event of onMouseover.
Below lists the code example of the same:
Listing 3: Adding one single event to the links present on the page
[CODE]<div id="menu" Mouseover="sound('A', soundfile)">
<a "http:// www.mrbool.com/home">Home</a>
<a "http:// www.mrbool.com /channels">Channels</a>
<a "http:// www.mrbool.com/courses">Courses</a>
<a "http:// www.mrbool.com/publishpost">PublishPost</a>
<a "http://www.mrbool.com/buycredits">BuyCredits</a>
</div>[/CODE]
With the help of the above code, all the links that are inside the DIV, they will pla
...
Post view interrupted. To view full content, click here
|
|
|
|
Let us see with the help of this article whether CSS3 can be performed in Internet Explorer without the help of complex programming languages such as JavaScript. We will make use the shadowed text examples in this tutorial to solve the purpose.
We can come up with lot of shadows that can be blurred or rather not blurred shadows and that too for a single block of text. The only thing that needs to be taken care of is that we would need to make the CSS selectors set. This needs to be done within the JavaScript file. This would make the code to be written in a very easy manner and you would see that it will be utmost easy to re-factor it. This will thereby turn into a plug-in for the CSS3 library class.
All that we need to do now is to incorporate some of the important <script> tags within the head and this would make the text shadow built in CSS3 work in Internet Explorer very smoothly. Assuming that we are seeing the web page in Internet Explorer, below are the attributes that would need to be followed in order to make the page visible properly and clearly in Internet Explorer.
Below lists the attribute of different sort of text shadow build in CSS and to be executed in internet Explorer:

|
Simple 2px 0 #E51919 |
...
Post view interrupted. To view full content, click here
|
|
|
|
Making use of
HTML 5 in order to add the video to the web page of your site is not as difficult as it seems. We have majority of the browsers that hold the potential to take care of the video tagged in HTML5. However the way any browser supports the video is different from other browsers. This means that with few lines of code and saving it in the supported video format makes it pretty easy to get the video displayed in majority of the browsers. The only browser that is exception over here is Internet Explorer 8.
Below lists the HTML 5 code that will make the browsers know on the incoming of HTML5.
<!doctype html>
Listing 1: Creating the Web page
[CODE]<html>
<head>
<title>How to make a video work on web browsers - MrBool Tutorial</title>
</head>
<body>
</body>
</html>[/CODE]
Video tag needs to be placed within the body as shown below:
[CODE]<video></video>[/CODE]
The most important part is to make judgement on the attributes you want to include as a part of your video. Below lists dome of the attributes:
- Autoplay is one such attribute which needs to be initiated the time it is downloaded.
- A control is the next tag that has the capability to permit the readers so as to take control of the video. This is done by making use of pause, rewind and fast-forward elements.
- Loop is the attribute that is used to initiate the video from the very start until the video is ended.
- In order to do the pre downloading of the video which will make the video to download as soon as user accesses the video, the preload attribute is made use of.
- Next comes in the turn of poster attribute which is used to define the image that is required to be utilized at the time when video is stopped.
Below we can see some example of HTML5 Video
Figure 1: HTML5 Video Example
The recommendation is to make use of controls as well as preload attributes and when we make use of poster attribute, it means that the first scene of the video is not of the expected quality.
<controls preload></video>
The next step is to incorporate the below code within the <video> attribute.
Listing 2: Incorporating the code within video attribute
[CODE]<controls preload>
<source src="videofile.mp4" type='video/mp4; codecs="avc1.4E0, mp4a.40.2"'>
<source src="videofile.ogg" type='video/ogg; codecs="vorbis"'>
</video>[/CODE]
This is not the end of the road and requires to be validated across different browsers. The browsers include Chrome 1, Firefox 3.5, Opera 10, and/or Safari 4. So open the page in these browsers and we need to make sure that correct display is visible.
The browser that is really required to validate the above code is at least Firefox 3.5 and Safari 4. This is for the reason that these browsers tend to have a different codec.
Post making this code in place, we will get the video that will work perfect in different browsers including Firefox 3.5, Safari 4, Opera 10, and Chrome 1.
The big question here is how to make the video support in Internet Explorer since vide t
...
Post view interrupted. To view full content, click here
|
|
|
|
Let us first see what the java collections are. The framework of java collections is nothing but a group of classes as well as the interfaces which are utilized to implement reusable structures of collection data.
We all know the limitations of java arrays, one of which is that they are unable to grow dynamically, have limited sort of safety. The other could be the implementation of efficient and complex data structures which is difficult to do the same from the scratch or very beginning. Talking about the java collections framework, it is nothing but a classes set that is utilized to implement the collection data structures.
The advantages that java collections bring in are that it helps to lessen the effort that is required in programming. It helps to increase the performance as well, helps to make the software upgrade to a level where it can be reused as well and is very easy to design as well.
Introduction to Collections Interface:
The base interface that is known in the hierarchy of collections is known by the anem of java.util.Collection and represents Objects group. The types such as integer is required t be include in a collection and the collection interfaces that are more regular such as list is used to extend this interface.
Collection Iteration:
What is an iterator? It is nothing but is said to be an object which is used to iterate the objects in a collection and we can use java.util.Iterator as an interface which specifies the iterator potential or capabilities.
What happens when we invoke the iterator() method? When we invoke this method on a collection, this then comes back with an iterator object. This iterator object is used to implement the iterator and helps knowing about the steps that are required to go over the objects in the collection.
The following methods are used to specify the interfaces of iterator.
- hasNext() -This returns a true value in case we have the good number of collection elements else it will return false.
- next() - This is used to return the next collection element
- remove() -This method is used to remove the last collection element which is returned by the iterator.
The below lists the example so as to get all the collection elements printed.
Listing 1: Collection elements printed
[CODE]private static print(Collection ) {
Iterator i = i.iterator();
while (i.Next()) {
Object o = i.next();
System.out.println(c);
}
}[/CODE]
The other way to write the same is given below:
[CODE]private static print(Collection c) {
for (Iterator i = i.iterator(); i.Next(); ) {
System.out.println(i.next());
}
}[/CODE]
Let us understand with the help of code language how several methods of collections classes can be used. The different methods of collections classes comprise of add as well as copy elements and also the reverse data structures.
Listing 2: Reverse data structures
[CODE]Collection.java
import java.util.*;
import java.Collections;
public class Collection {
public static void main(String[] args) {
List list = Arrays.asList("john rob steve mark steve".split(" "));
List sublist = Arrays.asList("richard");
List searchList = Arrays.asList("steve");
System.out.println("Elements in list : " + list);
// Creating a defined list copy
Collections.copy(list, sublist);
System.out.println("copy of list : " + list);
// Finding maximum as well as minimum object value from list.
System.out.println("object of max value : " + Collections.max(list));
System.out.println("object of min value : "
...
Post view interrupted. To view full content, click here
|
|
|
|
An scroll box is a box that shows scroll bars when it's contents are too large to fit in the box. To create it, you just need to create the box using the HTML div tag. Then, to make the box scroll, you apply the CSS overflow property to that div.
Assuming we don’t have any scrolling attribute that is used, browsers will normally use the “auto” attribute.
The attribute “auto” can be used so as to make the scroll bars suppress in the web page. This is done normally by marking the value of attribute as no, else if the value is set to yes, the spaces has to be reserved for the scroll bars. This is irrespective of whether the content slides off the page or not.
Listing 1: Suppressing the scrollbar
[CODE]Scrolling auto= no | yes [/CODE]
This means that when the value is set to yes, you will be able to see the missing content in the pane. When the value is set to no, you may miss out to read some of the content that is present in the pane.
The below lists the code which is useful to distinguish between the header and main frame where we see that header frame will not lead to scroll bars. On the other hand, the main frame will make scroll bars to appear forcefully.
Listing 2: Code to differentiate between header and main frame
[CODE]
<frameset rows="125,*" >
<frame src="header " frameborder="1"
resize="resize" scrolling="no"/>
<frame src="home" frameborder="0" scrolling="yes"/>
</frameset>[/CODE]
The values can be any of the three which is yes, no or auto. All the major browsers support this functionality of creating scrollbars. Example includes version of IE 5.0 and above, Firefox 1.0 and above, Safari 1.3 and above, Opera 9.2 and above & Chrome 2.0. Each and every browser that is listed here supports this attribute.
Now suppose that we want to implement a web page in the full screen mode, it is easy to do that but we might get stuck with still the vertical scrollbar appearing on the right side. So let us understand how to overcome this issue.
You just need to use the below code however this works only in IE.
scroll="no"
The alternative is that when you are going to apply for a full screen window, we should also be looking for the normal window option. For the reason that we have the above code designed to work just in IE, we can make use of CSS method that will work in other browsers as well.
Listing 3: Using CSS method to work in different browsers
[CODE]<style type= “text:css”>
Body {overflow: hidden};
<style>[/CODE]
Let us take a look at how we can always make the vertical scrollbars appear and horizontal ones hidden.
Listing 4: Hiding vertical and horizontal scrollbars
[CODE]<div >
Figure 1: Scrollbar example
Adding colour on the scrollbars is easy and requires the below code to be implemented on the web page.
Listing 6
...
Post view interrupted. To view full content, click here
|
|
|
|
What is a generic class?
Java generic is a term that is used to denote a set of features which are related to the use of generic types and methods. A Generic class in java is nothing but an interface which one can parameterize for different types. We can follow the below format when it comes to defining a Generic class.
[CODE]Class name {/*…*/}[/CODE]
The angle bracket defined above is basically used to specify the type parameters which are also known as type variables T1, T2..Tn.
We can customize the Java classes as well since we don’t have generics just limited to the predefined classes in the Java APIs. The below is an illustration of the declaration we learned above.
Listing 1: Customizing the Java classes
[CODE]
public class Generic {
Class theClass = null;
public Generic(Class theClass) {
this.theClass = theClass;
}
public E createInstance()
throws IllegalAccessException, InstantiationException {
return (E) this.theClass.newInstance();
}
}
[/CODE]
What is <E>?
The alphabet E in the angle brackets displayed in the code above is a token that gives a hint that the class can have a type set once this is instantiated.
Let us understand the above said statement by using an example.
Listing 2: Defining type set
[CODE]
Generic = new Generic(MyClass.class);
MyClass myClassInstance = createInstance();
[/CODE]
Objective of Java Generics:
The main benefit of generic classes is that they are useful in early error detection at compile time. In order to get this benefit, we need to use a parameterized type such as LinkedList. This needs to be used in place of LinkedList and this will help the compiler to perform more type checks. This in turn requires lesser dynamic casts.
Using the above technique, it will be easier to detect the errors early since they will be reported at a compile time with the help of a compiler error message instead of getting an exception at run time.
Let us consider the example of LinkedList<String> which is used to express the homogeneous list of elements. These homogenous lists of elements are of the type String.
Listing 3: Example of a parameterized type
[CODE]LinkedList list = new LinkedList();
List.add(“abc”);
List.add(new Date());
[/CODE]
Interfaces
In assition to classesclasses, we should also be aware of another hierarchy that is known by the name of interfaces which can be seen as a class specification. This however is not considered to be an implementation.
What does the interface lists?
An interface actually lists the method descriptors and not the actual code that are required by this interface. A class can always implement an interface by providing implementation to all methods declared in the interface. It is an interesting point to note that any class can be used to implement several interfaces and the only thing that is required to make this happen is the below method.
[CODE]int compareTo(Object o) {...}[/CODE]
The advantage of using this method is that it helps the object to get compared -to other objects that are of the same type. The output of the above method could be in any form-positive, negative and even zero. This means the specified object here is either less than, greater than or equal to the object that is being passed as a parameter.
Generic type:
A generic type with fo
...
Post view interrupted. To view full content, click here
|
|
|
|
CSS3 is exciting stuff and every developer really like the drop shadow feature because of the tiresome effort to create new PNG files just to get the effect. Also, it's a pain trying to get the bottom lined up, and the right side of a div to all look right with the shadow.
Introduction to tags
Just like the CSS3 rotating text, each browser has its own tag. So, here are the tags.
Listing 1: Defining the CSS3 tags
[CODE]<br>
filter:progid:DXImageTransform.Microsoft.DropShadow(sProperties)<br>
-webkit-box-shadow: 10px 10px 25px #ccc;<br>
-moz-box-shadow: 10px 10px 25px #ccc;<br>[/CODE]
The first one, the filter is for IE (details), the webkit tag is for Chrome and Safari, and the moz-box-shadow tag is for Firefox.
The properties are pretty simple. They pretty much go as follows:
Listing 2: Properties of CSS3 tags
[CODE]<br>
-webkit-box-shadow: offsetX offsetY blurRadius color<br>
-moz-box-shadow: offsetX offsetY blurRadius color<br>[/CODE]
Use of tags in Internet Explorer
For IE, we can use a few different properties. The table below describes them
| Attribute |
Property |
Description |
...
Post view interrupted. To view full content, click here
|
|
|
|
It is possible to make a TextView scrollable without putting it in a ScrollView . We could accomplish this but we need to make some changes in the layout XML as well as in the Java code in order to have a scrollable TextBar with a ScrollBar.
Layout container for a view hierarchy that can be scrolled by the user allows it to be larger than the physical display. A Scroll View is a FrameLayout, meaning we should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects. A child that is often used is a LinearLayout in a vertical orientation, presenting a vertical array of top-level items that the user can scroll through.
We should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling. Most importantly, doing this defeats all of the important optimizations in ListView for dealing with large lists, since it effectively forces the ListView to display its entire list of items to fill up the infinite container supplied by ScrollView.
The TextView class also takes care of its own scrolling, so does not require a ScrollView. But using the two together is possible to achieve the effect of a text view within a larger container.
ScrollView only supports vertical scrolling. For horizontal scrolling, use HorizontalScrollView.
As we know, in order to make a TextView Scrollable the setMovementMethod() has to be called like below in the Java code:
Listing 1: Making the Textview scrollable
[CODE]. . .
mTxtOutput = (TextView)findViewById(R.id.txtOutput);
mTxtOutput.setMovementMethod(ScrollingMovementMethod.getInstance());
. . .[/CODE]
So, it is easy. However, there will be no scroll bar displayed. To add a scroll bar, the android:scrollbars attribute has to be set in the layout file like this:
Listing 2: Adding a scroll bar
[CODE]. . .
<textview android:id="@+id/txtOutput" android:scrollbars="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"></textview>
. . .[/CODE]
Now, this TextView is scrollable and has a (vertical) scroll bar. It must be lighter than using a ScrollView. What is irritating about this trick is that two different kinds of files must be touched. We cannot make a TextView scrollable in the layout and we cannot enable scroll bars in the java code.
Another point to note is that with this trick there will be no fading edge effect which is given when ScrollView is used.
As an appendix, here is a very simple layout code for a scrollable TextView with a vertical scroll bar (using a ScrollView):
Listing 3: Simple layout code
[CODE]
. . .
<scrollview android:layout_width="fill_parent" android:layout_height="fill_parent">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent"></textview>
</scrollview>
. . .
[/CODE]
If we design a menu for android phones we will probably reach the end of the screen before we have placed all web elements. The solution is very easy: just use a scrollbar to enable the user to scroll up and down to see everything.
To do so we have to wrap web linear layout with a ScrollView and wrap the scroll view again with a LinearLayout. Set the height to whatever we want but keep in mind that we should not use px (pixel) for that since it is an absolute value.
Listing 4: Designing a scrollbar
[CODE]
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<scrollview android:id="@+id/ScrollView01" android:layout_height="420dp" android:layout_width="fill_parent">
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
</linearlayout>
</scrollview>
</linearlayout>
[/CODE]
We used dp (Density-independent Pixels) which is an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen. So one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dpi" and "dp", though "dp" is more consistent with "sp".
Sp is like the dp unit, but it is also scaled by the user's font size preference. It is recommend we use this unit when specif
...
Post view interrupted. To view full content, click here
|
|
|
|
With HTML we can open a page in a new window by using target="_blank". The problem with this is that we have no control over the size of the new window that is opened, where it is positioned on the screen, or what browser control bars display on that window.
We can gain that control over the popup window that we are opening by using Javascript to open the new window instead of HTML. The content of the new window can either be a separate web page or can be dynamically created by the Javascript.
The window.open Javascript method is used to open a new browser window. The method takes three parameters.
- The first parameter contains the file name of the web page that is to be opened in the new window.
- The second parameter contains a name that is being assigned to the new window. If we use the same name for several different popup calls then the second and subsequent calls will not open a new popup window but will instead use the one of the same name that is already open.
- The third parameter defines the size of the window, what toolbars it is to display, and whether or not it can be resized by your visitors. In the example we have set the height of the new window to 255 pixels and the width to 250 pixels. Also no toolbars, menu bar, status bar, scrollbars, or directories will be displayed for the new window which cannot be resized by your visitors.
For most people, the main browser window is the only one they ever use or need. However, it is possible for another window to be opened up to allow you to either view another page while retaining the existing page in the main window, or to open up a remote window that can control or be controlled by the main browser window.
Another browser window can be simply opened using HTML and the TARGET attribute, either in a link or on a form:
Listing 1: Using Target Attribute
[CODE]<a ”testpage.htm” target="anotherWindowName">Open new window</a>[/CODE]
or:
[CODE]<form action="testpage.htm" target="anotherWindowName">
<input type="submit" value="Open new window">
</form>[/CODE]
As long as the TARGET attribute specifies a window name that is not already open, a new window will be created mimicing the existing window. If the window already exists, then the contents will be changed instead.
The problem with this approach is that apart from the window name there is nothing in common between the two windows. You can change the location of the new window using a similar link for form target - but that's it. Whereas using JavaScript and the window.open() method, it is possible to control the look and feel of the new window, to have control over its contents, and also to be controlled by the new window
Being a regular internet user, you might be familiar with the popup dialog windows. These are the windows that appear on the screen asking you different options or displaying information or warning messages. Popup dialog windows are child windows that are commonly used in GUI systems and User Interface designs to interact with the user.
This is done without disturbing the main application or window workflow.
The first thing you need is the basic HTML code to create a popup dialog box. Most developers normally use HTML div element to create floating dialog windows.
Figure 1: Popup dialog window.
Following is the HTML code we used here to create buttons and popup dialog windows as shown below:
Listing 2: Code for JavaScript Popup Window
[CODE]<h3>JavaScript Popup Window</h3>
<input type="button" id="btnShowSimple" value="Simple Dialog" />
<input type="button" id="btnShowModal" value="Modal Dialog" />
<br /><br />
<div id="output"></div>
<div id="overlay" class="web_dialog_overlay"></div>
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction to Class CSS Selector:
Selecting elements on the basis of their class names is a very common technique in CSS. The class selector syntax [class~="warning"] is rather complex, but there’s a simpler and shorter form for it: the class selector.
Here’s a simple example that selects all elements with a class that contains the value "warning":
Listing 1: Example with the value “warning”
[CODE]
.warning {
⋮ declarations
}
[/CODE]
This example also illustrates the use of an implied universal selector-it’s equivalent to *.warning. Note that whitespace characters can’t appear after the period, or between an element type selector, or explicit universal selector, and the period. For example, the following selector will match all p elements with a class that contains the value "warning":
Listing 2: Code defined to match all p elements
[CODE]
p.warning {
⋮ declarations
}
[/CODE]
A simple selector may contain more than one class selector and/or class selector. In such cases, the selector pattern matches elements whose class contain all the specified components.
Listing 3: Example containing all specified components
[CODE]
div.foo.bar {
⋮ declarations
}
div.foo.bar[title^="Help"] {
⋮ declarations
}
[/CODE]
The first example selector above matches div elements whose class value contains both the words "foo" and "bar". The second example selector matches div elements whose class values contain both the words "foo" and "bar", and whose title class values begin with the string "Help". To clarify further, the html that would match the above selectors could be as follows:
Listing 4: HTML with the <div< class
[CODE]
<div class="foo bar">Matches first example</div>
<div class="foo bar" title="Help">Matches second example</div>
[/CODE]
The following selector will match all p elements with a class that contains the value "intro":
Listing 5: Matching all p elements
[CODE]
p.intro {
⋮ declarations
}
[/CODE]
Browser Compatibility
| INTERNET EXPLORER |
|
|
|
FIREFOX |
|
|
|
|
...
Post view interrupted. To view full content, click here
|
|
|
|
To give users the benefit of predictive search, your application should send a query request to the Autocomplete API as the user types characters into an input box. The best way to do this is to set up a listener for the keyup event on the input box, and then to use the value of the string in the input box as the value for the input parameter in your request. You can display the results in a variety of ways, including as a list directly below the input box or on some other element in your application’s user interface.
Note: If you find that your app is reaching the usage limits for the Autocomplete API very quickly, it may be because you are sending requests too quickly. One approach is to set a timeout for the input box so that requests are made to the API when a user pauses typing, thereby reducing the number of total requests made to the service.
What is a search list?
When a user enters a query against the search, Android starts to provide list for possible search queries. This is based on what the user has entered so far.
Figure 1: Search list of the sample application
Types of list
For search list to work you need to add a content provider to your application and also to configure your application’s search meta data.
Android supports two list models:
- Your list are based on queries the user made in the past
- Your list are based on data of your application (e.g. a database)
Recent Query List
Let us see how to display recent queries as list.
Android provides the class SearchRecentListProvider which offers a complete solution for recent list where in you need to inherit from this class and to configure it within your constructor:
Listing1: Defining the class SearchRecentListProvider
[CODE]Import android.content.SearchRecentListProvider;
public class SampleRecentListProvider
extends SearchRecentListProvider {
public static final String AUTHORITY =
SampleRecentListProvider.class.getName();
public static final int MODE = DATABASE_MODE_QUERIES;
public SampleRecentListProvider() {
setupList(AUTHORITY, MODE);
}
}[/CODE]
Now your content provider is able to return all recent queries. The thing we have done so far is to configure your content provider to provide list however you also have to save the queries so that Android can display them when the user starts another search. This is done from within your search activity when it reacts to the query:
Listing2: Returning all the search results
[CODE]SearchRecentList list =
new SearchRecentList(this,
SampleRecentListProvider.AUTHORITY,
SampleRecentListProvider.MODE);
list.saveRecentQuery(query, null);[/CODE]
As you can see SearchRecentListProvider‘s saveRecentQuery method does that for you.
Next you have to add your SearchRecentListProvider subclass as a content provider within the AndroidManifest.xml file. This is not different from the configuration of any other content provider.
Listing3: Adding the SearchRecentListProvider subclass
[CODE]
[/CODE]
Finally you need to add two lines to your search configuration file to enable your recent list provider:
Listing4: Code to enable recent list provider
[CODE]Android:searchSuggestAuthority =
"com.grokkingandroid.SampleRecentListProvider"
android:searchSuggestSelection = " ?"[/CODE]
The database containing your application recent list
The SearchRecentListProvider stores the search history in a database calledlist.db within your application’s databases directory. This db stores an id, the query, a display text and the timestamp of the time the query was made.
The timestamp is needed since lists are sorted by time so that the most recent queries show up first. You should also consider clearing the search history from within your application – maybe even offering the user the possibility to do so. Clearing the history is also easily done. You simply have to call the method clearHistory() of the SearchRecentList object that you used above to save the search terms.
However in case you do not clear the history, Android will eventually do so itself. At most up to 250 search terms are kept in the database.
Applicationlication specific list
For many applications you want to customize what list to display. Most often it’s not interesting what the user has already searched for, but what you can actually provide. For this you need to implement a content provider accessing an application-specific data source.
For search to work only the query() andgetContentType() methods are of interest. Android’s search framework calls your query() method to find out about the list of your application. But to supply list you first have to know what the user has typed into the search box so far. You get this information in one of two ways:
- The URI contains the query as its last segment. This is the default
- The selection parameter contains the query. The query as part of the URI
The URI Android consists of the authority of your content provider
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction to Exception Handling
Exceptions are anomalies that occur during the normal flow of a program and prevent it from continuing. These anomalies--user, logic, or system errors--can be detected by a function. If the detecting function cannot deal with the anomaly, it "throws" an exception. A function that "handles" that kind of exception catches it.
In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program. If no user-provided exception handler is present, the compiler provides a default mechanism to terminate the program.
Exception handling is expensive compared to ordinary program flow controls, such as loops or if-statements. It is therefore better not to use the exception mechanism to deal with ordinary situations, but to reserve it for situations that are truly unusual.
Exceptions are particularly helpful in dealing with situations that cannot be handled locally. Instead of propagating error status throughout the program, you can transfer control directly to the point where the error can be handled.
For example, a function might have the job of opening a file and initializing some associated data. If the file cannot be opened or is corrupted, the function cannot do its job. However, that function might not have enough information to handle the problem. The function can throw an exception object that describes the problem, transferring control to an earlier point in the program. The exception handler might automatically try a backup file, query the user for another file to try, or shut down the program gracefully. Without exception handlers, status and data would have to be passed down and up the function call hierarchy, with status checks after every function call. With exception handlers, the flow of control is not obscured by error checking. If a function returns, the caller can be certain that it succeeded.
Exception handlers have disadvantages. If a function does not return because it, or some other function it called, threw an exception, data might be left in an inconsistent state. You need to know when an exception might be thrown, and whether the exception might have a bad effect on the program state.
Exception Handling is an important part of every C++ program. Without it programming is not only more difficult but more time consuming. These examples should make programming easier and faster for you.
Using the code
This article will focus on the three main keywords used in Exception Handling. They are: try, throw, and catch. Essentially the try block tries to execute a piece of code and when it fails, for whatever reason, it throws the error to catch where the catch block executes an alternate piece of cod
...
Post view interrupted. To view full content, click here
|
|
|
| |
|