MY mENU


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