Thursday, January 13, 2011

Consuming REST Web Service using Java and Jersey API

In this tutorial we will create a Java application which will consume REST Web Service.

The web service which will be consumed is developed in this post.


If you have created the Web Service that means you already download Jersey API.
We will need those API for our application.


Create a new java project. Name it "NoteJava"


Insert those Jersey API libraries in our build path.


Create a new java class. Name it "NoteJava.java"


package com.tukangjava.tutorial;
import java.net.URI;
import java.util.Date;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;
public class NoteJava {
ClientConfig config;
Client client;
WebResource service;
public static void main(String[] args) {
DatabaseJava program = new DatabaseJava();
program.printAllResult();
program.printNoteById(1);
program.newNote();
program.printAllResult();
}
public NoteJava() {
config = new DefaultClientConfig();
client = Client.create(config);
service = client.resource(getBaseURI());
}
private void printAllResult() {
System.out.println(service.path("notes").accept(
MediaType.APPLICATION_XML).get(String.class));
}
private void printNoteById(int id) {
System.out.println(service.path("notes/1").accept(
MediaType.APPLICATION_XML).get(String.class));
}
private static URI getBaseURI() {
return UriBuilder.fromUri(
"http://localhost:8080/NoteWS/").build();
}
private void newNote() {
Form form = new Form();
form.add("noteId", "20");
form.add("content", "Make a new note");
form.add("createddate", new Date().getTime() + "");
ClientResponse response = service.path("notes").type(MediaType.APPLICATION_FORM_URLENCODED)
.post(ClientResponse.class, form);
}
}
view raw NoteJava.java hosted with ❤ by GitHub


Run the application.
Console will print xml data which you can use and parse for your application.

Its very simple!

Consume REST Web Service using iPhone

In this tutorial we will create an iPhone application which will consume REST Web Service.

The web service which will be consumed is developed in this post.

Our final application should looked like this.
This note is taken from a REST web service which taken its data from a database server.

First, create a new Window Based Application. Use "Notes" as the project name.

Next, create a new UIViewController subclass, check the UITableViewController subclass in the options panel but leave With XIB for user interface unchecked.
Use "NotesTableViewController" as the name.
Create several variables and a method in NotesTableViewController.h

#import <UIKit/UIKit.h>
@interface NotesTableViewController : UITableViewController {
NSMutableString *contentString;
NSMutableArray *notes;
NSMutableData *xmlData;
NSURLConnection *connectionInProgress;
}
- (void)loadNotes;
@end


Then, we will implement the method in NotesTableViewController.m

#import "NotesTableViewController.h"
@implementation NotesTableViewController
#pragma mark -
#pragma mark Initialization
- (id)initWithStyle:(UITableViewStyle)style {
if (self = [super initWithStyle:style]) {
notes = [[NSMutableArray alloc] init];
}
// Get the tab bar item
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"Notes List"];
return self;
}
- (void)loadNotes {
[notes removeAllObjects];
[[self tableView] reloadData];
// Construct the web service URL
NSURL *url = [NSURL URLWithString:@"http://203.247.166.88:8000/NoteWS/notes"];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
// Clear out the existing connection if there is one
if (connectionInProgress) {
[connectionInProgress cancel];
[connectionInProgress release];
}
// Instantiate the object to hold all incoming data
[xmlData release];
xmlData = [[NSMutableData alloc] init];
// Create and initiate the connection - non blocking
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
// Kick off the loading whenever NotesTableViewController's table view appears
// on the screen by overriding viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self loadNotes];
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
// Give it a delegate
[parser setDelegate:self];
// Tell it to start parsing - the document will be parsed and the delegate
// of NSXMLParser will get all of its delegate messages sent to it before
// this line of execution - it is blocking
[parser parse];
// The parser is done (it blocks until done), you can release it immediately
[parser release];
[[self tableView] reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connectionInProgress release];
connectionInProgress = nil;
[xmlData release];
xmlData = nil;
NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString
delegate:nil
cancelButtonTitle:@"OK"
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet showInView:[[self view] window]];
[actionSheet autorelease];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqual:@"content"]) {
NSLog(@"found content!");
contentString = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[contentString appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqual:@"content"]) {
NSLog(@"ended content: %@", contentString);
[notes addObject:contentString];
// Release and nil contentString so that the next time characters
// are found and not within a content tag, they are ignored
[contentString release];
contentString = nil;
}
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [notes count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"UITableViewCell"] autorelease];
}
[[cell textLabel] setText:[notes objectAtIndex:[indexPath row]]];
return cell;
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)dealloc {
[super dealloc];
}
@end


Create another UIViewController subclass for handling new note insertion. This time, uncheck the UITableViewController subclass but check the With XIB for user interface. Use "NotesInsertViewController" as the name

Next, create some outlet and a method in our controller. Modify "NotesInsertViewController.h"

#import <UIKit/UIKit.h>
@interface NotesInsertViewController : UIViewController {
IBOutlet UITextField *idField;
IBOutlet UITextField *contentField;
}
-(IBAction)insertNote:(id)sender;
@end


Then, double click NotesInsertViewController.xib to open Interface Builder.

Create two UITextField and one Rounded Button.
Connect both UITextField with the appropriate field: idField and contentField
Connect Rounded Button with the insertNote action

Next, implement the method in NotesInsertViewController.m

#import "NotesInsertViewController.h"
@implementation NotesInsertViewController
- (id)init {
[super initWithNibName:@"NotesInsertViewController"
bundle:nil];
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"Insert Note"];
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
return [self init];
}
- (IBAction)insertNote:(id)sender {
NSString *post = [NSString stringWithFormat:@"noteId=%@&content=%@&createddate=8", [idField text], [contentField text]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://203.247.166.88:8000/NoteWS/notes"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
}
else
{
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end


After this we can create the tab controller to navigate between the view table and insert view
Open and edit NotesAppDelegate.h

#import <UIKit/UIKit.h>
@interface NotesAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end


Create a UITabBarController and assign each tab item with the appropriate controller. Open and edit NotesAppDelegate.m

#import "NotesAppDelegate.h"
#import "NotesTableViewController.h"
#import "NotesInsertViewController.h"
@implementation NotesAppDelegate
@synthesize window;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Create the tabBarController
tabBarController = [[UITabBarController alloc] init];
// Create two view controllers
UIViewController *notesTable = [[NotesTableViewController alloc] initWithStyle:UITableViewStylePlain];
UIViewController *notesInsert = [[NotesInsertViewController alloc] init];
// Make an array containing the two view controllers
NSArray *viewControllers = [NSArray arrayWithObjects:notesInsert, notesTable, nil];
[notesTable release];
[notesInsert release];
// Attach them to the tab bar controller
[tabBarController setViewControllers:viewControllers];
// Put the tabBarController's view on the window
[window addSubview:[tabBarController view]];
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end


Build & run our application.
Notice that in inserting a new note we hardcode the date as a string and put 8 which will be interpreted by the web service as "8 seconds after 1 January 1970"

It is a little buggy and the view might not as good. But the point of the tutorial is on consuming REST Web Service, so i decide to make a minimum design and focus on the methods for handling Web Service.

Anyways, enjoy playing with REST Web Service!

Consuming REST Web Service using Android

In this tutorial, we will find out how to create an Android application to consume REST Web Service.

We will create android application which will consume web service in this post .
Our application should look like this.

Create a new Android Application named "Note Android".
Modify AndroidManifest and add INTERNET permission.

Next, create the view for posting new note : main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Note Id" />
<EditText android:id="@+id/txtId"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:text="Content"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="@+id/txtContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:id="@+id/btnPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post" />
<Button android:id="@+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View All" />
</LinearLayout>
view raw main.xml hosted with ❤ by GitHub


And the view for viewing all of our notes. There is no component here. Only a layout because we will create the component programmatically

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>
view raw view.xml hosted with ❤ by GitHub


Next, create our view for posting note : DatabaseAndroid.java

package com.tukangjava.tutorial;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DatabaseAndroid extends Activity
implements View.OnClickListener {
String urlPost = "http://203.247.166.88:8000/NoteWS/notes";
TextView txtId;
TextView txtContent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeGUI();
}
private void initializeGUI() {
Button btnPost =(Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
Button btnView =(Button)findViewById(R.id.btnView);
btnView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.btnPost)
postData();
startActivity(new Intent(this, ViewDatabase.class));
}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlPost);
txtId = (TextView) findViewById(R.id.txtId);
txtContent = (TextView) findViewById(R.id.txtContent);
try {
// Add the data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("noteId", txtId.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("content", txtContent.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("createddate", new Date().getTime() + ""));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
Log.w("ERROR", e.getMessage());
} catch (IOException e) {
Log.w("ERROR", e.getMessage());
}
}
}


And the code for parsing xml retrieved from web service and present each element on a TextView : ViewDatabase.java

package com.tukangandroid.tutorial;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class ViewDatabase extends Activity
implements View.OnClickListener{
String url = "http://203.247.166.88:8000/NoteWS/notes";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
retrieveData(ll);
this.setContentView(sv);
}
private void retrieveData(LinearLayout ll) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
DocumentBuilder builder;
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpGet, responseHandler);
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=builder.parse(new InputSource(new StringReader(responseBody)));
NodeList ids =doc.getElementsByTagName("noteId");
String[] allIds = new String[ids.getLength()];
for (int i=0;i<ids.getLength();i++) {
Element elem = (Element)ids.item(i);
allIds[i] = elem.getFirstChild().getNodeValue();
}
NodeList contents =doc.getElementsByTagName("content");
String[] allContents = new String[contents.getLength()];
for (int i=0;i<contents.getLength();i++) {
Element elem = (Element)contents.item(i);
allContents[i] = elem.getFirstChild().getNodeValue();
}
NodeList createddates =doc.getElementsByTagName("createdDate");
String[] allCreateddates = new String[createddates.getLength()];
for (int i=0;i<createddates.getLength();i++) {
Element elem = (Element)createddates.item(i);
allCreateddates[i] = elem.getFirstChild().getNodeValue();
}
for (int i=0;i<allIds.length;i++) {
TextView id = new TextView(this);
id.setText(allIds[i]);
ll.addView(id);
TextView content = new TextView(this);
content.setText(allContents[i]);
ll.addView(content);
TextView createddate = new TextView(this);
createddate.setText(allCreateddates[i]);
ll.addView(createddate);
View view = new View(this);
view.setBackgroundColor(Color.WHITE);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
ll.addView(view);
}
Button b = new Button(this);
b.setOnClickListener(this);
b.setText("Post New");
ll.addView(b);
} catch (ClientProtocolException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (IOException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (SAXException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (ParserConfigurationException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (FactoryConfigurationError e) {
Log.e(getString(R.string.app_name), e.getMessage());
}
}
@Override
public void onClick(View v) {
startActivity(new Intent(this, DatabaseAndroid.class));
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


Run our application and try creating new notes.

Have fun!

Wednesday, January 12, 2011

Creating REST Web Service using Java and Jersey API

In order to create a RESTful Web Service using Java, we need several tools and library
The tools and library which i used are:
1. Java 1.6
2. Eclipse IDE for Java EE developers (Ganymede)
3. Apache Tomcat (6.0)
4. Jersey API (1.4) . Download the zipped file.
5. Oracle Database 10g or any other DBMS

Create a new DynamicWebProject in Eclipse. If no such project template exists, you should download Eclipse for Java EE developers.
Copy those Jersey API librari in "WEB-INF\lib" folder
Modify web.xml to register our jersey servlet. Put any name on the servlet name tag. It doesn't matter.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>NoteWS</display-name>
<servlet>
<servlet-name>JerseyTest</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyTest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
view raw web.xml hosted with ❤ by GitHub


Our web service will connect to database and retrieve or insert a new note in NOTE table
Create a new table named : NOTE with the following columns
NOTEID       : number
CONTENT   : varchar
CREATEDDATE : date

We will create a model class for that table: Note.java

package com.tukangjava.tutorial;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Note {
private int noteId;
private String content;
private Date createdDate;
public Note() {}
public Note(int noteId, String content, Date createdDate) {
this.noteId = noteId;
this.content = content;
this.createdDate = createdDate;
}
public int getNoteId() {
return noteId;
}
public void setNoteId(int noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Override
public String toString() {
return "Note [content=" + content + ", createdDate=" + createdDate
+ ", noteId=" + noteId + "]";
}
}
view raw Note.java hosted with ❤ by GitHub


Next, create a class that will handle connection with database: DatabaseAccess.java

package com.tukangjava.tutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseAccess {
Connection connection = null;
public void connect() throws SQLException
{
String DRIVER = "oracle.jdbc.driver.OracleDriver";
String URL = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
String UserName = "daniel";
String Password = "daniel";
try
{
Class.forName(DRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
connection = DriverManager.getConnection(URL,UserName,Password);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void disconnect() throws SQLException
{
connection.close();
}
}


After that, create a class that will handle the database operation. A Data Access Object :
NoteDao.java

package com.tukangjava.tutorial;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class NoteDao {
DatabaseAccess data;
Connection connection;
public NoteDao()
{
try {
data = new DatabaseAccess();
connect();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void connect() throws SQLException
{
try
{
data.connect();
connection = data.connection;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Note getNoteById(int id)
{
PreparedStatement prepStmt = null;
try {
String cSQL = "SELECT * FROM NOTE WHERE NOTEID = ? ";
prepStmt = connection.prepareStatement(cSQL);
prepStmt.setInt(1, id);
ResultSet result = prepStmt.executeQuery();
Note note = new Note();
while (result.next())
{
note.setNoteId(result.getInt(1));
note.setContent(result.getString(2));
note.setCreatedDate(new java.util.Date(result.getDate(3).getTime()));
}
return note;
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
public List<Note> getAllNotes()
{
PreparedStatement prepStmt = null;
List<Note> notes = new ArrayList<Note>();
try {
String cSQL = "SELECT * FROM NOTE";
prepStmt = connection.prepareStatement(cSQL);
ResultSet result = prepStmt.executeQuery();
while (result.next())
{
Note note = new Note();
note.setNoteId(result.getInt(1));
note.setContent(result.getString(2));
note.setCreatedDate(new java.util.Date(result.getDate(3).getTime()));
notes.add(note);
}
return notes;
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
public void addNote(Note note) {
PreparedStatement prepStmt = null;
try {
String cSQL = "INSERT INTO NOTE VALUES(?, ?, ?)";
prepStmt = connection.prepareStatement(cSQL);
prepStmt.setInt(1, note.getNoteId());
prepStmt.setString(2, note.getContent());
prepStmt.setDate(3, new Date(note.getCreatedDate().getTime()));
prepStmt.executeUpdate();
} catch (SQLException e) {
prepStmt = null;
e.printStackTrace();
}
}
}
view raw NoteDao.java hosted with ❤ by GitHub


Finally, we create a resource class that will be able to retrieved by the client using REST web service

package com.tukangjava.tutorial;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
@Path("/notes")
public class NoteResource {
@Context
UriInfo uriInfo;
@Context
Request request;
NoteDao dao = new NoteDao();
@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void newNote(
@FormParam("noteId") String noteId,
@FormParam("content") String content,
@FormParam("createddate") String createddate,
@Context HttpServletResponse servletResponse
) throws IOException {
Note note = new Note();
note.setNoteId(Integer.parseInt(noteId));
note.setContent(content);
note.setCreatedDate(new Date(Long.parseLong(createddate)));
dao.addNote(note);
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Note> getNotes() {
return dao.getAllNotes();
}
@Path("{note}")
@GET
@Produces(MediaType.APPLICATION_XML)
public Note getNote(
@PathParam("note") String idStr) {
int id = Integer.parseInt(idStr);
Note note = dao.getNoteById(id);
if(note==null)
throw new RuntimeException("Get: Note with " + id + " not found");
return note;
}
}


Save and deploy the project.
Populate our NOTE table using some dummy data and try to call our resource using the following URL in your web browser.

http://localhost:8080/NoteWS/notes

If u got xml file containing the records in your NOTE table. You have successfully create a REST Web Service.

Now, how can we use the POST method to actually insert a record.
Well, we can create a html form whose method is POST and submit action refers to

http://localhost:8080/NoteWS/notes

Something like this:
Notice that we have to make sure our text field name match the form parameter name defined in NoteResource.java

<html>
<body>
<form method="POST" action="http://localhost:8080/NoteWS/notes">
Note ID <input type="text" name="noteId" /><br />
Content <input type="text" name="content" /><br />
Created Date <input type="text" name="createddate" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
view raw note.html hosted with ❤ by GitHub


Note that createddate accept a String but in NoteResource.java it parses the string to primitive type long for creating new Date object. So, for now, just insert any number which will represent the second from January 1, 1970.

access http://localhost:8080/NoteWS/notes again to check our new note.

That is if for creating REST Web Service using Java and Jersey API.

Check out my other tutorial to find out how to consume this REST Web Service From
1. Simple java project
2. Android
3. iPhone

Have fun with REST!

Create List without extending ListActivity

Creating list view in Android is an easy task.
All we have to do is extending ListActivity, implement the methods and we are good to go.
But there are times when it is not an option, because we need to extend another class.
Let say....MapActivity? So we need to create a two tabbed view for user to be able to change from map view to list view. Our intended application may look like this.

When user click on an entry in list view, user will be redirected to the entry location in map view.
In this tutorial, we will create only a ListView then, we will add Tabs and MapView Tab.
We will need to create our implementation of ArrayAdapter and override its getView() method to accomodate our own view. We will create a title, a description and an icon for each row.

Dont forget to add uses library and internet permission in AndroidManifest.xml

First, we need to create a model class. Let say Restaurant.java

package com.tukangandroid.tutorial;
public class Restaurant {
private String name;
private String specialMenu;
private int latitude;
private int longitude;
public Restaurant(String name, String specialMenu, int latitude, int longitude) {
this.name = name;
this.specialMenu = specialMenu;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecialMenu() {
return specialMenu;
}
public void setSpecialMenu(String specialMenu) {
this.specialMenu = specialMenu;
}
public int getLatitude() {
return latitude;
}
public void setLatitude(int latitude) {
this.latitude = latitude;
}
public int getLongitude() {
return longitude;
}
public void setLongitude(int longitude) {
this.longitude = longitude;
}
}
view raw Restaurant.java hosted with ❤ by GitHub


After that, we will create our view: main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
view raw main.xml hosted with ❤ by GitHub


Next, create our layout for each row in our list view: row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:src="@drawable/icon" />
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="@+id/toptext"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_vertical"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="@+id/bottomtext"
android:singleLine="true"
android:ellipsize="marquee"
/>
</LinearLayout>
</LinearLayout>
view raw row.xml hosted with ❤ by GitHub


Next step, our main application view: DoubleTabView.java

package com.tukangandroid.tutorial;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DoubleTabView extends Activity {
private ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.list);
// Adding dummy data
List<Restaurant> restaurants = new ArrayList<Restaurant>();
restaurants.add(new Restaurant("Indonesian Restaurant", "babi guling", 35100000, 129100000));
restaurants.add(new Restaurant("Chinese Restaurant", "cap cay", 35110000, 129110000));
restaurants.add(new Restaurant("Korean Restaurant", "kimchi jige", 35120000, 129120000));
lv.setAdapter(new RestaurantAdapter(this,android.R.layout.simple_list_item_1, restaurants));
}
// Our array adapter, in our view, we will create a title, a description and an icon for each row
private class RestaurantAdapter extends ArrayAdapter<Restaurant> {
private List<Restaurant> items;
public RestaurantAdapter(Context context, int textViewResourceId, List<Restaurant> items) {
super(context, textViewResourceId, items);
this.items = items;
}
// Create a title and detail, icon is created in the xml file
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Restaurant o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
if (tt != null) {
tt.setText("Name : "+o.getName());
}
if(bt != null){
bt.setText("Special menu: "+ o.getSpecialMenu());
}
}
return v;
}
}
}


Execute the application and we will see our generic list view application



Next, we will create a tab bar for user to choose List View or Map View and we will add the feature to navigate user to the map view whenever he/she click on a row in the List View

First, we should change our main.xml. We add TabHost, TabWidget and MapView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabHost android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="62px">
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="0Tmz2clOfrJGA0_c_d17-gSC4We41u7Onmx9W_Q"
/>
</FrameLayout>
</TabHost>
</LinearLayout>
view raw main.xml hosted with ❤ by GitHub


Next, we add the tab name programatically, then we add navigateToLocation method to navigate and zoom to the restaurant location

package com.tukangandroid.tutorial;
import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class DoubleTabView extends MapActivity {
private ListView lv;
private TabHost tabs;
private MapView mapView;
private List<Overlay> mapOverlays;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabs=(TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("list");
spec.setContent(R.id.list);
spec.setIndicator("List View");
tabs.addTab(spec);
spec=tabs.newTabSpec("mapview");
spec.setContent(R.id.mapview);
spec.setIndicator("Map View");
tabs.addTab(spec);
tabs.setCurrentTab(0);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
lv = (ListView)findViewById(R.id.list);
// Adding dummy data
final List<Restaurant> restaurants = new ArrayList<Restaurant>();
restaurants.add(new Restaurant("Indonesian Restaurant", "babi guling", 35100000, 129100000));
restaurants.add(new Restaurant("Chinese Restaurant", "cap cay", 35110000, 129110000));
restaurants.add(new Restaurant("Korean Restaurant", "kimchi jige", 35120000, 129120000));
lv.setAdapter(new RestaurantAdapter(this,android.R.layout.simple_list_item_1, restaurants));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// When user click a row, we get the row coordinate and navigate to that location
navigateToLocation(restaurants.get(position), mapView, false);
tabs.setCurrentTab(1);
}
});
}
public void navigateToLocation(Restaurant restaurant, MapView mv, boolean isDefault) {
mapOverlays.clear();
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(drawable);
GeoPoint point = new GeoPoint(restaurant.getLatitude(), restaurant.getLongitude());
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
mv.displayZoomControls(true);
MapController mc = mv.getController();
mc.animateTo(point); // move map to the given point
int zoomlevel = mv.getMaxZoomLevel() - 1;
mc.setZoom(zoomlevel); // zoom
mv.setSatellite(false); // display only "normal" mapview
}
// Our array adapter, in our view, we will create a title, a description and an icon for each row
private class RestaurantAdapter extends ArrayAdapter<Restaurant> {
private List<Restaurant> items;
public RestaurantAdapter(Context context, int textViewResourceId, List<Restaurant> items) {
super(context, textViewResourceId, items);
this.items = items;
}
// Create a title and detail, icon is created in the xml file
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Restaurant o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
if (tt != null) {
tt.setText("Name : "+o.getName());
}
if(bt != null){
bt.setText("Special menu: "+ o.getSpecialMenu());
}
}
return v;
}
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}


Build and run.
Our final application should look like this
Click one restaurant, and the application will navigate and zoom to the location

That's it! Have fun!





Create a Radius Around a Point in Google Map

Question : How do I create a 9000 meters buffer radius from a point and display placemarks that intersect that buffer.
Answer : Google Map API for android has a class that reads and draw your current location in the map.
That class is "MyLocationOverlay". The class has a "draw" method that will be called everytime user pan or zoom on the map.
So to draw a circle radius of your current location, we need to extends this class and override its draw method.
package com.tukangandroid.tutorial;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;
public class MyOwnLocationOverlay extends MyLocationOverlay{
private MapView mapView;
private Paint circlePainter;
private Point screenCurrentPoint;
private GeoPoint geoCurrentPoint;
private int meters;
public MyOwnLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
this.mapView = mapView;
}
// This method is used to get user submitted radius from our application
public void setMeters(int meters) {
this.meters = meters;
}
@Override
public synchronized boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when) {
// Set the painter to paint our circle. setColor = blue, setAlpha = 70 so the background
// can still be seen. Feel free to change these settings
circlePainter = new Paint();
circlePainter.setAntiAlias(true);
circlePainter.setStrokeWidth(2.0f);
circlePainter.setColor(0xff6666ff);
circlePainter.setStyle(Style.FILL_AND_STROKE);
circlePainter.setAlpha(70);
// Get projection from the mapView.
Projection projection = mapView.getProjection();
// Get current location
geoCurrentPoint = getMyLocation();
screenCurrentPoint = new Point();
// Project the gps coordinate to screen coordinate
projection.toPixels(geoCurrentPoint, screenCurrentPoint);
int radius = metersToRadius(geoCurrentPoint.getLatitudeE6() /1000000);
// draw the blue circle
canvas.drawCircle(screenCurrentPoint.x, screenCurrentPoint.y, radius, circlePainter);
return super.draw(canvas, mapView, shadow, when);
}
// hack to get more accurate radius, because the accuracy is changing as the location
// getting further away from the equator
public int metersToRadius(double latitude) {
return (int) (mapView.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));
}
}

Then, we create our view, one map view, one textbox and one button

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<EditText
android:id="@+id/txtRadius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Radius"
/>
<Button android:id="@+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
</TableRow>
<TableRow>
<com.google.android.maps.MapView
android:layout_span="2"
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="your_api_key_here"
/>
</TableRow>
</TableLayout>
view raw main.xml hosted with ❤ by GitHub

After that, we need to create our main class. TukangAndroidApp.java
package com.tukangandroid.tutorial;
import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class TukangAndroidApp extends MapActivity{
private MapView mapView;
private List<Overlay> mapOverlays;
private MyOwnLocationOverlay myLocationOverlay;
private MapController mapController;
private TextView txtRadius;
private Button btnSearch;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new SearchListener());
txtRadius = (TextView) findViewById(R.id.txtRadius);
}
private class SearchListener implements android.view.View.OnClickListener {
@Override
public void onClick(View v) {
mapView.getOverlays().clear();
mapOverlays = mapView.getOverlays();
myLocationOverlay = new MyOwnLocationOverlay(TukangAndroidApp.this, mapView);
myLocationOverlay.setMeters(Integer.parseInt(txtRadius.getText().toString()));
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapController.animateTo(myLocationOverlay.getMyLocation());
}
});
mapView.getOverlays().add(myLocationOverlay);
displayResults();
}
}
private void displayResults() {
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}

Dont forget to edit AndroidManifest.xml to add permissions and google map library
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tukangandroid.tutorial"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".TukangAndroidApp"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>


Run your application.
Tips : Set the GPS location from the DDMS first before you press Search, otherwise you will encounter NullPointerException
If all goes well, your application will be like this

Notice in TukangAndroidApp.java, our displayResult method didnt do anything, so we will implement the method to return some placemarks that intersect our buffer.
First, we should extends ItemizedOverlay class to create our placemark
package com.tukangandroid.tutorial;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
}


Next, we will implement the displayResult method.
Our last TukangAndroidApp.java should look like this
package com.tukangandroid.tutorial;
import java.util.ArrayList;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class TukangAndroidApp extends MapActivity{
private MapView mapView;
private List<Overlay> mapOverlays;
private MyOwnLocationOverlay myLocationOverlay;
private MapController mapController;
private TextView txtRadius;
private Button btnSearch;
private boolean isFound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new SearchListener());
txtRadius = (TextView) findViewById(R.id.txtRadius);
}
private class SearchListener implements android.view.View.OnClickListener {
@Override
public void onClick(View v) {
mapView.getOverlays().clear();
mapOverlays = mapView.getOverlays();
myLocationOverlay = new MyOwnLocationOverlay(TukangAndroidApp.this, mapView);
myLocationOverlay.setMeters(Integer.parseInt(txtRadius.getText().toString()));
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapController.animateTo(myLocationOverlay.getMyLocation());
}
});
mapView.getOverlays().add(myLocationOverlay);
displayResults();
}
}
private void displayResults() {
// Create dummy list of GeoPoint
GeoPoint point1 = new GeoPoint(35100000, 129100000);
GeoPoint point2 = new GeoPoint(35110000, 129110000);
GeoPoint point3 = new GeoPoint(35120000, 129120000);
List<GeoPoint> points = new ArrayList<GeoPoint>();
points.add(point1);
points.add(point2);
points.add(point3);
mapOverlays = mapView.getOverlays();
Drawable drawable = getResources().getDrawable(R.drawable.icon);
HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(drawable);
for(GeoPoint point : points) {
// Create a location because Location has a distanceTo method that we can
// use for buffering. Notice that distanceTo calculate distance in meter
Location gpsLocation = new Location("current location");
// Get our current gps point and use it to create a location
GeoPoint currentLocation = myLocationOverlay.getMyLocation();
double lat = (double) (currentLocation.getLatitudeE6() / 1000000.0);
double lng = (double) (currentLocation.getLongitudeE6() / 1000000.0);
gpsLocation.setLatitude(lat);
gpsLocation.setLongitude(lng);
Location pointLocation = new Location("point");
pointLocation.setLatitude(point.getLatitudeE6() / 1000000.0);
pointLocation.setLongitude(point.getLongitudeE6() / 1000000.0);
// Calculate the distance between current location and point location
if(gpsLocation.distanceTo(pointLocation) < Float.parseFloat(txtRadius.getText().toString())) {
isFound = true;
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedOverlay.addOverlay(overlayitem);
}
}
// If any location found, draw the placemark
if(isFound)
mapOverlays.add(itemizedOverlay);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}

Run the application, and you can see that our application will work well.







Have fun!