Monday, May 28, 2012

Add a reminder using local notifications

This article is based on multi-tasking environment in ios sdk. There is a simple solution put in place. This solution is known as push notifications. This solution is great and all, but it still requires to have an active internet connection. Furthermore, it is little bit difficult procedure. With iOS4, Apple has introduced a new type of notification that can be scheduled to fire within the device itself. That ‘s Local Notifications. Local notifications can be scheduled on the user’s iDevice to fire at any given time.

ReminderUI.h

[sourcecode language="objc"]
#import <UIKit/UIKit.h>

@interface ReminderUI : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
IBOutlet UITableView *tableview;
IBOutlet UIDatePicker *datePicker;
IBOutlet UITextField *eventText;
}
@property (nonatomic, retain) IBOutlet UITableView *tableview;
@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) IBOutlet UITextField *eventText;

-(IBAction)scheduleAlarm:(id) sender;
-(IBAction)hideKeyBoard;
-(IBAction)goBack;

@end

[/sourcecode]

ReminderUI.m

[sourcecode language="objc"]

#import "ReminderUI.h"
#import "GreetingAppViewController.h"

@implementation ReminderUI
@synthesize datePicker,tableview, eventText;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

}
return self;
}

- (void)dealloc
{
[super dealloc];
}

- (void) viewWillAppear:(BOOL)animated {
[self.tableview reloadData];
}

- (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.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
[super viewDidUnload];
datePicker = nil;
tableview = nil;
eventText = nil;
}

-(IBAction)hideKeyBoard
{
[eventText resignFirstResponder];

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return&nbsp; YES;
}

- (IBAction) scheduleAlarm:(id) sender
{
[eventText resignFirstResponder];

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the current date
NSDate *pickerDate = [self.datePicker date];

// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |&nbsp; NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];

// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = @"View";

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;

// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
localNotif.userInfo = infoDict;

// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

[self.tableview reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...

NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];

[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];

return cell;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{

return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)goBack
{
GreetingAppViewController *home= [[GreetingAppViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:home animated:YES];
}

@end

[/sourcecode]

Modify the appDelegate.m so that following changes will reflect.

appDelegate.m

[sourcecode language="objc"]
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.

self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;

// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(@"Recieved Notification %@",localNotif);
}

return YES;

}

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
// Handle the notificaton when the app is running
NSLog(@"Recieved Notification %@",notif);
}



[/sourcecode]

Send Email with attachment in iPhone

We need MessageUI framework to send email. Sending Email can not be tested using iPhone simulator. The reason is simulator does not include a mail app. The application should be installed in actual device and tested. In simulator, it displays a successful message that email has been sent but it just an indicator that no other problem with source code.

[sourcecode language="objc"]

NSData *audioFile = [[NSData alloc]initWithContentsOfURL:temporaryRecFile];

MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate = self;
[mailer setSubject:@"Greeting Message"];
NSArray *toReceipients = [NSArray arrayWithObjects:@"recepient_mail_address", nil];
[mailer setToRecipients:toReceipients];
[mailer addAttachmentData:audioFile mimeType:@"audio/caf" fileName:@"VoiceFile.caf"];
[mailer setMessageBody:@"My greetings for you" isHTML:NO];

[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Failure" message:@"Device does not support" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];


[/sourcecode]

Record and playback voice in iPhone

NewRecordingUI.h

[sourcecode language="objc"]
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <MessageUI/MessageUI.h>

@interface NewRecordingUI : UIViewController <AVAudioRecorderDelegate,MFMailComposeViewControllerDelegate>
{
IBOutlet UIButton *playBtn;
IBOutlet UIButton *recBtn;
IBOutlet UILabel *recStstus;

BOOL isNotRecording;
NSURL *temporaryRecFile;
AVAudioRecorder *recorder;
NSTimer *sliderTimer;
}
@property(nonatomic,retain)IBOutlet UIButton *playBtn;
@property(nonatomic,retain)IBOutlet UIButton *recBtn;
@property(nonatomic,retain)IBOutlet UIButton *emailBtn;
@property(nonatomic,retain)IBOutlet UIButton *shareBtn;
@property (retain, nonatomic) IBOutlet UISlider *progressSlider;

-(IBAction)play;
-(IBAction)record;
-(IBAction)openMail:(id)sender;
@end

[/sourcecode]

NewRecordingUI.m

[sourcecode language="objc"]
#import "NewRecordingUI.h"
#import "GreetingAppViewController.h"
#import <MessageUI/MessageUI.h>

@implementation NewRecordingUI
@synthesize playBtn,recBtn,emailBtn,shareBtn,progressSlider;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
isNotRecording = YES;
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
//[playBtn setEnabled:NO];
recStstus.text = @"";

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil ];

[super viewDidLoad];
}

- (void)dealloc
{
[playBtn release];
[recBtn release];
[emailBtn release];
[shareBtn release];
[super dealloc];
}

- (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.
}

#pragma mark - View lifecycle

- (void)viewDidUnload
{
NSFileManager *fileHandler = [NSFileManager defaultManager];
[fileHandler removeItemAtPath:temporaryRecFile error:nil];
[recorder dealloc];
recorder = nil;
temporaryRecFile = nil;
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
}

- (void)updateSlider
{

if (!isNotRecording) {
progressSlider.value = recorder.currentTime;
}

}

-(IBAction)record
{
if(isNotRecording)
{
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:@selector(updateSlider)
userInfo:nil repeats:YES];

progressSlider.maximumValue = 100;
//[recorder recordForDuration:10];

isNotRecording = NO;
[recBtn setTitle:@"Stop" forState:UIControlStateNormal];
//[playBtn setEnabled:NO];
playBtn.hidden = YES;
emailBtn.hidden = YES;
shareBtn.hidden = YES;
recStstus.text = @"Recording...";
temporaryRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithString:@"VoiceFile"]]];

recorder = [[AVAudioRecorder alloc]initWithURL:temporaryRecFile settings:nil error:nil];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];

}
else
{
isNotRecording = YES;
[recBtn setTitle:@"Record" forState:UIControlStateNormal];
playBtn.hidden = NO;
emailBtn.hidden = NO;
shareBtn.hidden = NO;
recStstus.text = @"";
[recorder stop];
progressSlider.value = 0;
}
}

-(IBAction)play
{
progressSlider.value = 0;
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self selector:@selector(updateSlider)
userInfo:nil repeats:YES];

recStstus.text = @"Playing...";
[recBtn setEnabled:NO];
NSLog(@"%@",temporaryRecFile);
AVAudioPlayer *player =  [[AVAudioPlayer alloc]initWithContentsOfURL:temporaryRecFile error:nil];
player.volume = 120;
[player play];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)cancel
{
GreetingAppViewController * cancel= [[GreetingAppViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:cancel animated:YES];
}

@end
[/sourcecode]

Sunday, May 20, 2012

Display date in different formats with PHP

[sourcecode language="php"]
echo date('Y-m-d H:i:s');
[/sourcecode]

Sample output : 2012-05-20 11:33:44

Thursday, May 17, 2012

Display Near by places with Google Places API

[sourcecode language="javascript"]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>

<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>

<script type="text/javascript">
var map;
var infowindow;

function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);

map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});

var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}

function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="text">
<pre>
var request = {
location: new google.maps.LatLng(-33.8665433, 151.1956316),
radius: 500,
types: ['store']
};
</pre>
</body>
</html>


[/sourcecode]

 

Monday, May 14, 2012

ios UIImagePicker tutorial


MyImagePickerViewController.h


[sourcecode language="objc"]
#import <UIKit/UIKit.h>

@interface MyImagePickerViewController : UIViewController
<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
UIImagePickerController *ipc;
IBOutlet UIImageView *bgImage;

}
@property (nonatomic,retain) UIImageView *bgImage;

-(IBAction) buttonClicked;

@end

[/sourcecode]

MyImagePickerViewController.m

[sourcecode language="objc"]
#import "MyImagePickerViewController.h"

@implementation MyImagePickerViewController


@synthesize bgImage;

-(IBAction) buttonClicked{

ipc=[[UIImagePickerController alloc]init];
ipc.delegate = self;

if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
}else
{
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}

[self presentModalViewController:ipc animated:YES];

}


-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{

//release picker

[[picker parentViewController]dismissModalViewControllerAnimated:YES];

[picker release];
}


-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

//set image

bgImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
//release picker

[[picker parentViewController]dismissModalViewControllerAnimated:YES];

[picker release];

}







- (void)dealloc
{
[super dealloc];
}

- (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.
}

#pragma mark - View lifecycle

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

[/sourcecode]

 

ios database application tutorial

This is an ios application which demonstrates accessing data tier for common data manipulation tasks. So we are going to build a simple book list application.
This is the application interface.



First add sqlite3 framework to your project.

BookListViewController.h


[sourcecode language="objc"]
//
//  BookListViewController.h
//  BookList
//
//  Created by Snow Leopard User on 19/04/2012.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "/usr/include/sqlite3.h"

@interface BookListViewController : UIViewController {

UITextField *txtBid;
UITextField *txtBname;
UITextField *txtBauthor;

UIButton *btnSave;
UIButton *btnFind;

UILabel *status;
NSString *databasepath;
sqlite3 *booksDB;

}
@property (nonatomic,retain) IBOutlet UITextField *txtBid;
@property (nonatomic,retain) IBOutlet UITextField *txtBname;
@property (nonatomic,retain) IBOutlet UITextField *txtBauthor;
@property (nonatomic,retain) IBOutlet UIButton *btnSave;
@property (nonatomic,retain) IBOutlet UIButton *btnFind;

@property (nonatomic,retain) IBOutlet UILabel *status;

-(IBAction) Save;
-(IBAction) Find;

@end

[/sourcecode]


BookListViewController.m


[sourcecode language="objc"]
//
// BookListViewController.m
// BookList
//
// Created by Snow Leopard User on 19/04/2012.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "BookListViewController.h"

@implementation BookListViewController
@synthesize txtBauthor,txtBid,txtBname,btnFind,btnSave,status;

-(IBAction) Save
{
sqlite3_stmt *statement;
const char *dbpath=[databasepath UTF8String];

if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
{
NSString *insertSQL=[NSString stringWithFormat:@"INSERT INTO BOOKS(BookID,BookName,Author) VALUES(\"%@\",\"%@\",\"%@\")",txtBid.text,txtBname.text,txtBauthor.text];

const char *insert_stmt=[insertSQL UTF8String];

sqlite3_prepare_v2(booksDB, insert_stmt, -1, &statement, NULL);

if(sqlite3_step(statement)==SQLITE_DONE)
{
status.text=@"Book Added";
txtBid.text=@"";
txtBauthor.text=@"";
txtBname.text=@"";

}else
{
status.text=@"Failed to add Book";
}
sqlite3_finalize(statement);
sqlite3_close(booksDB);
}

}

-(IBAction) Find
{
const char *dbpath=[databasepath UTF8String];
sqlite3_stmt *statement;

if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
{
NSString *querySQL=[NSString stringWithFormat:@"SELECT BookID,BookName FROM books WHERE BookID=\"%@\"",txtBid.text];

const char *query_stmt=[querySQL UTF8String];

if(sqlite3_prepare_v2(booksDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
{
if(sqlite3_step(statement)==SQLITE_ROW)
{
NSString *addressField=[[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];

txtBname.text=addressField;

NSString *phoneField=[[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];

txtBname.text=phoneField;

status.text=@"Match Found";
txtBname.text=@"";
txtBauthor.text=@"";

}
sqlite3_finalize(statement);
}
sqlite3_close(booksDB);

}

}

- (void)dealloc
{
[txtBid release];
[txtBname release];
[txtBauthor release];

[super dealloc];
}

- (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.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir =[dirPaths objectAtIndex:0];

databasepath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"books.db"]];

NSFileManager *filemgr=[NSFileManager defaultManager];

if([filemgr fileExistsAtPath:databasepath]==NO)
{
const char *dbpath=[databasepath UTF8String];

if(sqlite3_open(dbpath, &booksDB)==SQLITE_OK)
{
char *errMsg;
const char *sql_stmt="CREATE TABLE IF NOT EXISTS BOOKS(ID INTEGER PRIMARY KEY AUTOINCREMENT,BookID TEXT,BookName TEXT,Author TEXT)";

if(sqlite3_exec(booksDB, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK)
{
status.text=@"Failed to create table";
}
sqlite3_close(booksDB);

}else
{
status.text=@"Failed to Open/Create Database";
}

}
[filemgr release];

[super viewDidLoad];
}

- (void)viewDidUnload
{

[super viewDidUnload];

self.txtBid=NULL;
self.txtBname=NULL;
self.txtBauthor=NULL;
self.status=NULL;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

[/sourcecode]

 

Wednesday, May 9, 2012

Android To Do List

The To Do List application described in this tutorial  supports add new tasks, update and delete them. User can add new tasks using Options menu and delete them using Context menu

Download the complete project

main.xml

[sourcecode language="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="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>
[/sourcecode]

new_task.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/task"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/txtTask"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/task"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/txtDesc"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginBottom="10dp"
android:layout_weight="0.40" >
</EditText>

<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/add" />

</LinearLayout>
[/sourcecode]

row.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/row"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

</TextView>
[/sourcecode]

Strings.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ToDo List</string>
<string name="add">Add</string>
<string name="delete">Delete</string>
<string name="task">Task</string>
<string name="desc">Description</string>

</resources>
[/sourcecode]

AndroidManifest.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.biz"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".ToDo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewTask"></activity>
</application>

</manifest>
[/sourcecode]

DBHelper.java

[sourcecode language="java"]
package com.my.biz;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "tasks";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE task_data (_id integer primary key autoincrement,task text not null,description text not null );";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS task_data");
onCreate(db);

}

}

[/sourcecode]

DBAdapter.java

[sourcecode language="java"]
package com.my.biz;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter
{
private static final String DATABASE_TABLE = "task_data";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DESCRIPTION = "description";

SQLiteDatabase mDb;
Context mCtx;
DBHelper mDbHelper;

public DBAdapter(Context context)
{
this.mCtx = context;
}

public DBAdapter open() throws SQLException
{
mDbHelper = new DBHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close()
{
mDbHelper.close();
}

public long createTask(String task,String desciption)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DESCRIPTION, desciption);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteTask(long id)
{
return mDb.delete(DATABASE_TABLE, KEY_ROW_ID + " = " + id, null) > 0;
}

public boolean updateTask(long id,String task,String desciption)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DESCRIPTION, desciption);
return mDb.update(DATABASE_TABLE, initialValues, KEY_ROW_ID + " = " + id, null) > 0;
}

public Cursor fetchAllTasks()
{
return mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TASK,KEY_DESCRIPTION}, null, null, null, null, null);
}

public Cursor fetchTask(long id)
{
Cursor c = mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TASK,KEY_DESCRIPTION}, KEY_ROW_ID + " = " + id, null, null, null, null);
if(c != null)
{
c.moveToFirst();
}
return c;
}
}

[/sourcecode]

NewTask.java

[sourcecode language="java"]
package com.my.biz;

import com.my.biz.DBAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

public class NewTask extends Activity {
DBAdapter mDbAdapter;
Long mRowId;
EditText mTask;
EditText mDesc;
DatePicker mDate;
Spinner mCategorry;
Button mAdd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbAdapter = new DBAdapter(this);
mDbAdapter.open();
setContentView(R.layout.new_task);

mTask = (EditText)findViewById(R.id.txtTask);
mDesc = (EditText)findViewById(R.id.txtDesc);
mAdd = (Button)findViewById(R.id.btnAdd);

mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(DBAdapter.KEY_ROW_ID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(DBAdapter.KEY_ROW_ID)
: null;
}

populateFields();

mAdd.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();

}
});
}

private void populateFields() {
if (mRowId != null) {
Cursor c = mDbAdapter.fetchTask(mRowId);
startManagingCursor(c);
mTask.setText(c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_TASK)));
mDesc.setText(c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_DESCRIPTION)));

}
}

@Override
protected void onPause() {
super.onPause();
saveState();
}

@Override
protected void onResume() {
super.onResume();
populateFields();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(DBAdapter.KEY_ROW_ID, mRowId);
}

private void saveState() {
String task = mTask.getText().toString();
String desc = mDesc.getText().toString();
if (mRowId == null) {
long id = mDbAdapter.createTask(task, desc);
if (id > 0) {
mRowId = id;
}
} else {
mDbAdapter.updateTask(mRowId, task, desc);
}
}

}

[/sourcecode]

ToDo.java

[sourcecode language="java"]
package com.my.biz;

import com.my.biz.DBAdapter;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ToDo extends ListActivity {
DBAdapter mDbAdapter;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;

public static final int INSERT_ID = Menu.FIRST;
public static final int DELETE_ID = Menu.FIRST + 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbAdapter = new DBAdapter(this);
mDbAdapter.open();
fillData();
registerForContextMenu(getListView());
}

public void create()
{
Intent i = new Intent(this,NewTask.class);
startActivityForResult(i, ACTIVITY_CREATE);
}

public void fillData()
{
Cursor c = mDbAdapter.fetchAllTasks();
startManagingCursor(c);
String []from = new String[]{DBAdapter.KEY_TASK,DBAdapter.KEY_DESCRIPTION};
int [] to = new int[]{R.id.row};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, c, from, to);
setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fillData();
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId())
{
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbAdapter.deleteTask(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);


}


@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.delete);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.add);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case INSERT_ID:
create();
return true;


}


return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this,NewTask.class);
i.putExtra(DBAdapter.KEY_ROW_ID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}


}
[/sourcecode]

Download the complete project

Simple Android Database Application

Today we are going to build a simple database application in Android. First see the project resources screenshot indicated below.


This application uses SQLite database which stores data as a file. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. This is highly recommended for mobile applications as they share little memory compared to general desktop applications. When the application creates a database, it is saved in the directory data/data/APP_NAME/databases/FILENAME. (Find this using DDMS perspective in Eclipse)


We need a DBHelper class that inherits from SQLiteOpenHelper super class. This allows to create database, upgrade database,  get a writable database, get a readable database and many more.

DBAdapter class consists of several user-defined wrapper methods to handle database operations like add,update,delete,fetch data ...etc. Inside these methods we call built-in methods in SQLiteDatabase class to accomplish  our tasks.

The Biz2Activity class is bind to main.xml and it creates the only GUI interface in the application. The interface  has a ListView to display business items as a list. User can add, update or delete a business using the options menu. Android DatePicker tool is used to get the date. Business categories are listed using Android  Spinner which uses an ArrayAdapter to get and display data. The data comes from a String array defined in Strings.xml in Resources folder.

This is the final application

Download Complete Project


main.xml

[sourcecode language="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="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<EditText
android:id="@+id/txtTask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">

<requestFocus />
</EditText>

<DatePicker
android:id="@+id/dtpDate"
android:layout_width="wrap_content"
android:layout_height="79dp" android:layout_marginBottom="10dp"/>

<Spinner
android:id="@+id/spCategory"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginBottom="10dp"/>

<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>
[/sourcecode]

row.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "@+id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

</TextView>
[/sourcecode]

Strings.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="hello">Hello World, Biz2Activity!</string>
<string name="app_name">Biz2</string>
<string name="add">Add</string>
<string name="update">Update</string>
<string name="delete">Delete</string>
<string name="add_biz">Add New Business</string>
<string name="update_biz">Update Business</string>
<string name="title">Title</string>
<string name="start_date">Start Date</string>
<string name="category">Category</string>
<string name="save">Save</string>
<string-array name="biz_categories">
<item >Real Estate</item>
<item >Foods</item>
<item >Housing</item>
<item >Health Care</item>
</string-array>
</resources>
[/sourcecode]

DBHelper.java

[sourcecode language="java"]
package com.my.biz2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "biz";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE biz_data (_id integer primary key autoincrement,title text not null,start_date text,category text not null );";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS biz_data");
onCreate(db);

}

}

[/sourcecode]

DBAdapter.java

[sourcecode language="java"]
package com.my.biz2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter
{
private static final String DATABASE_TABLE = "biz_data";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_START_DATE = "start_date";
public static final String KEY_CATEGORY = "category";

SQLiteDatabase mDb;
Context mCtx;
DBHelper mDbHelper;

public DBAdapter(Context context)
{
this.mCtx = context;
}

public DBAdapter open() throws SQLException
{
mDbHelper = new DBHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close()
{
mDbHelper.close();
}

public long createBiz(String title,String date,String category)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_START_DATE, date);
initialValues.put(KEY_CATEGORY, category);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteBiz(long id)
{
return mDb.delete(DATABASE_TABLE, KEY_ROW_ID + " = " + id, null) > 0;
}

public boolean updateBiz(long id,String title,String date,String category)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_START_DATE, date);
initialValues.put(KEY_CATEGORY, category);
return mDb.update(DATABASE_TABLE, initialValues, KEY_ROW_ID + " = " + id, null) > 0;
}

public Cursor fetchAllBiz()
{
return mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TITLE,KEY_START_DATE,KEY_CATEGORY}, null, null, null, null, null);
}

public Cursor fetchBiz(long id)
{
Cursor c = mDb.query(DATABASE_TABLE, new String[]{KEY_ROW_ID,KEY_TITLE,KEY_START_DATE,KEY_CATEGORY}, KEY_ROW_ID + " = " + id, null, null, null, null);
if(c != null)
{
c.moveToFirst();
}
return c;
}
}

[/sourcecode]

Biz2Activity.java

[sourcecode language="java"]
package com.my.biz2;

import java.util.StringTokenizer;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

public class Biz2Activity extends ListActivity {
DBAdapter mDbAdapter;
EditText mTitle;
DatePicker mDate;
Spinner mCategory;
ArrayAdapter<CharSequence> adapter;
public static final int INSERT_ID = Menu.FIRST;
public static final int UPDATE_ID = Menu.FIRST + 1;
public static final int DELETE_ID = Menu.FIRST + 2;
private long id;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mDbAdapter = new DBAdapter(this);
mDbAdapter.open();
fillData();

mTitle = (EditText)findViewById(R.id.txtTask);
mDate = (DatePicker)findViewById(R.id.dtpDate);
mCategory = (Spinner)findViewById(R.id.spCategory);
adapter = ArrayAdapter.createFromResource(this, R.array.biz_categories, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCategory.setAdapter(adapter);
}

public void fillData()
{
Cursor c = mDbAdapter.fetchAllBiz();
startManagingCursor(c);
String []from = new String[]{DBAdapter.KEY_TITLE,DBAdapter.KEY_START_DATE,DBAdapter.KEY_CATEGORY};
int [] to = new int[]{R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, c, from, to);
setListAdapter(adapter);
}

public String getDate()
{
int year = mDate.getYear();
int month = mDate.getMonth();
int day = mDate.getDayOfMonth();

String a = String.valueOf(year);
String b = String.valueOf(month);
String c = String.valueOf(day);

return a + "/" + b + "/" + c;
}
public void create()
{
String title = mTitle.getText().toString();
String date = getDate();
String category = mCategory.getSelectedItem().toString();
mDbAdapter.createBiz(title, date, category);
fillData();
}

public void update()
{
String title = mTitle.getText().toString();
String date = getDate();
String category = mCategory.getSelectedItem().toString();
mDbAdapter.updateBiz(id, title, date, category);
fillData();
}

public void delete()
{
mDbAdapter.deleteBiz(id);
fillData();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.add);
menu.add(0, UPDATE_ID, 0, R.string.update);
menu.add(0, DELETE_ID, 0, R.string.delete);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case INSERT_ID:
create();
return true;
case UPDATE_ID:
update();
return true;
case DELETE_ID:
delete();
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
this.id = id;
Cursor c = mDbAdapter.fetchBiz(id);
mTitle.setText(c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_TITLE)));

String category = c.getString(
c.getColumnIndexOrThrow(DBAdapter.KEY_CATEGORY));
ArrayAdapter<CharSequence> myAdap = (ArrayAdapter<CharSequence>) mCategory.getAdapter(); //cast to an ArrayAdapter

int spinnerPosition = myAdap.getPosition(category);
mCategory.setSelection(spinnerPosition);

//display date
String date = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_START_DATE));
StringTokenizer tokens = new StringTokenizer(date,"/");
int arr[] = new int[3];
int i=0;

while(tokens.hasMoreTokens())
{
arr[i] = Integer.valueOf(tokens.nextToken());
i++;
}

mDate.updateDate(arr[0], arr[1], arr[2]);
}

}

[/sourcecode]

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...