Save data on form and display using table view using DB - iphone

I am creating an email signature, i have made two view's till now "ViewController and "ListView" coding is like this
ViewController.h
#import <UIKit/UIKit.h>
#import "ListView.h"
#import "sqlite3.h"
#interface ViewController:UIViewController<UITextViewDelegate,UIImagePickerControllerDelegate>
{
UIImageView *imageView;
UIImage *signimage;
UIImagePickerController *imagePicker;
NSMutableArray *hello;
NSMutableArray *hellocontent;
ListView *listview;
UITextField *signaturename;
UITextView *textView; // UITextView *scontent;
// IBOutlet UIScrollView *scrollview;
// BOOL keyboardIsShown;
//IBOutlet UITextField *recordTextField;
NSString *databasePath;
sqlite3 *Dummy2;
}
#property(nonatomic,retain) IBOutlet UIImageView *imageView;
#property(nonatomic,retain) UIImage *signimage;
-(IBAction)btnLoadImage:(id) sender;
-(IBAction)clearFields:(id)sender;
-(IBAction)show:(id)sender;
// #property (nonatomic,retain) UITextField *recordsTextField;
//#property(nonatomic,retain) IBOutlet UIScrollView *scrollview;
#property(nonatomic, retain) IBOutlet UITextField *signaturename;
#property(nonatomic, retain) IBOutlet UITextView *textView; // scontent
-(IBAction) btnsave:(id) sender;
-(IBAction) keyboard:(id) sender;
-(IBAction)next:(id)sender;
-(IBAction) bgtouch:(id) sender;
// -(IBAction)show:(id)sender;
// -(IBAction)records:(id)s;
// -(IBAction)updateQuery:(id)sender;
//Static methods.
+ (void) getInitialDataToDisplay:(NSString *)dbPath;
+ (void) finalizeStatements;
//Instance methods.
- (id) initWithPrimaryKey:(NSInteger)pk;
- (void) saveAllData;
#end
ViewController.m
#import "ViewController.h"
#import"ListView.h"
#implementation ViewController
#synthesize signaturename,imageView,textView,signimage; // recordsTextField
// scrollview;
-(IBAction)next:(id)sender{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
hello = [[NSMutableArray alloc]init];
// hellocontent = [[NSMutableArray alloc]init];
if (sqlite3_open(dbpath, &Dummy2) == SQLITE_OK)
{
NSString *updateSQL = #"SELECT * FROM PROFILE";
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(Dummy2, update_stmt, -1, &statement, NULL);
while(sqlite3_step(statement) == SQLITE_ROW) {
[hello addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)]];
// [hellocontent addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)]];
}
sqlite3_finalize(statement);
sqlite3_close(Dummy2);
}
listview = [[ListView alloc]initWithNibName:#"ListView" bundle:nil];
listview.arr=[[NSMutableArray alloc]init];
listview.arr = hello;
[self.view addSubview:listview.view];
}
- (void)setCoffeeImage:(UIImage *)theCoffeeImage {
// self.isDirty = YES;
[signimage release];
signimage = [theCoffeeImage retain];
}
-(IBAction) btnsave:(id) sender
{
if (([self.signaturename.text length] && [self.textView.text length]) != 0) {
// NSData *data = UIImagePNGRepresentation(self.signimage);
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
hello = [[NSMutableArray alloc]init];
if (sqlite3_open(dbpath, &Dummy2) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO profile (sname,scontent) VALUES (\"%#\", \"%#\")", signaturename.text,textView.text];
const char *insert_stmt = [insertSQL UTF8String];
// sqlite3_bind_blob(statement, 3, [data bytes], [data length], NULL);
sqlite3_prepare_v2(Dummy2, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
// status.text = #"Contact added";
signaturename.text = #""; //address.text = #"";
textView.text = #"";
// imageUrl.text=#"";
} else {
// status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(Dummy2);
}
}
else
{
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Signature Name and Content Field Should Not Be Empty" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
-(IBAction)show:(id)sender{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &Dummy2) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT sname, scontent FROM profile WHERE sname=\"%#\"", signaturename.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(Dummy2, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
textView.text = addressField;
// status.text = #"Match found";
[addressField release];
} else {
// status.text = #"Match not found";
textView.text = #"";
}
sqlite3_finalize(statement);
}
sqlite3_close(Dummy2);
}
}
-(IBAction)clearFields:(id)sender
{
signaturename.text=#"";
textView.text=#"";
NSLog(#"clear is working");
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:#"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
-(IBAction) bgtouch:(id) sender
{
[signaturename resignFirstResponder];
// [textView resignFirstResponder];
}
-(IBAction) keyboard:(id)sender
{
[sender resignFirstResponder];
// [self.signaturecontent resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
imagePicker =[[UIImagePickerController alloc]init];
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"Dummy2.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &Dummy2) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS profile(ID INTEGER PRIMARY KEY AUTOINCREMENT, SNAME TEXT, SCONTENT TEXT)";
if (sqlite3_exec(Dummy2, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
// status.text = #"Failed to create table";
}
sqlite3_close(Dummy2);
} else {
// status.text = #"Failed to open/create database";
}
}
[filemgr release];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)btnLoadImage:(id)sender
{
imagePicker.delegate =self;
imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
// show the image picker
[self presentModalViewController:imagePicker animated:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image;
NSURL *mediaUrl;
mediaUrl =(NSURL *)[info valueForKey:UIImagePickerControllerMediaURL];
if(mediaUrl == nil){
image = (UIImage *)[info valueForKey:UIImagePickerControllerEditedImage];
if(mediaUrl == nil){
// original image selected
image =(UIImage *)[info valueForKey:UIImagePickerControllerOriginalImage];
// display the image
imageView.image = image;
}
else {
// edited image picked
CGRect rect = [[info valueForKey:UIImagePickerControllerCropRect]CGRectValue];
// display the image
imageView.image = image;
}
}
// hide the image picker
[picker dismissModalViewControllerAnimated:YES];
}
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
// user did not select image; hide the image picker
[picker dismissModalViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
ListView.h
#import <UIKit/UIKit.h>
#interface ListView : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *arr;
}
#property(nonatomic,retain) NSMutableArray *arr;
-(IBAction)back:(id)sender;
#end
ListView.m
#import "ListView.h"
#implementation ListView
#synthesize arr;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(IBAction)back:(id)sender
{
[super.view removeFromSuperview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 6;
return [arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *cellvalue = [arr objectAtIndex:indexPath.row];
cell.textLabel.text=cellvalue;
// Configure the cell.
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (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];
// 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
Database "Dummy2.sql" is like this
PROFILE = table
id = field = INTEGER PRIMARY KEY
sname = field = TEXT
scontent = field = TEXT
simage = field = BLOB
Schema
CREATE TABLE PROFILE(id INTEGER PRIMARY KEY, sname TEXT, scontent TEXT, simage BLOB)
This is what i have done so far, what should i code in didselectrowAtIndexpath so that when i select any name from table it should appear in textview in "ListView.xib" ... any help also i am not able to save the image in DB i have to show the image also according to the name selected from tableView in "ListView.xib" so that in bottom section i can see the image and content of that name in UIimage and in textview field .. any idea ??

If you want to pass the name to ListView just use the code below:
Create a object class for holding all data about a person like.
#interface Person
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *content;
#property (nonatomic, assign) int profileId;
#end
#implementation Person
#synthesize name,content;
#synthesize profileId;
#end
change the data fetching method like:
Person *person = nil;
NSString *updateSQL = #"SELECT * FROM PROFILE";
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(Dummy2, update_stmt, -1, &statement, NULL);
while(sqlite3_step(statement) == SQLITE_ROW) {
person = [[Person alloc] init];
[person setProfileId:(int)sqlite3_column_int(statement, 0)];
[person setName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
[person setContent:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
[hello addObject:person];
}
in the tableView class
Change the cellForRowAtIndexPath like:
Person *cellvalue = [arr objectAtIndex:indexPath.row];
cell.textLabel.text=cellvalue.name;
And the didSelectRowAtIndexPath like:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Person *selected = [arr objectAtIndex:indexPath.row];
txtView.txt = selected.content
}
1 Suggestion.
Don't save image on database, it'll make your database too heavy and database operations too slow.
1 alternative is to save image to document directory and save the path to database.

Related

How to Display data from SQlite into Table views to iPhone app

I'm working on an iPhone project in Xcode 4.3 with SQlite3, the connection between the SQlite and Xcode is done, now I want to display my data into a table views (three views) and its read only!
so I have the main table view, select raw --> take to 2nd view and load other data from the DB select raw --> take to the details view to display long text and image!
Any help appreciated.
AppDelegate.h
#import "AppDelegate.h"
#import "MasterViewController.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize navigationController = _navigationController;
- (void)dealloc
{
[_window release];
[_navigationController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"cities.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (success) {
NSLog(#"we have the database");
} else {
NSLog(#"we have no database");
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"cities.sqlite"];
BOOL moved = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:nil];
if (moved) {
NSLog(#"database copied");
}
}
MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:#"MasterViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
MasterViewController.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#class DetailViewController;
#interface MasterViewController : UITableViewController {
NSMutableArray *cities;
}
#property (strong, nonatomic) DetailViewController *detailViewController;
#end
MasterViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
students = [[NSMutableArray alloc] init];
countries = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)] autorelease];
self.navigationItem.rightBarButtonItem = addButton;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"cities.sqlite"];
sqlite3 *database;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select * from cities_info";
sqlite3_stmt *compileStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compileStatement, NULL) == SQLITE_OK) {
while (sqlite3_step(compileStatement) == SQLITE_ROW) {
NSLog(#"one record");
NSString *cityName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compileStatement, 1)];
[cities addObject:cityName];
}
NSLog(#"cities: %#",cities);
}
} else {
NSLog(#"error in database");
}
}
Blockquote
I suggest a light wrapper over SQLite - see https://github.com/JohnGoodstadt/EasySQLite
This will allow:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _personTable.rows.count;
}
AND
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
NSArray* row= _personTable.rows[indexPath.row];
cell.textLabel.text = row[[_personTable colIndex:#"lastname"]];
...
Set this up by using an iVar representing a SQL Table:
self.personTable = [_db ExecuteQuery:#"SELECT firstname , lastname , age , salary FROM person"];
And a DB Connection iVar passing in your SQL file name:
self.db = [DBController sharedDatabaseController:#"DataTable.sqlite"];
First of all, I suggest using FMDB, which is an Objective-C wrapper around sqlite3. Secondly, I'd create a custom Data Access Object with a shared instance, like so:
#interface MyDatabaseDAO : NSObject
#property (nonatomic, strong) FMDatabase *database;
#end
#implementation MyDatabaseDAO
#synthesize database = _database;
+ (MyDatabaseDAO *)instance {
static MyDatabaseDAO *_instance = nil;
#synchronized (self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)init {
self.database = [FMDatabase databaseWithPath:myDatabasePath];
[self.database open];
}
- (void)dealloc {
[self.database close];
}
#end
This DAO must have 3 access methods: one for each data object in the database. Because you weren't specific, I made these objects without any specific properties.
- (NSArray *)retrieveAllFirstViewItems {
NSMutableArray *items = [NSMutableArray array];
FMResultSet *resultSet = [FMDBDatabase.database executeQuery:#"SELECT * FROM myFirstViewItemTable"];
while ([resultSet next]) {
// extract whatever data you want from the resultset
NSString *name = [resultSet stringForColumn:#"name"]
[items addObject:name];
}
[resultSet close];
return items;
}
- (MySecondViewItem *)retrieveSecondViewItemFromIndexPath:(NSIndexPath *)indexPath {
FMResultSet *resultSet = [FMDBDatabase.database executeQuery:#"SELECT * FROM mySecondViewItemTable WHERE pid = ?", [indexPath indexAtPosition:0]];
if ([resultSet next]) {
// extract whatever data you want from the resultset
NSString *name = [resultSet stringForColumn:#"name"]
MySecondViewItem *mySecondViewItem = [[MySecondViewItem alloc]
initWithName:name withPID:[indexPath indexAtPosition:0]];
[resultSet close];
return mySecondViewItem;
} else {
return nil;
}
}
- (MyThirdViewItem *)retrieveThirdViewItemFromIndexPath:(NSIndexPath *)indexPath {
FMResultSet *resultSet = [FMDBDatabase.database executeQuery:#"SELECT * FROM mySecondViewItemTable WHERE pid = ?", [indexPath indexAtPosition:1]];
if ([resultSet next]) {
// extract whatever data you want from the resultset
NSString *name = [resultSet stringForColumn:#"name"]
MyThirdViewItem *myThirdViewItem = [[MyThirdViewItem alloc]
initWithName:name withPID:[indexPath indexAtPosition:1]];
[resultSet close];
return myThirdViewItem;
} else {
return nil;
}
}
Since it's read-only, these are all the required methods. In your first UITableView, just implement method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MySecondViewItem *mySecondViewItem = [[MyDatabaseDAO instance] retrieveSecondViewItemFromIndexPath:indexPath];
//instantiate a view from this item and use [UINavigationController pushViewController:animated:] to navigate to it
}
All that's left is just to show your data objects in views somehow. I sugget doing as much of the data retrieval as possible in the Data Access Object so that the view controllers can read the properties of the data objects without having to worry about the backend.
That's all there is to it! I hope this helped

Connecting SQlite3 to UITextview

I am doing an iPad app, were i will have UITabelview and a Button and UiTextview in same screen. My task is that if i select some row in UITableview and press button the text has to be appeared on the UITextview.
I filled few methods but it didn't work can any one let me know what exactly i can do to complete this task successfully.
Please find my code below for your reference...it may help you to explain my problem.
#import <UIKit/UIKit.h>
#import "table1.h"
#import "textView.h"
#interface searchOne : UIViewController
{
IBOutlet UITableView *firstTable;
table1 *tableOne;
textView * text1;
int row;
}
#property(nonatomic,retain)IBOutlet UIButton * search;
#property (nonatomic,retain) IBOutlet UITextView *txt;
#property(nonatomic, assign) int row;
-(IBAction)resPage:(id)sender;
#end
#import "searchOne.h"
#import "textView.h"
#implementation searchOne
#synthesize search;
#synthesize txt, row;
- (void)viewDidLoad {
[super viewDidLoad];
if (tableOne == nil) {
tableOne = [[table1 alloc] init];
}
[firstTable setDataSource:tableOne];
tableOne.view = tableOne.tableView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
row = [indexPath row];
}
-(IBAction)resPage:(id)sender{
NSString *str = txt.text;
row = [str intValue];
NSLog(#"get clicked");
self.view =txt;
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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 {
// [self setTxt:nil];
[super viewDidUnload];
}
#end
DB:
#import <Foundation/Foundation.h>
#interface db : NSObject{
NSInteger ID;
NSString * name;
}
#property (nonatomic, retain) NSString * name;
#property(nonatomic, readwrite) NSInteger ID;
-(id)initWithID: (NSInteger)i andName:(NSString *)n;
#end
#implementation db
#synthesize name,ID;
-(id)initWithID: (NSInteger)i andName:(NSString *)n{
self=[super init];
if(self)
{
self.ID = i;
self.name = n;
}
return self;
}
#end
Tabel view:
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "db.h"
#interface table1 : UITableViewController<UITableViewDataSource>{
NSString *databaseName;
NSString * databasePath;
NSMutableArray * tableOne;
}
#property(nonatomic, retain) NSMutableArray * tableOne;
-(void)checkAndCreateDatabase;
-(void)readDataFromDatabase;
#end
#import "table1.h"
#import "db.h"
#implementation table1
#synthesize tableTwo;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
databaseName=#"nobel10.db";
NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentDir = [documentPaths objectAtIndex:0];
databasePath=[documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[self readDataFromDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - TableView Data Source methods
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [tableTwo count]; }
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell= nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"mycell"];}
db * temp =(db *)[self.tableTwo objectAtIndex:indexPath.row];
cell.textLabel.text=temp.name;
return cell;
}
-(void)checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager=[NSFileManager defaultManager];
success=[fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)readDataFromDatabase{
sqlite3 *database;
tableTwo=[[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
const char *sqlStatement = "SELECT * FROM country";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK){
while (sqlite3_step(compiledStatement)==SQLITE_ROW) {
NSInteger pId = sqlite3_column_int(compiledStatement, 0);
NSString *stringName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
db *info =[[db alloc]initWithID:pId andName:stringName];
[tableTwo addObject:info];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
#end
UITextView:
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "db.h"
#interface textView : UIViewController<UITextViewDelegate>{
NSString *databaseName;
NSString * databasePath;
NSMutableArray *textOne;
NSString *description;
}
#property(nonatomic, retain) NSMutableArray *textOne;
#property (nonatomic, retain) NSString *description;
-(void)checkAndCreateDatabase;
-(void)readDataFromDatabase;
-(id)initWithDescription:(NSString *)d;
#end
#import "textView.h"
#implementation textView
#synthesize textOne, description;;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
databaseName=#"nobel10.db";
NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentDir = [documentPaths objectAtIndex:0];
databasePath=[documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[self readDataFromDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - TableView Data Source methods
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
-(void)checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager=[NSFileManager defaultManager];
success=[fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)readDataFromDatabase{
sqlite3 *database;
textOne=[[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
const char *sqlStatement = "SELECT name,item_country.id,text.item FROM country,item_country,text WHERE country.name ='India' AND country.id = item_country.id AND text.item =item_country.item ";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK){
while (sqlite3_step(compiledStatement)==SQLITE_ROW) {
NSInteger pId = sqlite3_column_int(compiledStatement, 0);
NSString *stringName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
db *info =[[db alloc]initWithID:pId andName:stringName];
[textOne addObject:info];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
-(id)initWithDescription:(NSString *)d{
self.description = d;
return self;
}
#end
PLease help me i am new to iPad development and struck here..
A quick and dirty way is just to remove the UITextView, and add it back in when you select the row. See if that works.
I realize this is not the question you asked, but depending on your needs, you might want to use Core Data instead. It abstracts the .sqlite database from you and does some pretty cool things in terms of memory usage, modelling objects and relationships and so on.

Reload TaUITableViewbleView

I have a problem, I make a TabBAr application (with navigationbar), the bar bar is a list of favorits stored in an array.
My problem is that if I change ViewController and add object to array, when I come back to UITableView it isn't reloaded...
This is the class:
-
(void)viewDidLoad {
[super viewDidLoad];
[self readArgFromDatabaseSottoArgomenti];
[self VisualizzaPreferiti];
}
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
-(void) readArgFromDatabaseSottoArgomenti {
databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"ARGOMENTI.sqlite"];
sqlite3 *databaseDesc;
// Init the argoments Array
arraySottoArgomenti = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &databaseDesc) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
// const char *sqlStatement = "select * from DESCRIZIONE ";
const char *sqlStatement = [[NSString stringWithFormat:#"SELECT * from DESCRIZIONE ORDER BY id"] UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(databaseDesc, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aIDArgomento = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescrizione = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aTesto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new argoments object with the data from the database
ContenutoObjectDescrizione *contenutoSottoArgomenti = [[ContenutoObjectDescrizione alloc] initWithName:aID idArgomento:aIDArgomento descrizione:aDescrizione testo:aTesto];
[arraySottoArgomenti addObject:contenutoSottoArgomenti];
[contenutoSottoArgomenti release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(databaseDesc);
}
- (void) VisualizzaPreferiti {
int i;
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
array = [userPref objectForKey:#"array"];
NSLog(#"Retain Count %d Numero ID Array %d",[array retainCount],[array count]);
NSMutableArray *arrayOggettoPreferito;
arrayOggettoPreferito = [[NSMutableArray alloc] init];
ContenutoObjectDescrizione *oggetto = [[ContenutoObjectDescrizione alloc] init];
for (oggetto in arraySottoArgomenti) {
for (i=0; i<[array count]; i++) {
if ([[array objectAtIndex:i] intValue] == [oggetto.id intValue]) {
[arrayOggettoPreferito addObject:oggetto];
NSLog(#"ID %# IDMateria %# Titolo %#",oggetto.id,oggetto.idArgomento,oggetto.descrizione);
}
}
}
listaPref = arrayOggettoPreferito;
arrayOggettoPreferito=nil;
[arrayOggettoPreferito release];
[oggetto release];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [listaPref count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
cell.textLabel.text = oggettoCercato.descrizione;
NSLog(#"%#",oggettoCercato.descrizione);
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
TestoViewController *testoViewController = [[TestoViewController alloc] initWithNibName:#"TestoView" bundle:nil];
[self.navigationController pushViewController:testoViewController animated:YES];
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
testoViewController.idPreferito = oggettoCercato.id;
testoViewController.title = oggettoCercato.descrizione;
NSString *descrizioneWeb = oggettoCercato.testo;
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[testoViewController.vistaWeb loadHTMLString:descrizioneWeb baseURL:baseURL];
[testoViewController release];
}
#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)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
Simply calling reloadData doesn't make it do anything unless you update your datasource. In viewWillAppear, you will need to call VisualizzaPreferiti again before you call reloadData.

viewWillAppear is never called [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
iphone viewWillAppear not firing
I have a problem, I have a tabBar / NavigationBar application. I try to use viewWillAppear but nothing. If I put a simple NSLog the console not show. Where is the problem?
-(void)viewDidLoad {
[super viewDidLoad];
[self readArgFromDatabaseSottoArgomenti];
[self VisualizzaPreferiti];
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"test");
[self VisualizzaPreferiti];
[self.tableView reloadData];
}
-(void) readArgFromDatabaseSottoArgomenti {
databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"ARGOMENTI.sqlite"];
sqlite3 *databaseDesc;
// Init the argoments Array
arraySottoArgomenti = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &databaseDesc) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
// const char *sqlStatement = "select * from DESCRIZIONE ";
const char *sqlStatement = [[NSString stringWithFormat:#"SELECT * from DESCRIZIONE ORDER BY id"] UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(databaseDesc, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aIDArgomento = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescrizione = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aTesto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new argoments object with the data from the database
ContenutoObjectDescrizione *contenutoSottoArgomenti = [[ContenutoObjectDescrizione alloc] initWithName:aID idArgomento:aIDArgomento descrizione:aDescrizione testo:aTesto];
[arraySottoArgomenti addObject:contenutoSottoArgomenti];
[contenutoSottoArgomenti release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(databaseDesc);
}
- (void) VisualizzaPreferiti {
int i;
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
array = [userPref objectForKey:#"array"];
NSLog(#"Retain Count %d Numero ID Array %d",[array retainCount],[array count]);
NSMutableArray *arrayOggettoPreferito;
arrayOggettoPreferito = [[NSMutableArray alloc] init];
ContenutoObjectDescrizione *oggetto = [[ContenutoObjectDescrizione alloc] init];
for (oggetto in arraySottoArgomenti) {
for (i=0; i<[array count]; i++) {
if ([[array objectAtIndex:i] intValue] == [oggetto.id intValue]) {
[arrayOggettoPreferito addObject:oggetto];
NSLog(#"ID %# IDMateria %# Titolo %#",oggetto.id,oggetto.idArgomento,oggetto.descrizione);
}
}
}
listaPref = arrayOggettoPreferito;
arrayOggettoPreferito=nil;
[arrayOggettoPreferito release];
[oggetto release];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [listaPref count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
cell.textLabel.text = oggettoCercato.descrizione;
NSLog(#"%#",oggettoCercato.descrizione);
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
TestoViewController *testoViewController = [[TestoViewController alloc] initWithNibName:#"TestoView" bundle:nil];
[self.navigationController pushViewController:testoViewController animated:YES];
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
testoViewController.idPreferito = oggettoCercato.id;
testoViewController.title = oggettoCercato.descrizione;
NSString *descrizioneWeb = oggettoCercato.testo;
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[testoViewController.vistaWeb loadHTMLString:descrizioneWeb baseURL:baseURL];
[testoViewController release];
}
#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)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[sup
er dealloc];
}
Add [super viewWillAppear]; and give it a try.

Adding 2 or 3 rows at a time in the database fails to add the record in iPhone

I have an application which have a system add button the navigation bar .on clicking the add button a new page opens which consists of 3 textfields named txtJourneyname, txtlocationName, txtdescription.
On this page there is a save button on the navigation so when the user enters the value in the textfields and click the save button the values are saved in the database. But I am having a problem that when I add 2 or 3 values at a time only the first value is entered in the database. I want all the values that I enter must be saved in the database.
This is my appdelegate code:
#import <UIKit/UIKit.h>
#class NewJourney;
#class JourneyController;
#interface SqltestAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
JourneyController *jList;
//this is to hold the list of journey
NSMutableArray *journeyList;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#property (nonatomic, retain) NSMutableArray *journeyList;
-(void) copyDatabaseIfNeeded;
-(NSString *)getDBPath;
-(void)removeJourney:(NewJourney *)journeyobj;
-(void)addJourney:(NewJourney *)journeyobj;
#end
.m file
#import "SqltestAppDelegate.h"
#import "JourneyController.h"
#import "NewJourney.h"
#implementation SqltestAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize journeyList;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch.
//this function is used to copy database to user's phone if needed.
[self copyDatabaseIfNeeded];
//Initializing the journeylist array.
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
self.journeyList = tempArray;
[tempArray release];
//this is function is used when once the db is copied, get the initial data to display on screen.
[NewJourney getInitialDataToDisplay:[self getDBPath]];
//configuring and displaying the window
jList = [[JourneyController alloc]initWithNibName:#"JourneyController" bundle:nil];
self.navigationController = [[[UINavigationController alloc]initWithRootViewController:jList]autorelease];
[window addSubview:self.navigationController.view];
[window makeKeyAndVisible];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[self.journeyList makeObjectsPerformSelector:#selector(saveAllData)];
[NewJourney finalizeStatements];
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[self.journeyList makeObjectsPerformSelector:#selector(saveAllData)];
}
- (void)dealloc {
[journeyList release];
[navigationController release];
[window release];
[super dealloc];
}
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
NSLog(#"%#",dbPath);
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"journey.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"journey.sqlite"];
}
- (void)removeJourney:(NewJourney *)journeyobj {
[journeyobj deleteCoffee];
[journeyList removeObject:journeyobj];
}
- (void)addJourney:(NewJourney *)journeyobj {
[journeyobj addCoffee];
[journeyList addObject:journeyobj];
}
#end
This is my newjourney class
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#interface NewJourney : NSObject
{
NSInteger journeyID;
NSString *journeyName;
NSString *locationName;
NSString *description;
BOOL isDirty;
BOOL isDetailViewHydrated;
}
#property(nonatomic, readonly)NSInteger journeyID;
#property(nonatomic, copy) NSString *journeyName;
#property(nonatomic,copy) NSString *locationName;
#property(nonatomic,copy) NSString *description;
#property(nonatomic,readwrite) BOOL isDirty;
#property(nonatomic,readwrite) BOOL isDetailViewHydrated;
+(void) getInitialDataToDisplay:(NSString*)dbPath;
+(void) finalizeStatements;
-(id) initWithPrimaryKey:(NSInteger)pk;
-(void)deleteCoffee;
-(void)addCoffee;
//-(void)hydrateDetailViewData;
-(void)saveAllData;
#end
.m
#import "NewJourney.h"
#import "SqltestAppDelegate.h"
static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
static sqlite3_stmt *addStmt = nil;
static sqlite3_stmt *detailSmt = nil;
static sqlite3_stmt *updateStmt = nil;
#implementation NewJourney
#synthesize journeyID,journeyName,locationName,description,isDirty,isDetailViewHydrated;
+(void) getInitialDataToDisplay:(NSString *)dbPath
{
SqltestAppDelegate *appDelegate =(SqltestAppDelegate *)[[UIApplication sharedApplication]delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select JourneyID,JourneyName,LocationName,Description from UserJourney";
sqlite3_stmt *selectstmt;
if (sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
NewJourney *newobj = [[NewJourney alloc]initWithPrimaryKey:primaryKey];
newobj.journeyName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
newobj.isDirty = NO;
[appDelegate.journeyList addObject:newobj];
//[appDelegate.journeyList release];
[newobj release];
}
}
}
else {
sqlite3_close(database);
}
}
+(void) finalizeStatements
{
if (database) sqlite3_close(database);
if (database) sqlite3_finalize(deleteStmt);
if (database) sqlite3_finalize(addStmt);
if (database) sqlite3_finalize(detailSmt);
if (database) sqlite3_finalize(updateStmt);
}
-(id) initWithPrimaryKey:(NSInteger)pk
{
[super init];
journeyID = pk;
isDetailViewHydrated = NO;
return self;
}
-(void) deleteCoffee
{
if (deleteStmt == nil)
{
const char *sql = "delete from UserJourney where JourneyID = ?";
if (sqlite3_prepare_v2(database, sql, -1, &deleteStmt,NULL) != SQLITE_OK)
{
NSAssert1(0,#"Error while creating delete statemnet.'%s'",sqlite3_errmsg(database));
}
//when binding parameters, index starts from 1 and not zero.
sqlite3_bind_int(deleteStmt, 1, journeyID);
if (SQLITE_DONE != sqlite3_step(deleteStmt))
{
NSAssert1(0,#"Error while deleting. '%s'",sqlite3_errmsg(database));
}
sqlite3_reset(deleteStmt);
}
}
-(void) addCoffee
{
if (addStmt == nil)
{
const char *sql = "insert into UserJourney(JourneyName,LocationName,Description) Values(?,?,?)";
if (sqlite3_prepare_v2(database, sql, -1,&addStmt , NULL) != SQLITE_OK)
{
NSAssert1(0,#"Error while creating add statement.'%s'",sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1 , [journeyName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2 , [locationName UTF8String],-1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [description UTF8String],-1, SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(addStmt))
{
NSAssert1(0,#"Error while inserting data. '%s'",sqlite3_errmsg(database));
}else
{
journeyID = sqlite3_last_insert_rowid(database);
}
sqlite3_reset(addStmt);
}
}
-(void)saveAllData
{
if (isDirty) {
if (updateStmt == nil) {
const char *sql = "update UserJourney Set JourneyName = ?,LocationName = ?,Description = ? Where JourneyID =?";
if (sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSAssert1(0,#"Error while creating update statement. '%s'",sqlite3_errmsg(database));
}
sqlite3_bind_text(updateStmt, 1, [journeyName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [locationName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3, [description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt,4, journeyID);
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(updateStmt);
isDirty = NO;
}
[journeyName release];
//this is to test whether it will work or not.
[locationName release];
[description release];
journeyName = nil;
//this is to test .
locationName = nil;
description = nil;
isDetailViewHydrated = NO;
}
- (void)setJourneyName:(NSString *)newName {
self.isDirty = YES;
[journeyName release];
journeyName= [newName copy];
}
- (void)setLocationName:(NSString *)newLocation {
self.isDirty = YES;
[locationName release];
locationName = [newLocation copy];
}
- (void)setDescription:(NSString *)newDescription {
self.isDirty = YES;
[description release];
description = [newDescription copy];
}
- (void) dealloc {
[journeyName release];
[locationName release];
[description release];
[super dealloc];
}
#end
This is my JourneyController class
#import <UIKit/UIKit.h>
#class NewJourney,AddController;
#class SqltestAppDelegate;
#interface JourneyController : UITableViewController
{
SqltestAppDelegate *appDelegate;
AddController *addController;
UINavigationController *addNavigationController;
}
#end
.m
#import "JourneyController.h"
#import "NewJourney.h"
#import "AddController.h"
#import "SqltestAppDelegate.h"
#implementation JourneyController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add_Clicked:)];
appDelegate = (SqltestAppDelegate *)[[UIApplication sharedApplication] delegate];
self.title = #"Journey List";
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [appDelegate.journeyList count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
}
//Get the object from the array.
NewJourney *newobj = [appDelegate.journeyList objectAtIndex:indexPath.row];
//Set the journeyname.
cell.textLabel.text = newobj.journeyName;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
///this is the code to get the object to delete from array.
NewJourney *newobj = [appDelegate.journeyList objectAtIndex:indexPath.row];
[appDelegate removeJourney:newobj];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.tableView reloadData];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:YES];
//Do not let the user add if the app is in edit mode.
if(editing)
self.navigationItem.leftBarButtonItem.enabled = NO;
else
self.navigationItem.leftBarButtonItem.enabled = YES;
}
- (void) add_Clicked:(id)sender {
if(addController == nil)
addController = [[AddController alloc] initWithNibName:#"AddNew" bundle:nil];
if(addNavigationController == nil)
addNavigationController = [[UINavigationController alloc] initWithRootViewController:addController];
[self.navigationController presentModalViewController:addNavigationController animated:YES];
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
#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)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[addController release];
[addNavigationController release];
[super dealloc];
}
#end
This is my addcontroller class
#import <UIKit/UIKit.h>
#class NewJourney;
#interface AddController : UIViewController {
IBOutlet UITextField *txtJourneyName;
IBOutlet UITextField *txtLocationName;
IBOutlet UITextField *txtDescription;
}
#end
.m
#import "AddController.h"
#import "NewJourney.h"
#import "SqltestAppDelegate.h"
#implementation AddController
// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Add Coffee";
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(cancel_Clicked:)] autorelease];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSave
target:self action:#selector(save_Clicked:)] autorelease];
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//Set the textboxes to empty string.
txtJourneyName.text = #"";
txtLocationName.text = #"";
txtDescription.text = #"";
//Make the coffe name textfield to be the first responder.
[txtJourneyName becomeFirstResponder];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void) save_Clicked:(id)sender {
SqltestAppDelegate *appDelegate = (SqltestAppDelegate *)[[UIApplication sharedApplication] delegate];
//Create a Coffee Object.
NewJourney *coffeeObj = [[NewJourney alloc] initWithPrimaryKey:0];
coffeeObj.journeyName = txtJourneyName.text;
//NSDecimalNumber *temp = [[NSDecimalNumber alloc] initWithString:txtPrice.text];
//coffeeObj.price = temp;
//[temp release];
coffeeObj.isDirty = NO;
coffeeObj.isDetailViewHydrated = YES;
//Add the object
[appDelegate addJourney:coffeeObj];
//Dismiss the controller.
[self.navigationController dismissModalViewControllerAnimated:YES];
}
- (void) cancel_Clicked:(id)sender {
//Dismiss the controller.
[self.navigationController dismissModalViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextField resignFirstResponder];
return YES;
}
- (void)dealloc {
[txtJourneyName release];
[txtLocationName release];
[txtDescription release];
[super dealloc];
}
#end
The code in addCoffee will only ever run once because once you have created addStmt, the next time you execute that method, the if statement causes the entire code to be omitted including the actual insert.
On a separate note, you must finalize your sqlite3 statements before closing the database.