MY mENU


Thursday 27 December 2012

SQL SERVER – What is – DML, DDL, DCL and TCL – Introduction and Examples


SQL SERVER – What is – DML, DDL, DCL and TCL – Introduction and Examples

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.
Examples: SELECT, UPDATE, INSERT statements
DDL
DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.
Examples: CREATE, ALTER, DROP statements
DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.
Examples: GRANT, REVOKE statements
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.
Examples: COMMIT, ROLLBACK statements

Friday 21 December 2012

JSON Introduction

What is JSON?
  •  JSON stands for JavaScript Object Notation.
  •  JSON is lightweight text-data interchange format.
  •  JSON is language independent.
  •  JSON is "self-describing" and easy to understand.
JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

JSON format is a format similar to XML but usually it is shorter and easier to parse. Many web services now work with JSON. Using the new JSON library, you can parse and generate JSON strings easily.

Much like XML
  • JSON is plain text
  • JSON is "self-describing" (human readable)
  • JSON is hierarchical (values within values)
  • JSON can be parsed by JavaScript
  • JSON data can be transported using AJAX
Much Unlike XML
  • No end tag
  • Shorter
  • Quicker to read and write
  • Can be parsed using built-in JavaScript eval()
  • Uses arrays
  • No reserved words
Why JSON?
For AJAX applications, JSON is faster and easier than XML:
Using XML
  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
Using JSON
  • Fetch a JSON string
  • eval() the JSON string

GSM, 3G, Edge, WIFI, GPS

GSM: (Global System for Mobile Communications: originally from Groupe Spécial Mobile) is the most popular standard for mobile.


3G stands: for 3rd-generation mobile technology. The services associated with 3G provide the ability to transfer both voice data and non-voice data. 3G brings wireless transmission speeds, which allow full motion video, high-speed internet access and video-conferencing. 


Edge means: Enhanced Data rates for GSM Evolution (EDGE) is a digital mobile phone technology which acts as a bolt-on enhancement to 2G and 2.5G GPRS networks. It can carry data speeds up to 384 kbit/s in packet mode and will therefore meet the International Telecommunications Union's requirement for a 3G network.

WIFI:  wireless local area network: a local area network that uses high frequency radio signals to transmit and receive data over distances of a few hundred feet; uses ethernet protocol)

GPS: (a navigational system involving satellites and computers that can determine the latitude and longitude of a receiver on Earth by computing the time difference for signals from different satellites to reach the receiver)



Wednesday 19 December 2012

Should variables be stored in local blocks?

The use of local blocks for storing variables is unusual and therefore should be avoided, with only rare exceptions. One of these exceptions would be for debugging purposes, when you might want to declare a local instance of a global variable to test within your function. You also might want to use a local block when you want to make your program more readable in the current context.

Sometimes having the variable declared closer to where it is used makes your program more readable. However, well-written programs usually do not have to resort to declaring variables in this manner, and you should avoid using local blocks.

HTML5 Introduction

HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.

HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG).

The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.
Browser Support:

The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.

The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.
New Features: HTML5 introduces a number of new elements and attributes that helps in building a modern websites. Following are great features introduced in HTML5.
  • New Semantic Elements: These are like <"header">, <"footer">, and <"section">
  • Forms 2.0: Improvements to HTML web forms where new attributes have been introduced for <"input"> tag.
  • Persistent Local Storage: To achieve without resorting to third-party plugins.
  • WebSocket : A a next-generation bidirectional communication technology for web applications.
  • Server-Sent Events: HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE).
  • Canvas: This supports a two-dimensional drawing surface that you can program with JavaScript.
  • Audio & Video: You can embed audio or video on your web pages without resorting to third-party plugins.
  • Geolocation: Now visitors can choose to share their physical location with your web application.
  • Microdata: This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics.
  • Drag and drop: Drag and drop the items from one location to another location on a the same webpage.
  • Backward Compatibility
HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers.

It is suggested to detect support for individual HTML5 features using a few lines of JavaScript.

Monday 17 December 2012

What is jQuery?


jQuery is a lightweight, "write less, do more", JavaScript library.The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that requires many lines of JavaScript code to accomplish, and wraps it into methods that you can call with a single line of code. jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. The jQuery library contains the following features:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

Friday 7 December 2012

POPUP Boxes in JavaScript

A popup box that displays a message, along with an "OK" button. Depending on the popup box, it might also have a "Cancel" button, and you might also be prompted to enter some text. These are all built into JavaScript and are what I call "JavaScript popup boxes". They can also referred to as "dialog boxes", "JavaScript dialog" , "popup dialog" etc.

ALERT BOX:

  • The syntax for an alert box is: alert("yourtext");
  • The user will need to click "OK" to proceed. 
  • Typical use is when you want to make sure information comes through to the user.
  • Examples could be warnings of any kind.(Typical examples are "Adult Content", or technical matters like "This site requires Shockwave Flash plug-in").


Screenshot of a JavaScript alert box


CONFIRM BOX:
  • The syntax for a confirm box is: confirm("yourtext");
  • The user needs to click either "OK" or "Cancel" to proceed.
  • Typical use is when you want the user to verify or accept something.
  • Examples could be age verification like "Confirm that you are at least 57 years old" or technical matters like "Do you have a plug-in for Shockwave Flash?"

- If the user clicks "OK", the box returns the value true.
- If the user clicks "Cancel", the box returns the value false.

Screenshot of a JavaScript confirm box




PROMPT BOX:

  • The prompt box syntax is: prompt("yourtext","defaultvalue");
  • The user must click either "OK" or "Cancel" to proceed after entering the text.
  • Typical use is when the user should input a value before entering the page.
  • Examples could be entering user's name to be stored in a cookie or entering a password or code of some kind.

- If the user clicks "OK" the prompt box returns the entry.
- If the user clicks "Cancel" the prompt box returns null.
Screenshot of a JavaScript prompt box

Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example:

Syntax Of JavaScript


Explanation of code
  • The tag Script tell the browser to expect a script in between them. You specify the language using the type attribute. The most popular scripting language on the web is JavaScript.
  • The bits that look like HTML comments tags are just that - HTML comment tags. These are optional but recommended. They tell browsers that don't support JavaScript (or with JavaScript disabled) to ignore the code in between. This prevents the code from being written out to your website users.
  • The part that writes the actual text is only 1 line (document.write("JavaScript is not Java");). This is how you write text to a web page in JavaScript. This is an example of using a JavaScript function (also known as method).

Where to put your scripts?

You can place your scripts in any of the following locations: Between the HTML document's head tags. Within the HTML document's body (i.e. between the body tags). In an external file (and link to it from your HTML document).

The location choice of head or body is very simple. If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head. If you want the script to run when the page loads, like our "Hello World!" example in the previous lesson, then you will want to place the script within the body tag.

Java Script Introduction

What is JavaScript?

JavaScript is a scripting language that enables web developers/designers to build more functional and interactive websites.

Common uses of JavaScript include:
  1. Alert messages
  2. Popup windows
  3. Dynamic dropdown menus
  4. Form validation
  5. Displaying date/time
JavaScript usually runs on the client-side (the browser's side), as opposed to server-side (on the web server). One benefit of doing this is performance. On the client side, JavaScript is loaded into the browser and can run as soon as it is called. Without running on the client side, the page would need to refresh each time you needed a script to run.
What do I need to create JavaScript?
You can create JavaScript using the same equipment you use when creating HTML. That is:
Computer, Text editor. For example, Notepad (for Windows), Pico (for Linux), or Simpletext (Mac). You could use a HTML editor if you like but it's not needed.
Web Browser. For example, Internet Explorer or Firefox. You will need to ensure JavaScript is enabled within your browser's settings (this is normally enabled by default).

Wednesday 21 November 2012

Shaking Browser Trick

This one is one of the funniest computer tricks I have learnt so far. Follow the steps below to learn this trick:

1. Copy the Java code below,

javascript:function Shw(n) {if (self.moveBy) {for (i = 35; i > 0; i--) {for (j = n; j > 0; j--) {self.moveBy(1,i);self.moveBy(i,0);self.moveBy(0,-i);self.moveBy(-i,0); } } }} Shw(6)
·
2. Paste the code in the address bar of your browser and click Enter.

You will be amazed when you see that your web browser starts shaking!

Tuesday 20 November 2012

Difference Between Kbps And KBPs

Lots of people have confusion between Kbps and KBps ,,,, Even he/she know the that Kbps means "Kilo bits per seconds" as a transfer rate.
KBps means "Kilo Bytes per second" as a transfer rate. even they are confused when they saw or listen 1mbps or 50 KBps because all data card or network provider mentions KBps or Mbps. so there's a lot difference between Kbps and KBps as i mentioned above .... :P
so

8 bits = 1 byte
256 kbps = 32 KBps
512 kbps = 64 KBps
1 mbps = 128 KBps
2 mbps = 256 KBps
now don't waste your time on calculating :P

Sunday 4 November 2012

Customize the Quick Launch Bar in Windows XP

In Windows XP, the customizable Quick Launch Bar also gives you convenient shortcuts to your favorite programs, folders, and files. The Quick Launch Bar remains accessible from most windows, so it’s a handy way to open the applications and files you use frequently.

If the Quick Launch Bar isn’t already visible to the right of the Start button , you’ll need to turn it on. To do that, right-click an open area of the taskbar. Hover your mouse pointer over Toolbars, then click Quick Launch. The Quick Launch Bar appears on your taskbar.


The Quick Launch Bar on the Windows XP taskbar

To add a program shortcut to the Quick Launch Bar, click the Start button, click All Programs, then click and drag the application you want to the Quick Launch Bar. Release the mouse button and the application’s icon appears in the Quick Launch Bar.

To add a folder or file shortcut to the Quick Launch Bar, open Windows Explorer, navigate to the folder, subfolder, or individual file you want, click and drag the folder or file you want to the Quick Launch Bar. Release the mouse button and the icon for the folder or file appears in the Quick Launch Bar.

To remove a shortcut from the Quick Launch Bar, right-click on the icon in the Quick Launch Bar of the application, folder, or file you want to remove and right-click it, click Delete, and then click Yes when asked if you’re sure you want to delete the shortcut. Note: Although the shortcut is removed from the Quick Launch Bar, the actual application, folder, or file has not been deleted from your computer.

Thursday 18 October 2012

What is a container class? What are the types of container classes?

A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

How can I handle a destructor that fails?

Write a message to a log-file. But do not throw an exception.
The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding.
During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bar e) { handler? There is no good answer -- either choice loses information.
So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.

Wednesday 17 October 2012

What is an Iterator class?

A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. Something like a pointer.

Tuesday 16 October 2012

What problem does the namespace feature solve?

Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.
namespace [identifier] { namespace-body }
A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.

Monday 15 October 2012

What is virtual function?

When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent
{
   void Show()
{
cout << "i'm parent" << endl;
}
};

class child: public parent
{
   void Show()
{
cout << "i'm child" << endl;
}
};

parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show() i

now we goto virtual world...
class parent
{
   virtual void Show()
{
cout << "i'm parent" << endl;
}
};

class child: public parent
{
   void Show()
{
cout << "i'm child" << endl;
}
};

parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show() 

When are temporary variables created by C++ compiler?

Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.
a) The actual argument is the correct type, but it isn't Lvalue
double Cube(const double & num)
{
num = num * num * num;
return num;
}
double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type
long temp = 3L;
double value = cuberoot ( temp); // long to double conversion

What is passing by reference?

Method of passing arguments to a function which takes parameter of type reference.
for example:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );

Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.

What are storage qualifiers in C++ ?

They are..
const
volatile
mutable

Const keyword indicates that memory once initialized, should not be altered by a program.
volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complier
strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

What is difference between template and macro??

There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.
If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times.
Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
for example:
Macro:
#define min(i, j) (i < j ? i : j)
template:
template
T min (T i, T j)
{
return i < j ? i : j;
}

Constructor & Destructors in C

What is constructor or ctor?
Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.

What is destructor?
Destructor usually deletes any extra resources allocated by the object.

What is default constructor?
Constructor with no arguments or all the arguments has default values.

What is copy constructor?
Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Boo Obj1(10); // calling Boo constructor
Boo Obj2(Obj1); // calling boo copy constructor
Boo Obj2 = Obj1;// calling boo copy constructor
When are copy constructors called?
Copy constructors are called in following cases:
a) when a function returns an object of that class by value
b) when the object of that class is passed by value as an argument to a function
c) when you construct an object based on another object of the same class
d) When compiler generates a temporary object

What will happen if any string in c is converted to integer explicitly?

 If we try to convert string into integer explicitly then string’s address will get stored in integer. 
int main()

 char *a="abhas";
 int b=(int)a;
 // now b will hold address of a 
}

Friday 12 October 2012

Blog Update

Hai Dear Viewers, Am added forum tab for this blog for discussions.so Please try come here for tech discussions.

Thursday 11 October 2012

Is the server or the client in control in AJAX?

With AJAX the control can be more centralized in a server-side component or a mix of client-side and server-side controllers.
  • Centralized server-side controller:In this type of architecture, the controller ensures that the data on the client and the server are synchronized.
  • Client and server-side controllers:In this type of architecture the presentation related control, event processing, page manipulation, and rendering of model data is done through Javascript on the client side.
  • The server-side: is responsible for business logic and pushing updated model data to the client.
  • Both methods are viable depending on the kind of task. However, the centralized server side controller is preferred as in the other case (Client and server-side controllers) the server might not have the knowledge of the state of the client page.

Wednesday 10 October 2012

How Ajax is different?

AJAX allows for asynchronous processing of events. This is different from the traditional sequential events that a users is used to, instead, a user can fire multiple events, each of which process executes independent of each other, enhancing the user experience. In traditional web applications, every time a user triggered an event, the request was sent to the server and the complete page was rendered again as a result of that. AJAX allows for partial page rendering which enable a user to trigger multiple events through different portions of the same web page.

Tuesday 9 October 2012

When should I use a Java applet instead of AJAX?

Scenarios to use Java applet instead of AJAX:
  • When there is a need for custom data streaming
  • Need for graphic manipulation
  • Threading related functionality
  • Complex and advanced GUI manipulations.
  • Applets provide features like custom data streaming, graphic manipulation, threading, and advanced GUIs which AJAX cannot.
  • However, with the help of DHTML, the functionalities of AJAX can be extended further.
  • AJAX requires that the browser be DHTML and AJAX capable.
  • AJAX-based functionality does need to take browser differences into consideration due to which using a JavaScript library such as Dojo which abstracts browser differences is recommended.
  • AJAX/DHTML works well for applications where the latest browsers are used.

Monday 8 October 2012

How is encoding handled in AJAX?

Ways to handle encoding in AJAX:
  • Using encodeActionURL() method to refresh the complete page
  • Using encodeResourceURL() method to partially update a page.


Sunday 7 October 2012

Why is AJAX a comfortable fit with JAVA?

AJAX is a comfortable fit because, using Java Enterprise Edition the following tasks can be performed:
  • AJAX client pages can be generated to server incoming AJAX requests
  • Server side state is managed for AJAX clients
  • AJAX clients can be connected to enterprise resources.

Saturday 6 October 2012

What is the disadvantage of AJAX?

The disadvantages of AJAX are:
  • Search engines would not be able to index an AJAX application.
  • The server information can not be accessed within AJAX.
  • AJAX is not well integrated with any browser.
  • ActiveX requests are enabled only in IE 5 and IE6
  • Data of all requests is URL-encoded, which increases the size of the request.

Friday 5 October 2012

Won't my server-side framework provide me with AJAX?

You may be benefiting from AJAX already. Many existing Java based frameworks already have some level of AJAX interactions and new frameworks and component libraries are being developed to provide better AJAX support. I won't list all the Java frameworks that use AJAX here, out of fear of missing someone, but you can find a good list at www.ajaxpatterns.org/Java_Ajax_Frameworks. If you have not chosen a framework yet it is recommended you consider using JavaServer Faces or a JavaServer Faces based framework. JavaServer Faces components can be created and used to abstract many of the details of generating JavaScript, AJAX interactions, and DHTML processing and thus enable simple AJAX used by JSF application developer and as plug-ins in JSF compatible IDE's, such as Sun Java Studio Creator.

Thursday 4 October 2012

Who’s Using Ajax ?

Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year — Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps — are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques. 

These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn’t another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.

At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is only going to grow. And because there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google’s lead in reaping the competitive advantage Ajax provides.
Moving Forward

The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities

Strings in Android

What is a String? 

At the most fundamental level, Java programs are broken into functionality and data. Much human-readable data comes in the forms of words, characters, punctuation, numbers and so on. Basically, anything the user can type on a keyboard. Programmers call this storage of textual content “string data”, but the data itself can be stored using a variety of different data structures, depending on your requirements:

· The Java String class (java.lang.String) is a utility class for storing string data that will not be modified.

· The Java StringBuilder class (java.lang.StringBuilder) is a utility class for storing string data that will be modified; used when concurrency is not an issue.

· The Java StringBuffer class (java.lang.StringBuffer) is a utility class for storing string data that will be modified; used when concurrency is an issue.

· An array of char primitives or Character (java.lang.Character) variables

· An array of byte primitives or Byte (java.lang.Byte) variables

· Various other data structures and object classes can be used to store string data

As you can see, there are numerous ways to store string data in Java. For example, the following Java variables represent a string of vowel characters in different ways (as bytes, characters, Unicode representations or sub-strings):

 String strVowels = "aeiou";
char astrVowels[] = { 'a', 'e', 'i', 'o', 'u' };
 byte abyteVowels[] = { 'a', 'e', 'i', 'o', 'u' };
byte abyteVowelsU[] = { '\u0061', '\u0065','\u0069','\u006F','\u0075' };
 String uVowels = new String("\u0061\u0065\u0069\u006F\u0075");
 CharSequence csVowels = (CharSequence) new String("aeiou");
 StringBuffer sbVowels = new StringBuffer("a" + "e" + "iou");
 StringBuilder sVowelBuilder = new StringBuilder();
 sVowelBuilder.append('a');
 sVowelBuilder.append("eio");
 sVowelBuilder.append('\u0075');

The String class is the convenience class used most often, especially by beginners. You’ll also want to have a passing understanding of the CharSequence (java.lang.CharSequence) interface, as it is often used when working with Android resources.

Working with the String Class

The String class is available as part of the java.lang package, which is included within the Android SDK for developers to use. The complete documentation for the String class can be found with the Android SDK documentation.

The String class represents an immutable (unchangeable) sequence of Unicode (16-bit encoding) characters, appropriate for storing characters in any language (English, German, Japanese, and so on).

So what does this have to do with Android development? Well, strings are used to store content displayed on application screens, or to store the input taken in from a user. Android developers are constantly loading, creating, and manipulating string data. So let’s look at some of the stuff we can do with the String class.

Creating Strings

The String class has numerous constructors, for creating and instantiating string variables. String variables can be set to empty using the null keyword. You can also set its content from byte, character, or other String data. For example, here are some ways to create String variables for use within your applications (some are initialized from the variables, like uVowels and sVowelBuilder, defined earlier in this tutorial):

String strVowels1 = "aeiou";
 String strVowels2 = new String("aeiou");
 String strVowels3 = new String(sVowelBuilder);
 String strVowels4 = new String(sbVowels);
 String strVowels5 = new String(uVowels);
 String strVowels6 = new String(abyteVowels2);
 String strVowels7 = new String(abyteVowelsU);
 String strVowels8 = new String("a" + "e" + "iou");
 String strVowels9 = new String( new char[]{'\u0061', '\u0065','\u0069','\u006F','\u0075'});
 String strVowels10 = new String(new byte[]{ '\u0061','\u0065','\u0069','\u006F','\u0075' });

Using Android String Resources

You can also load strings from Android application resources, provided you have stored them correctly. For example, you can load the string resource for the application name into a String variable as follows:

String strAppName = getResources().getString(R.string.app_name);

This requires that the Android application in question contains a string resource named app_name somewhere in the /res/values project directory hierarchy. For example, a file called /res/values/strings.xml which contains the following XML string definition:


 
 My Android App Name!  


Simple String Iteration

Now let’s look at some of the cool stuff you can do to String objects. First, let’s focus on the features available within the String class itself.

It’s helpful to think of a String as a sequence of characters. As such, you sometimes want to iterate through its contents, one character at a time. There are numerous ways to do this, but one simple way is to use a for() loop. You can take advantage of the String’s length() method to determine how many characters you’ve got, and the charAt() method to retrieve a specific character by its index, much like you would an array index. For example:

String strVowels = "AEIOU";
for (int i = 0; i < strVowels.length(); i++) {
 char curChar = strVowels.charAt(i);  }

String Modifications: The Basics

As mentioned earlier, String variables are immutable, or unchangeable. That is not to say you cannot manipulate the textual contents of a String variable, but each method that does so returns a new String variable. Some common examples of String class methods that generate new String variables include:

· The concat() method is used to concatenate, or combine, two strings into a new String object. Note: You can also use the + operator to create a new String object from parts as well.

· The format() method allows you to create parameterized string templates (a more advanced topic for future discussion)

· The replace() and replaceFirst() methods are used to replace one character or substring with another substring. The replaceAll() method supports regular expression pattern matching.

· The split() method is helpful for breaking a larger String into numerous substrings. For example, you could break up a comma-delimited list into an array of String objects, one for each list item.

· The substring() method is used to extract only part of the original String object.

· The toUpperCase() and toLowerCase() methods are used to change the String’s case, especially useful for normalizing strings.

· The trim() method is used to hack off (remove) any whitespace before or after the String contents.

Keep in mind that each of these methods allocates a new String object instance to store the result. The original String variable remains unchanged.

String Modifications: Converting to Upper and Lowercase

Sometimes you want to convert your string to uppercase or lowercase. One reason you might want to change the case of a string is to normalize the string to make case-insensitive searching or matching easier to implement.

String strUpperCaseVersion = strVowels.toUpperCase();
String strLowerCaseVersion = strVowels.toLowerCase();

Note that here you have created two new String variables for use. The original String variable, strVowels, remains unchanged.

String Modifications: Splitting

Sometimes you want to quickly parse a string into substrings. You might do this to extract the individual words from a sentence, or a delimited list of tags, etc. You can use simple regular expressions with the split() function for this purpose. For example, the following code extracts the individual words (colors) from a String:

String someWords = "Red Orange Yellow Green Blue Indigo";
 String aColors[] = someWords.split(" ");

If you were to print out the contents of the String array called aColors, you would see that:

 aColors[0]=Red
 aColors[1]=Orange
 aColors[2]=Yellow
 aColors[3]=Green
 aColors[4]=Blue
 aColors[5]=Indigo

Note that here you have created a new array containing 6 new String variables for use.

Simple String Matching

You can check if two strings match using the String class’s compareTo() method. This method will return 0 if, and only if, the two strings are identical:

String strVowels = "AEIOU";
 if(strVowels.compareTo("AEIOU") == 0)
 {
 // Strings match! (This code will execute)
 } else {
 // Strings don’t match!
 }

Note that the compareTo() method is case-sensitive. Consider converting both sides of your comparison to one case before comparing them, unless you are specifically looking for one case. If you don’t care about case, you can also use the compareToIgnoreCase() method instead of the compareTo() method:

String strVowels = "AEIOU";
 if(strVowels.compareToIgnoreCase ("aeiou")== 0)
 {
 // Strings match! (This code will execute)
 } else {
 // Strings don’t match!
}

Simple String Searching
Sometimes you want to search a string for a character or substring. There are many other ways to perform string matching and searching, allowing you to build whatever search methods you desire. You can also hunt for specific characters or substrings using the indexOf() and lastIndexOf() methods, check if a string begins or ends with a substring using the startsWith() and endsWith() methods. Finally, the matches() method supports regular expression matching.

Here we use the contains() method to determine if a specific substring exists:

 if(strVowels.contains("IOU")==true)
 {
// String contains IOU sub-string!
 }

If you don’t care about case, use the compareToIgnoreCase() method instead:

 String strVowels = "AEIOU"; 
if(strVowels. compareToIgnoreCase ("aeiou")== 0)
 {  // Strings match! (This code will execute)
 } else { // Strings don’t match!
 }

TIP: When implementing matching and searching functionality in your applications, don’t forget to do any preprocessing string manipulation necessary to rule out upper/lower/mixed case string issues before searching. User input normalization can be done as part of the input validation process, keeping your code as simple and maintainable as possible.

Strings and Other Data Types

The String object is so fundamental to Java that every class, due to being derived from the root class called Object (java.lang.Object), has a toString() method to create a useful string representation of their value. Classes that don't have a reasonable string representation usually return some identifier or debug information as to the type of class. Those that do have a reasonable string representation, such as a number string from an Integer object, return the textual representation of the encapsulated number. When concatenated with a String, such as with the plus (+) operator described above, the toString() method results are used by default. For example:

Integer iNum = new Integer(123);
 String sText = "The number one-two-three = ";
 String sFullText = sText + iNum;
 String sFullText2 = sText + iNum.toString();

Both the strings (sFullText and sFullText2) have the same value, "The number one-two-three = 123". Many such objects can also work in reverse. That is, they can parse a String representation and convert it to the native type the object is representing. For instace, again with the Integer class, the parseInt() method can be used to get a new Integer object based on the string representation.

Strings and Performance

As you’ve seen, strings can be used to great effect. String creation and manipulation does, however, have some drawbacks. Imprudent String manipulation can have negative performance implications for your application. It’s a basic design principle of Java to not create objects you don’t need. You can see that string manipulation and modifications can result in a lot of String variables floating around. Here are some tips for good string usage:

· Don’t create String variables you don’t need, especially temporary ones.

· Use the StringBuilder and StringBuffer classes to generate string contents from the ground up.

· Review the performance suggestions available on the Android Developer website.

· Use static final String constants for String values known at compile time.

Wrapping Up

Strings are an important data type that Android developers use to store textual data. String data, whether it be a sequence of characters, numbers, symbols, or some mix thereof, can be stored in a variety of ways, but the String class is the primary utility class used for this purpose. The String class, and it’s helper classes like StringBuilder, contain a robust set of methods for use with strings, allow their contents to be searched or modified.

Wednesday 3 October 2012

Shut Down from Your Desktop


If you're trying to eliminate every extraneous mouse click, you can shut down your computer with an icon on the desktop. Right-click on your desktop, click "New," and then click "Shortcut." In the "Type the location of the item" field, type "shutdown -s -t 00" to give you a way to shut down the computer immediately. (Change the -s to -r to create a reboot shortcut instead.)

What's AJAX ?

AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google Suggest, and Google Maps hit the streets.

Asynchronous JavaScript and XML, or Ajax (pronounced "Aye-Jacks"), is a web development technique for creating interactive web applications using a combination of XHTML (or HTML) and CSS for marking up and styling information. (XML is commonly used, although any format will work, including preformatted HTML, plain text, JSON and even EBML).

The Document Object Model manipulated through JavaScript to dynamically display and interact with the information presented

The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server.

Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies together. In fact, derivative/composite technologies based substantially upon Ajax, such as AFLAX, are already appearing.

Ajax applications are mostly executed on the user's computer; they can perform a number of tasks without their performance being limited by the network. This permits the development of interactive applications, in particular reactive and rich graphic user interfaces.

Ajax applications target a well-documented platform, implemented by all major browsers on most existing platforms. While it is uncertain that this compatibility will resist the advent of the next generations of browsers (in particular, Firefox), at the moment, Ajax applications are effectively cross-platform.

While the Ajax platform is more restricted than the Java platform, current Ajax applications effectively fill part of the one-time niche of Java applets: extending the browser with portable, lightweight mini-applications.

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

* standards-based presentation using XHTML and CSS;
* dynamic display and interaction using the Document Object Model;
* data interchange and manipulation using XML and XSLT;
* asynchronous data retrieval using XMLHttpRequest;
* and JavaScript binding everything together.

Monday 1 October 2012

Map Marker Example In Android


This example show you how to draw movable marker on to map. You can darg and drop the marker to change its position. Can be used in any application where u want to take input from user for map location.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it MapMarkerExample.
2.) You will see some default code into your main.xml and android manifest file.
3.) Add internet permission to your manifest file or write following in android.manifest file:
 version="1.0" encoding="utf-8"?>
 package="com.example.mapmarker"xmlns:android="http://schemas.android.com/apk/res/android"
        android:versionCode="1" android:versionName="1.0">
         android:minSdkVersion="7" />

         android:name="android.permission.INTERNET" />
         android:name="android.permission.ACCESS_COARSE_LOCATION"/>
         android:icon="@drawable/icon"android:label="@string/app_name">
                 android:name="com.google.android.maps" />
                 android:label="@string/app_name"android:name=".MapMarkerActivity">
                        >

                                 android:name="android.intent.action.MAIN"/>
                                android:name="android.intent.category.LAUNCHER" />
                        
>
                >
        >
>
4.) Write following into main.xml file:
 version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        
                android:id="@+id/map" android:layout_width="wrap_content"
                android:layout_height="wrap_content"android:apiKey="0jp8vWjNayJISFKdvcJwGmwsjgoCoQrT_dflCfQ"
                android:clickable="true" />
         android:id="@+id/drag" android:layout_width="wrap_content"
                android:layout_height="wrap_content"android:src="@drawable/marker"
                android:visibility="gone" />
>
5.) CreateYour own map API key and replace it in above main.xml.
6.) Add any marker image or push pin image in drawable folder.
7.) Run for output.
Steps:
1.) Create a project named MapMarkerExample and set the information as stated in the image.
Build Target: Android 2.1 (Google API)
Application Name: MapMarkerExample
Package Name: com.example.mapmarker
Activity Name: MapMarkerActivity
Min SDK Version: 7
2.) Open MapMarkerActivity.java file and write following code there:
package com.example.mapmarker;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
public class MapMarkerActivity extends MapActivity {
  private MapView map=null;
  private MyLocationOverlay me=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    map=(MapView)findViewById(R.id.map);
 
    map.getController().setCenter(getPoint(21.0000169992044,
                                            78.0000484771729));
    map.setBuiltInZoomControls(true);
 
 
    Drawable marker=getResources().getDrawable(R.drawable.marker);
 
    marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight());
 
    map.getOverlays().add(new SitesOverlay(marker));
 
    me=new MyLocationOverlay(this, map);
    map.getOverlays().add(me);
  }

  @Override
  public void onResume() {
    super.onResume();
 
    me.enableCompass();
  } 

  @Override
  public void onPause() {
    super.onPause();
 
    me.disableCompass();
  } 

  @Override
  protected boolean isRouteDisplayed() {
    return(false);
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_S) {
      map.setSatellite(!map.isSatellite());
      return(true);
    }
    else if (keyCode == KeyEvent.KEYCODE_Z) {
      map.displayZoomControls(true);
      return(true);
    }
 
    return(super.onKeyDown(keyCode, event));
  }
  private GeoPoint getPoint(double lat, double lon) {
    return(new GeoPoint((int)(lat*1000000.0),
                          (int)(lon*1000000.0)));
  }
 
  private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
    private List<OverlayItem> items=new ArrayList<OverlayItem>();
    private Drawable marker=null;
    private OverlayItem inDrag=null;
    private ImageView dragImage=null;
    private int xDragImageOffset=0;
    private int yDragImageOffset=0;
    private int xDragTouchOffset=0;
    private int yDragTouchOffset=0;
 
    public SitesOverlay(Drawable marker) {
      super(marker);
      this.marker=marker;
   
      dragImage=(ImageView)findViewById(R.id.drag);
      xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
      yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
   
      items.add(new OverlayItem(getPoint(21.169992044,
                                                                78.484771729),
                                "Mumbai",
                                "Maharashtra, India"));
      populate();
    }
 
    @Override
    protected OverlayItem createItem(int i) {
      return(items.get(i));
    }
 
    @Override
    public void draw(Canvas canvas, MapView mapView,
                      boolean shadow) {
      super.draw(canvas, mapView, shadow);
   
      boundCenterBottom(marker);
    }
 
    @Override
    public int size() {
      return(items.size());
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView) {
      final int action=event.getAction();
      final int x=(int)event.getX();
      final int y=(int)event.getY();
      boolean result=false;
   
      if (action==MotionEvent.ACTION_DOWN) {
        for (OverlayItem item : items) {
          Point p=new Point(0,0);
       
          map.getProjection().toPixels(item.getPoint(), p);
       
          if (hitTest(item, marker, x-p.x, y-p.y)) {
            result=true;
            inDrag=item;
            items.remove(inDrag);
            populate();
            xDragTouchOffset=0;
            yDragTouchOffset=0;
         
            setDragImagePosition(p.x, p.y);
            dragImage.setVisibility(View.VISIBLE);
            xDragTouchOffset=x-p.x;
            yDragTouchOffset=y-p.y;
         
            break;
          }
        }
      }
      else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
        setDragImagePosition(x, y);
        result=true;
      }
      else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
        dragImage.setVisibility(View.GONE);
     
        GeoPoint pt=map.getProjection().fromPixels(x-xDragTouchOffset,
                                                   y-yDragTouchOffset);
        OverlayItem toDrop=new OverlayItem(pt, inDrag.getTitle(),
                                           inDrag.getSnippet());
        Toast.makeText(MapMarkerActivity.this, pt.getLatitudeE6()+" "+pt.getLongitudeE6(), Toast.LENGTH_SHORT).show();
        items.add(toDrop);
        populate();
     
        inDrag=null;
        result=true;
      }
   
      return(result || super.onTouchEvent(event, mapView));
    }
 
    private void setDragImagePosition(int x, int y) {
      RelativeLayout.LayoutParams lp=
        (RelativeLayout.LayoutParams)dragImage.getLayoutParams();
         
      lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
                      y-yDragImageOffset-yDragTouchOffset, 0, 0);
      dragImage.setLayoutParams(lp);
    }
  }
}
3.) Compile and build the project.
4.) Move the marker shown on the map with the help of mouse for results shown below.
Output