Wednesday, June 17, 2009
Getting current location using iPhone programming
// MyCLController.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@protocol MyCLControllerDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end
@interface MyCLController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
id delegate;
}
@property (nonatomic, retain) CLLocationManager *locationManager; @property (nonatomic, assign) id delegate;
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error;
@end
// MyCLController.m
#import "MyCLController.h"
@implementation MyCLController
@synthesize locationManager;
@synthesize delegate;
- (id) init {
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
[self.delegate locationUpdate:newLocation];
[locationManager stopUpdatingLocation]; }
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
[self.delegate locationError:error];
}
- (void)dealloc {
[self.locationManager release];
[super dealloc];
}
@end
// Use the follwing code to get the current location latitude and longitude
- (void)viewDidLoad {
[self setTitle:contactLocation];
locationController = [[MyCLController alloc] init];
locationController.delegate = self;
[locationController.locationManager startUpdatingLocation];
[super viewDidLoad];
}
- (void)locationUpdate:(CLLocation *)location {
CLLocationCoordinate2D currentLocation = location.coordinate;
latitude = currentLocation.latitude;
longitude = currentLocation.longitude;
}
- (void)locationError:(NSError *)error {
NSLog(@"Location Error Occured");
}
Tuesday, June 16, 2009
Display directions from the current location as starting address using Google Maps in iPhone programming
// MapsWebViewController.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapsWebViewController : UIViewController {
IBOutlet UIWebView *mapsWebView;
IBOutlet UIView *loadingView;
NSString *contactAddress;
float latitude;
float longitude;
}
@property (nonatomic, retain) NSString *contactAddress;
@property (nonatomic, retain) NSString *displayDirections;
@property (nonatomic) float latitude;
@property (nonatomic) float longitude;
@end
// MapsWebViewController.m file
#import "MapsWebViewController.h"
@implementation MapsWebViewController
@synthesize contactAddress;
@synthesize latitude, longitude;
- (void)viewDidLoad {
self.title = contactAddress;
mapsWebView.scalesPageToFit = YES;
contactAddress = [contactAddress stringByReplacingOccurrencesOfString:@" " withString:@","];
contactAddress = [contactAddress stringByAppendingFormat:@",%@", @<Destination-Address>];
NSString *theURLString = nil;
theURLString = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@",
latitude, longitude,
[contactAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *theURL = [NSURL URLWithString:theURLString];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:theURL];
[mapsWebView loadRequest:theRequest];
mapsWebView.userInteractionEnabled = YES;
self.view.userInteractionEnabled = YES;
[super viewDidLoad];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[self.view addSubview:loadingView];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[loadingView removeFromSuperview];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError*)error {
NSString *ErrorMessage = error.localizedDescription;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:ErrorMessage
delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[super dealloc];
}
@end
Friday, June 12, 2009
Edit Contacts in Address Book using iPhone programming
ABAddressBookRef addressBook= ABAddressBookCreate(); // this will open the AddressBook of the iPhone
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook); // this copies all the contacts from the Address Book into the array
NSString *contactName = [[NSString alloc] init];
// specify the contact name to be edited
contactName = @"ABCD";
for (int i =0 ;i<ABAddressBookGetPersonCount(addressBook);i++){
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty); // this gets the First Name of the person
// check whether the editable contact exists in the AddressBook if exists then allows the user to edit the contact
if ([contactName compare: firstName] == NSOrderedSame) {
ABPersonViewController *personController = [[ABPersonViewController alloc] init];
personController.addressBook = addressBook; // this passes the reference of the Address Book
personController.displayedPerson = ref; // this sets the person reference
personController.allowsEditing = YES; // this allows the user to edit the details
personController.personViewDelegate = self;
personController.navigationItem.rightBarButtonItem = [self editButtonItem]; // this will add the inbuilt Edit button to the view
// this displays the contact with the details and presents with an Edit button
[[self navigationController] pushViewController:personController animated:YES];
[personController release];
}
}
// setEditing method needs to be overridden for edit functionality to work properly
------------------
- (void)setEditing:(BOOL)flag animated:(BOOL)animated {
[super setEditing:flag animated:animated];
if (flag == YES){
// change the view to an editable view
[ [self navigationController] setEditing:YES animated:NO];
}
else {
// save the changes and change the view to noneditable
[ [self navigationController] setEditing:NO animated:NO];
}
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue {
return YES;
}
Tuesday, June 9, 2009
Generating .COD files using RAPC Compiler
If you want to generate .COD files using command line using the RAPC compiler first you need to have RAPC executable on your machines.
RAPC is the command line compiler which is used to compile .java files into .cod files. c.
RAPC takes in a number of arguments from the command line and can be linked to the JDE compiler. It takes in either .java source files or a .jar file, compiles them, and then creates a compressed .cod file, which the BlackBerry handheld can run.
Copy the 2 files (.jad and .jar) to the directory where rapc.exe is present.
Generate the .cod file using the following command in the command line under the RAPC executable installed directory
C:\Program Files\Research In Motion\BlackBerry JDE 4.7.0\bin>rapc.exe import="C:\Program Files\Research In Motion\BlackBerry JDE 4.7.0\lib\net_rim_api.jar" codename=
The above command generates
Thursday, June 4, 2009
Adding contact to Address Book using iPhone programming
Create a View Based Application using the X-Code, place a button with "Add Contact" label and link the addPicker action to the button and follow the below code
-(IBAction)addPicker:(id)sender {
// Open the AddressBook of you iPhone using the ABAddressBookRef it does not create a new one rather it opens the existing Address book
ABAddressBookRef addressBook= ABAddressBookCreate();
// Create a Persons New Record
ABRecordRef aRecord = ABPersonCreate();
// Adding the FirstName, LastName, Company, Job Code
ABRecordSetValue(aRecord, kABPersonFirstNameProperty, @"Your First Name",nil);
ABRecordSetValue(aRecord, kABPersonLastNameProperty, @"Your Last Name", nil);
ABRecordSetValue(aRecord, kABPersonOrganizationProperty, @"Your Company Name",nil);
ABRecordSetValue(aRecord, kABPersonJobTitleProperty, @"Your Job Title",nil);
// Adding the Phone details a person may have multiple phone numbers
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
// Adding Phone number
ABMultiValueAddValueAndLabel(multiPhone, @"1-555-555-5555", kABPersonPhoneMainLabel, NULL);
// Adding a Custom property to the phone details property
ABMultiValueAddValueAndLabel(multiPhone, @"1-444-444-4444", @"Clientphone", NULL);
ABRecordSetValue(aRecord, kABPersonPhoneProperty, multiPhone,nil);
CFRelease(multiPhone);
// Adding the Email property
ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, @"Your Email ID", kABWorkLabel, NULL);
ABRecordSetValue(aRecord, kABPersonEmailProperty, multiEmail, nil);
CFRelease(multiEmail);
// Adding the Address property
ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
[addressDictionary setObject:@"Your Street Name" forKey:(NSString *) kABPersonAddressStreetKey];
[addressDictionary setObject:@"Your City Name" forKey:(NSString *)kABPersonAddressCityKey];
[addressDictionary setObject:@"Your State Name" forKey:(NSString *)kABPersonAddressStateKey];
[addressDictionary setObject:@"ZIP Code" forKey:(NSString *)kABPersonAddressZIPKey];
ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(aRecord, kABPersonAddressProperty, multiAddress,nil);
CFRelease(multiAddress);
// Finally adding the Person's record to the Address book and saving the Address book
ABAddressBookAddRecord(addressBook, aRecord, nil);
ABAddressBookSave(addressBook, nil);
// Releasing the memory
CFRelease(aRecord);
CFRelease(addressBook);
}
UIAlertView with Ok and Cancel buttons using iPhone SDK
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Title" delegate:self
cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK" otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void)alertConfirmAction {
alertName = [[NSString alloc] init];
AlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
[alert show];
[alert release];
}
// UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0){
NSLog(@"Ok button clicked");
}
else {
NSLog(@"Cancel button clicked");
}
}
// UIAlertViewDelegate
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(@"Clicked OK Button");
// TO-DO perform some action for OK button
}
else {
NSLog(@"Clicked Cancel Button");
//TO-DO perform some action for Cancel button
}
}
How to play video file in J2ME code
BlackBerry device does not play media files directly, they need to be converted into BlackBerry supported format. Some of the available converters are BlackBerry Media Converter, NideSoft Converter etcUse the following code to play the Video file using a J2ME application.
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VideoPlayer extends Form implements CommandListener, PlayerListener, Runnable {
private Display display;
private Command stop = new Command("Stop",Command.SCREEN, 2);
public static Player player;
static VideoPlayer videoPlayer;
public VideoPlayer(String s) {
super(" Playing a Video file ");
videoPlayer = this;
start();
addCommand(stop);
setCommandListener(this);
}
public void playerUpdate(Player player,String event, Object data) {
if(event == PlayerListener.END_OF_MEDIA) {
try {
defplayer();
} catch(MediaException me) {
}
reset();
}
}
public void commandAction(Command c, Displayable d) {
if (c == AMSDashboard.CMD_BACK){
stopPlayer();
// TO-DO perform some action
}
if(c == stop) {
stopPlayer();
// TO-DO perform some action
}
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
play();
}
void play() {
try {
VideoControl vc;
defplayer();
// specify the location of the media file
player = Manager.createPlayer(getClass().getResourceAsStream("/videos/
// realize the player
player.realize();
vc = (VideoControl)player.getControl("VideoControl");
if(vc != null) {
Item video = (Item)vc.initDisplayMode(vc.USE_GUI_PRIMITIVE, null); append(video);
}
player.prefetch();
player.start();
} catch(Throwable t) {
reset();
Alert al = new Alert("Error", t.getMessage(), null, AlertType.ERROR); display.setCurrent(al);
t.printStackTrace();
}
}
public static void defplayer() throws MediaException {
if (player != null) {
if(player.getState() == Player.STARTED) {
player.stop();
} if(player.getState() == Player.PREFETCHED) {
player.deallocate();
}
if(player.getState() == Player.REALIZED || player.getState() == Player.UNREALIZED){ player.close();
}
}
player = null;
}
public static void reset() {
player = null;
}
void stopPlayer() {
try {
defplayer();
} catch(MediaException me) {
}
reset();
}
}