Saturday, February 23, 2013

Android Text to speach library

Android now talks, and so can your apps. Text-to-speech can help you push your app in new directions. 

TTS=Text To Speach Library for Android  -- Comes with 1.6 API Level 4 (Also called speech synthesis)
TTS Engine supports-- English, French, German, Italian and Spanish
General code:- 
The simplest way to do so is to use the speak() method
String myText1 = "Did you sleep well?";
String myText2 = "I hope so, because it's time to wake up.";
mTts.speak(myText1, TextToSpeech.QUEUE_FLUSH, null);
mTts.speak(myText2, TextToSpeech.QUEUE_ADD, null);

Thursday, May 31, 2012

SAX vs DOM Parsers

SAX parser can get better speed. A tree-based API is centered around a tree structure and therefore provides interfaces on components of a tree (which is a DOM document) such as Document interface,Node interface, NodeList interface, Element interface, Attr interface and so on. By contrast, however, an event-based API provides interfaces on handlers. There are four handler interfaces, ContentHandler interface, DTDHandler interface, EntityResolver interface and ErrorHandler interface.
DOM parsers and SAX parsers work in different ways.

* A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document.

* A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time. * With DOM parser, method calls in client application have to be explicit and forms a kind of chain. But with SAX, some certain methods (usually overriden by the cient) will be invoked automatically (implicitly) in a way which is called "callback" when some certain events occur. These methods do not have to be called explicitly by the client, though we could call them explicitly.

Ideally a good parser should be fast (time efficient),space efficient, rich in functionality and easy to use . But in reality, none of the main parsers have all these features at the same time. For example, a DOMParser is rich in functionality (because it creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree), but it is space inefficient when the document is huge, and it takes a little bit long to learn how to work with it. A SAXParser, however, is much more space efficient in case of big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOMParser because its API is really simple. But from the functionality point of view, it provides less functions which mean that the users themselves have to take care of more, such as creating their own data structures.

SAX DOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Friday, December 9, 2011

HTML5 - LocalStorage

One of the most useful feature of HTML 5 for the mobile and web developers is Local Storage. LocalStorage is a handy API included in the "HTML5" wave that gives developers an easy to use 5MB store on an users local machine. Local Storage is simple API's developers can use to store data and use it later in an offline mode.
For example, if you are on a web page and by mistake you close it or navigate to another page while filling some useful information in the form, all the information input in the form is lost...What a bummer :(

By nature, web html pages do not persist data, it was hard to persist the information. Local Storage API's has been designed to address this issue.

Local Storage is a simple key/value dictionary with a simple API to match:
simple code snippet would look like:-
//To Save a value to localStorage
localStorage.setItem('key', 'value-to-be-saved');
//OR
localStorage.key = 'string value-to-be-saved';

//Get the value back out of localStorage
localStorage.getItem('key');
//OR
localStorage.key;

//Clear all localStorage values
localStorage.clear();


I hope above is very simple and does not need any explanation.

Difference between Local Storage and Session Storage
Joining LocalStorage in the HTML5 spec is also SessionStorage. It provides an identical API, but a different "retention policy." As the name implies, values in SessionStorage should only survive a single browser session (not server session).

How Local Storage Works

let's take a few moments and first learn how local storage actually works.

At the core, each of your pages has a reference to a global object called localStorage:
If you step inside this object, there is a defined key-value pair structure that is well designed for storing data. The way it stores the data is by neatly organizing them into rows of key/value pairs.

In the above localStorage visualization, you can see that there are three pieces of data:

firstName with a value of Vikrant
lastName with a value of Bains
location with a value of Los-Angeles

Think of each row as one contiguous piece of data made up of a key and a value. The key serves as the identifier to your data, and the value is the information associated with it.

An important thing to note is the scope of this data. The localStorage data is domain-specific where you have only one instance per domain. In other words, any data inside your localStorage object is available only when you are referring to it from a page hosted within the same domain.

Some important facts:-
1. LocalStorge values on Secure (SSL) pages are isolated
Browsers isolate LocalStorage values based on scheme + hostname + unique port (also known as an HTML5 Origin). Hostname is expected, since you don't want malicious websites to have access to other websites' LocalStorage data. But scheme (i.e. http and https)?

The result of this separation means that a value saved to LocalStorage on http://abc.com cannot be accessed by pages served from https://abc.com (and vice versa). There is some good reason for this (I suppose), especially in the case of isolating values created during a secure session from unsecured sessions. But since LocalStorage should never be a place for storing sensitive data,it makes this little strange as well...

2. SessionStorage values survive some browser restarts

SessionStorage, unlike LocalStorage, is not designed for long-term persistence of values in the user's browser. Instead, values in SessionStorage are destroyed when a browser session ends, which is usually when the browser window is closed.

There is an exception, though.

When a browser provides a "Restore Session" feature, usually designed to help users quickly recover from a browser/computer crash, values in SessionStorage will be restored, too. So while it's a new "session" on the server, from the browser's perspective, it's a continuation of a single session across a browser restart.

3. LocalStorage values created in "incognito" or Safe mode are isolated

When you fire-up a browser in private/incognito/safe mode , it will create a new, temporary database for LocalStorage values. That means anything saved to LocalStorage will be destroyed when the private browsing session is closed, making LocalStorage behave more like SessionStorage.

Additionally, since a browser's "Session Restore" feature does not re-open private mode sessions, anything created in SessionStorage will also be lost after the browser window is closed. Really, in short, any data put in Local or SessionStorage during a private browsing session will be lost as soon as the browser window is closed (intentionally or not).

4. LocalStorage quotas cannot be made bigger than 5MB

LocalStorage is not supposed to be the primary form of in-browser storage with HTML5 (IndexDB will eventually come along to provide that), but some apps may want more than the default 5MB LocalStorage provides. There is NO way to expand LocalStorage quotas.

Technically, the LocalStorage origin restriction does not block sub-domains of the same host (using the same scheme and port) from accessing the same LocalStorage object. As a result, some browsers have exposed a workaround that grants "a1.website.com" and "a2.website.com" their own 5MB LocalStorage quotas. And since both sites are on the same origin, they can access each others values.

5. LocalStorage can be used on older browsers (including IE)

Legacy browsers can use this feature as well. Fortunately, LocalStorage is incredibly well supported in Class A browsers. It's natively available in IE8+ (!), Firefox 3.5+, and Chrome 4+.

Simple self explanatory code snippets


Detecting Whether Local Storage Exists or Not
function isLocalStorageSupported {

try {

var supported = false;
if (window['localStorage'] !== null)
{

supported = true;

}
return supported;

} catch(e) {

return false;

}

}

Dealing with File Size

You have a fixed size of 5 MB for each domain your local storage is tied to. If you try to add more data even after you have exceed your quota, a QUOTA_EXCEEDED_ERR exception will be thrown.

Handling this exception is pretty straightforward:

try {

localStorage.setItem("key", "some data");

} catch (e) {

if (e == QUOTA_EXCEEDED_ERR) {

// do something nice to notify your users

}

}

All you need to do is wrap any code that tries to add more data to your localStorage into a try/catch statement. While just catching the exception will prevent users from seeing a script error, matching the exception to the QUOTA_EXCEEDED_ERR exception will allow you to go one step further and let your users know why they were not able to save the data to local local storage.

Removing Data

There are two extremes to removing data from your localStorage object. You can remove everything scorched earth style, or you can selectively remove a key/value pair individually.

Because scorched earth is an awesome game, let's look at it first. To remove everything from your localStorage for your current domain, you can call the clear() method:

localStorage.clear();

This will remove all traces of any data you may have stored for this domain, so use it cautiously if you have several pages on your site that each write to the local storage independently.

To remove only select key/value entries from your local storage, you can use removeItem() and pass in the key name associated with the data you wish to remove:

localStorage.removeItem("location");

In this example, the location key and its value will be deleted while leaving all of the other data intact.

Retrieving Data

To retrieve data stored in your localStorage object, you use the getItem method:

var firstNameData = localStorage.getItem("firstName");
var lastNameData = localStorage.getItem("lastName");
var locationData = localStorage.getItem("location");

The getItem method takes only the key as an argument, and it returns the value associated with that key. If the key you pass in does not exist, a value of undefined is returned.
Note

If you don't like using the getItem or setItem methods, you can bypass them by using object notation for setting and retrieving data:

// storing data
localStorage[key] = value;
// retrieiving data
var myData = localStorage[key];

Adding Data

To add data to your local storage object, all you need is a key and a value...and the setItem method that lives on your localStorage object:

localStorage.setItem('firstName', 'Vikrant');
localStorage.setItem('lastName', 'Bains');
localStorage.setItem('location', 'Los-Angeles');

In each line, we are adding a key/value pair to our localStorage object. The setItem method takes two arguments. The first argument is the key, and the second argument is the value.

Conclusion- Local Storage is very simple to use but like any other project, careful design decisions needs to be made before implementing it. Merely simplicity of use should not be a driving factor to use this

Thursday, January 6, 2011

Monday, January 3, 2011

Testing Gigya -- Login














Click the button below to publish an Activity Feed item:

(Please make sure you are logged in to Gigya, you may log in using the Login Widget on the "Me" tab above)







Click the button below to logout from Gigya platform:

Sunday, December 19, 2010

Google Code Blog: Save the date for Google I/O 2011

Google Code Blog: Save the date for Google I/O 2011: "Google I/O just recently came to a close, but it won’t be long before we start gearing up for next year. And we’d like to make sure it’s on..."

Sunday, December 5, 2010

Non UI blocking network call / web request

Code snippet to fetche content(s) from the web without blocking the UI (runs in the background in a Thread). Once finished, it posts a Handler that is picked up by the UI as soon as possible.
It is widely used in most of commercial/production level apps

Code Snippet:-
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;

public class Iconic extends Activity {
    private String html = "";
    private Handler mHandler;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mHandler = new Handler();
        checkUpdate.start();
    }

    private Thread checkUpdate = new Thread() {
        public void run() {
            try {
                URL updateURL = new URL("http://iconic.4feets.com/update");
                URLConnection conn = updateURL.openConnection();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /* Convert the Bytes read to a String. */
                html = new String(baf.toByteArray());
                mHandler.post(showUpdate);
            } catch (Exception e) {
            }
        }
    };

    private Runnable showUpdate = new Runnable(){
           public void run(){
            Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show();
        }
    };
}