current image not deleting from array - iphone

I stored multiple images in database. And i fetched the images using SQLite and added these to array. When i click the button it displays the array of images under scrollview. In scrollview when i click particular image it goes to center of the screen. Center of the screen images having another imageview. When i delete particular image from array, the current image is not deleting.
code:
SQLiteManager:
Table name: SimpleTbl
id sm descrip photo
1 sm1 ok BLOB(size:2345)
2 sm2 ok1 BLOB(size:3245)
3 sm3 ok2 BLOB(size:4535)
.h file:
#interface Mysof : NSObject{
NSInteger sofId;
NSString *sof;
NSString *rating;
UIImage *photo;
}
#property (nonatomic,retain)NSString *sofa;
#property (nonatomic, assign) NSInteger sofaId;
#property (nonatomic, retain)NSString *rating;
#property (nonatomic, retain) UIImage *photo;
.m file:
- (NSMutableArray *) getMylists{
NSMutableArray *sArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"Sample.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
;
const char *sql = "SELECT * FROM SimpleTbl";
NSLog(#"sql is %s", sql);
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Mysof *Mylist = [[Mysof alloc]init];
Mylist.sofId = sqlite3_column_int(sqlStatement, 0);
Mylist.sof = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
Mylist.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
const char *raw = sqlite3_column_blob(sqlStatement, 3);
int rawLen = sqlite3_column_bytes(sqlStatement, 3);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
Mylist.photo = [[UIImage alloc] initWithData:data];
[sArray addObject:Mylist];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return sArray;
}
}
Then viewcontroller i display the fetching image to imageview via button click:
-(void)click:(id)sender{
for (int i = 0; i<[self.arraysofs count]; i++ ) {
NSLog(#"index %d",i);
// imgView1=[[UIButton alloc]initWithFrame:CGRectMake(20+(i*74), 500, 72, 72)];
imgView1=[[UIButton alloc]initWithFrame:CGRectMake(20+(i*74), 0, 72, 72)];
Width = Width + 20+(i*74);
[imgView1 setTag:i+1];
[imgView1 addTarget:self action:#selector(arraysofsClicked:) forControlEvents:UIControlEventTouchUpInside];
[imgView1 setImage:((Mysof *)[self.arraysofs objectAtIndex:i]).photo forState:UIControlStateNormal];
[scrollview addSubview:imgView1];
// [myScroll addSubview:imgView1];
}
}
It displays the center of the screen:
-(void)arraysofsClicked:(id)sender{
NSLog(#"button %d is clicked.", [sender tag]-1);
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(50,50,150,150)];
[mmageView setUserInteractionEnabled:YES];
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:[sender tag]-1]).photo];
[self.view addSubview:mmageView];
UILongPressGestureRecognizer *dblongpress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(dblongPress:)];
[mmageView addGestureRecognizer:dblongpress];
}
Long press for deleting images from center of the screen:
-(void)dblongPress:(UILongPressGestureRecognizer*)sender{
// NSLog(#"button %d is clicked.", [send tag]-1);
// [mmageView setImage:((Mysof *) [self.sofas objectAtIndex:[send tag]-1]).photo];
[mmageView removeFromSuperview];
}
If two images on the center of the screen, when i click first images the second is removing.

The imageview you are seeing after deleting is the older one which you added earlier. This is because every time you press the button, it calls -(void)arraysofsClicked, and a new instance of the imageview is added there.
Solution is:
put this in viewDidLoad
mnageView = nil;
& Change this method
-(void)arraysofsClicked:(id)sender{
// chcek is mnageView is initialized before or not
if(mmageView == nil) {
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(50,50,150,150)];
[mmageView setUserInteractionEnabled:YES];
[self.view addSubview:mmageView];
UILongPressGestureRecognizer *dblongpress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(dblongPress:)];
[mmageView addGestureRecognizer:dblongpress];
}
// change image here
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:[sender tag]-1]).photo];
}
declare the mnageView globally in case you are not doing so. but from your code it seems you are declaring it globally.

Related

Multiple images not showing from database

I stored all the images in SQLiteManager for local database. I need to show all images in viewcontroller. But when i was fetching images from database it showing only one images. I don't use any webservice.
code:
SQLiteManager:
Table name: SimpleTbl
id sm descrip photo
1 sm1 ok BLOB(size:2345)
2 sm2 ok1 BLOB(size:3245)
3 sm3 ok2 BLOB(size:4535)
.h file:
#interface Mysof : NSObject{
NSInteger sofId;
NSString *sof;
NSString *rating;
UIImage *photo;
}
#property (nonatomic,retain)NSString *sofa;
#property (nonatomic, assign) NSInteger sofaId;
#property (nonatomic, retain)NSString *rating;
#property (nonatomic, retain) UIImage *photo;
.m file:
- (NSMutableArray *) getMylists{
NSMutableArray *sArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"Sample.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
;
const char *sql = "SELECT * FROM SimpleTbl";
NSLog(#"sql is %s", sql);
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Mysof *Mylist = [[Mysof alloc]init];
Mylist.sofId = sqlite3_column_int(sqlStatement, 0);
Mylist.sof = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
Mylist.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
const char *raw = sqlite3_column_blob(sqlStatement, 3);
int rawLen = sqlite3_column_bytes(sqlStatement, 3);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
Mylist.photo = [[UIImage alloc] initWithData:data];
[sArray addObject:Mylist];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return sArray;
}
}
Then viewcontroller i display the fetching image to imageview via button click:
-(void)click:(id)sender{
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(20, 52, 72, 72)];
// UIImageView *mmageView=[UIImageView alloc];
// [mmageView setFrame:CGRectMake(20, 52, 75, 75)];
[self.view addSubview:mmageView];
Soflistsql * mysofs =[[Soflistsql alloc] init];
self.arraysofs = [mysofs getMyLists];
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:0]).photo];
}
scrollview:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint scrollOffset=scrollView.contentOffset;
///at any time, it will have only 3 pages loaded- previous, current and next
if(pageOnScrollView < ((int)scrollOffset.x/320))
{
//unload
if(pageOnScrollView>1)[self unloadPreviousPage:pageOnScrollView-2];
[self loadNextPage:((int)scrollOffset.x/320)+1];
else if(pageOnScrollView > ((int)scrollOffset.x/320))
{
//unload
if(pageOnScrollView<(NUM_PAGES-2))[self unloadPreviousPage:pageOnScrollView+2];
[self loadNextPage:((int)scrollOffset.x/320)-1];
}
pageOnScrollView=scrollOffset.x/320;
}
-(void)unloadPreviousPage:(int)index
{
for (int index = 0; index<[self.arraysofs count]; index++ ) {
[[myScrollView viewWithTag:index+1] removeFromSuperview];
}
}
-(void)loadNextPage:(int)index
{
int countFlag=0;
for (int index = 0; index<[self.arraysofs count]; index++ ) {
NSLog(#"index %d",index);
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake((320*index)+countFlag*80+ 2, 5, 75, 75)];
[self.view addSubview:mmageView];
mmageView.tag=index+1;
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:index]).photo];
}
[myScrollView addSubview:mmageView];
countFlag++;
}
1) log the Array count and check the items count.
2) then make a for loop like this
for (int index = 0; index < [self.arraysofs count]; index ++ ) {
NSLog(#"index %d",index);
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(20+(index*74), 52, 72, 72)];
[self.view addSubview:mmageView];
Soflistsql * mysofs =[[Soflistsql alloc] init];
self.arraysofs = [mysofs getMyLists];
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:index]).photo];
}
check this to add images on a scroll view Adding UIImageViews to UIScrollView

Save data on form and display using table view using DB

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.

UIScrollView updating/loading wrongly

Im making a preview in my ViewController that all my Picked images in imagePicker will be in my scrollView,
Yes, I was able to make a preview of it in thumbnail, But when I'm logging it in my debugger, it seems to be that everytime my viewDidAppear, it also reAdds the scrollView, so the images count is being added again, making it harder to delete in view due to overlaping of the images. What I needed is to just refresh the scrollview whenever the view appears and when I'm adding a new image/s.
Here is a sneak preview of those codes I'm having problems for a long time:
- (id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
_images = [[NSMutableArray alloc] init];
_thumbs = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
[self createScrollView];
}
- (void) createScrollView {
[scrollView setNeedsDisplay];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
}
- (void)viewDidLoad
{
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 310, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,130.0f)];
[slotBg addSubview:self.scrollView];
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
}
Help would be much appreciated.
And would using this be much of help, removing then adding. Or is this a way to just completely remove/delete all those subview completely, then REadd?
Thanks for those whose gonna help.
And could this be helpful? Thankyou
for(UIView *subview in [scrollView subviews]) {
if([subview isKindOfClass:[UIView class]]) {
[subview removeFromSuperview];
} else {
}
}
DELETE:
- (void)deleteItem:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
[_images removeObject:button];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
}
Here is a working example : Google Code
I wrote out the code, and I have this. It will align the view to be 5 wide, and however tall it has to be, and the scrollview will change height.
You will need to create a new NSMutableArray named _buttons that will contain a list of your buttons.
- (void)addImage:(UIImage *)imageToAdd {
[_images addObject:imageToAdd];
[_thumbs addObject:[imageToAdd imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
int row = floor(([views count] - 1) / 5);
int column = (([views count] - 1) - (row * 5));
UIImage *thumb = [_thumbs objectAtIndex:[_thumbs count]-1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside];
button.tag = [views count] - 1;
// This is the title of where they were created, so we can see them move.s
[button setTitle:[NSString stringWithFormat:#"%d, %d", row, column] forState:UIControlStateNormal];
[_buttons addObject:button];
[scrollView addSubview:button];
// This will add 10px padding on the bottom as well as the top and left.
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
- (void)deleteItem:(id)sender {
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[views removeObjectAtIndex:button.tag];
[_buttons removeObjectAtIndex:button.tag];
[self rearrangeButtons:button.tag];
}
- (void)rearrangeButtons:(int)fromTag {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > fromTag) {
button.tag -= 1;
}
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
}
}
Note: In the rearrangeButtons method, it is possible to animate the changes.
Here is the code to rearrange the files:
- (void)rearrangeButtons:(int)fromTag {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > fromTag) {
// Create name string
NSString *imageName = [NSString stringWithFormat:#"images%i.png", button.tag];
// Load image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFile = [paths objectAtIndex:0];
NSSting *oldFilePath = [documentFile stringByAppendingPathComponent:imageName];
NSData *data = [[NSData alloc] initWithContentsOfFile:oldFilePath];
button.tag -= 1;
// Save the image with the new tag/name
NSString *newImageName = [NSString stringWithFormat:#"images%i.png", button.tag];
NSString *newFilePath = [documentFile stringByAppendingPathComponent:newImageName];
[data writeToFile:newFilePath atomically:YES];
// Delete the old one
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *err = nil;
if (![fileManager removeItemAtPath:file error:&err]) {
// Error deleting file
}
}
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
}
}

Application crashes while displaying many images

Please review following code
-(void)addScrollView{
[self selectData];
scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(5, 00, 320, 480)];
int counter=5;
float y=40.0f;
int fullLength=[photoArray count];
int horizontal=320;
int vertical=(fullLength/4)*80;
int c1=1;
for(int c=0;c<[photoArray count];c++){
PhotoData *d=[photoArray objectAtIndex:c];
if(c1==5){
counter=5;
y=y+80.0f;
c1=1;
}
UIImage *img1=[[UIImage alloc]initWithContentsOfFile:d.photoPath];
UIButton* button = [[UIButton alloc] init];
button.tag=c;
[button setBackgroundImage:img1 forState:UIControlStateNormal];
[button setFrame:CGRectMake(counter, y, 70.0, 70.0)];
[button addTarget:self action:#selector(showDetail:)
forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
counter=counter+78.0f;
c1++;
[button release];
[img1 release];
[d release];
}
[scrollView setContentSize:CGSizeMake(horizontal, vertical+200)];
[self.view addSubview:scrollView];
[scrollView release];
}
-(void)selectData{
//This method is defined to retrieve data from Database
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
//Obtained the path of Documennt directory which is editable
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"memory.sql"];
//memory.sql is sqlite file which is used as local database
photoArray=[[NSMutableArray alloc]init];
NSString *dbPath=filePath;
sqlite3 *database;
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from photo where mid=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiledStatement, 1,memoryId);
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
PhotoData *data=[[PhotoData alloc]init];
int pId=sqlite3_column_int(compiledStatement, 1);
NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
[data setPhotoId:pId];
[data setPhotoPath:filePath];
[photoArray addObject:data];
[filePath release];
} // end of the while
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
tableArray=[[NSArray alloc]initWithArray:photoArray];
paths=nil;
documentsPath=nil;
filePath=nil;
dbPath=nil;
}
Some times application crashes by giving data formatter error
You should not release object that was returned by objectAtIndex: if you have not retained it. SO try to remove line:
[d release];
You should release that object after adding it to photoArray. Do it after line :
[photoArray addObject:data];
[data release];
You should do that because your data object is not autoreleased (PhotoData *data=[[PhotoData alloc]init];) and after adding it to photoArray it is automatically retained.

how to connect with sqlite in iphone? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am developing an application in iphone and am new to iphone.
Kindly let me know the code for open/close/update/delete database record in iphone using sqlite?
Regards,
Vijaya
import
In .h file
- (void)createEditableCopyOfDatabaseIfNeeded;
+ (sqlite3 *) getNewDBConnection;
Add the following code in appdelegate.m in didFinishLaunching method:
[self createEditableCopyOfDatabaseIfNeeded];
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Scores.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Scores.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message ‘%#’.", [error localizedDescription]);
}
}
+ (sqlite3 *) getNewDBConnection {
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Scores.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
In your view controller call the method of insertion etc. here i called a method which brings me the data from table
sqlite3* db =[iMemory_SharpenerAppDelegate getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sql = "select * from HighScore";
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK) {
NSAssert1(0,#"error prepearing statement",sqlite3_errmsg(db));
} else {
while (sqlite3_step(statement)==SQLITE_ROW) {
//dt= [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
dt = [NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement, 0)];
//dt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSLog(#"%#score==",dt);
[nmber addObject:dt];
}
}
sqlite3_finalize(statement);
sqlite3_close(db);
Read the sqlite documentation on their website. They have API references and tutorials. All you need to get going in XCode is to add the libsqlite3.dylib to the referenced frameworks.
Here is a sample code to connect SQLite from iOS:(insertion of data)
Source:http://sickprogrammersarea.blogspot.in/2014/03/sqlite-in-ios-using-objective-c.html
#import "sqlLiteDemoViewController.h"
#interface sqlLiteDemoViewController (){
UILabel *lblName;
UILabel *lblRoll;
UILabel *lblAge;
UITextField *txtName;
UITextField *txtroll;
UISlider *sldAge;
}
#end
#implementation sqlLiteDemoViewController
- (void)viewDidLoad
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:#"student.db"]];
NSLog(#"%#",_databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt ="CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ROLL TEXT, AGE TEXT)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(_contactDB);
NSLog(#"Connection Successful");
} else {
NSLog(#"Failed to open/create database");
}
}
UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapped)];
[self.view addGestureRecognizer:tapScroll];
[super viewDidLoad];
lblName = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 50)];
lblName.backgroundColor = [UIColor clearColor];
lblName.textColor=[UIColor blackColor];
lblName.text = #"Name";
[self.view addSubview:lblName];
lblRoll = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 100, 50)];
lblRoll.backgroundColor = [UIColor clearColor];
lblRoll.textColor=[UIColor blackColor];
lblRoll.text = #"Roll no";
[self.view addSubview:lblRoll];
lblAge = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, 100, 50)];
lblAge.backgroundColor = [UIColor clearColor];
lblAge.textColor=[UIColor blackColor];
lblAge.text = #"Age";
[self.view addSubview:lblAge];
txtName = [[UITextField alloc] initWithFrame:CGRectMake(80, 40, 200, 40)];
txtName.borderStyle = UITextBorderStyleRoundedRect;
txtName.font = [UIFont systemFontOfSize:15];
txtName.placeholder = #"Specify Name";
txtName.autocorrectionType = UITextAutocorrectionTypeNo;
txtName.keyboardType = UIKeyboardTypeDefault;
txtName.returnKeyType = UIReturnKeyDone;
txtName.clearButtonMode = UITextFieldViewModeWhileEditing;
txtName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtName.delegate = self;
[self.view addSubview:txtName];
txtroll = [[UITextField alloc] initWithFrame:CGRectMake(80, 90, 200, 40)];
txtroll.borderStyle = UITextBorderStyleRoundedRect;
txtroll.font = [UIFont systemFontOfSize:15];
txtroll.placeholder = #"Specify Roll";
txtroll.autocorrectionType = UITextAutocorrectionTypeNo;
txtroll.keyboardType = UIKeyboardTypeNumberPad;
txtroll.returnKeyType = UIReturnKeyDone;
txtroll.clearButtonMode = UITextFieldViewModeWhileEditing;
txtroll.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtroll.delegate = self;
[self.view addSubview:txtroll];
CGRect frame = CGRectMake(80.0, 140.0, 200.0, 40.0);
sldAge= [[UISlider alloc] initWithFrame:frame];
[sldAge setBackgroundColor:[UIColor clearColor]];
sldAge.minimumValue = 0;
sldAge.maximumValue = 30;
sldAge.continuous = YES;
sldAge.value = 15.0;
[self.view addSubview:sldAge];
UIButton *subButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
subButton.frame = CGRectMake(80.0, 200.0, 80.0, 30.0);
[subButton setTitle:#"Store" forState:UIControlStateNormal];
subButton.backgroundColor = [UIColor clearColor];
[subButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[subButton addTarget:self action:#selector(store:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:subButton];
UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame = CGRectMake(200.0, 200.0, 80.0, 30.0);
[srchButton setTitle:#"Search" forState:UIControlStateNormal];
srchButton.backgroundColor = [UIColor clearColor];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[srchButton addTarget:self action:#selector(find:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:srchButton];
}
- (void)tapped {
[self.view endEditing:YES];
}
-(void)store:(id)sender{
#try{
NSLog(#"store called");
sqlite3_stmt *statement;
const char *dbpath = (const char *)[_databasePath UTF8String];
NSString *age=[NSString stringWithFormat:#"%g", sldAge.value];
NSLog(#"Age is %#",age);
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO STUDENT (name, roll , age) VALUES (\"%#\", \"%#\", \"%#\")",
txtName.text, txtroll.text, age];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Insertion Successful");
} else {
NSLog(#"Insertion Failure");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}#catch (NSException *e) {
NSLog(#"Exception : %s",sqlite3_errmsg(_contactDB));
}
}
- (void) find:(id)sender
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT roll, age FROM STUDENT WHERE name=\"%#\"",txtName.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *roll = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
txtroll.text = roll;
NSString *age = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
sldAge.value = [age floatValue];
NSLog(#"Match found");
} else {
NSLog(#"Match found");
txtroll.text = #"";
sldAge.value = 0.0;
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
}
ViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface ViewController
{
IBOutlet UITextField *no;
UITextField *name,*address;
IBOutlet UIButton *save,*update,*del,*clear,*Find,*showdata;
sqlite3 *contactDB;
IBOutlet UILabel *status;
}
#property (strong, nonatomic) IBOutlet UITextField *no;
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *address;
#property (retain, nonatomic) IBOutlet UILabel *status;
- (IBAction)SaveData:(id)sender;
- (IBAction)FindData:(id)sender;
- (IBAction)UpdateData:(id)sender;
- (IBAction)DeleteData:(id)sender;
- (IBAction)ClearData:(id)sender;
- (IBAction)ShowData:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import "ShowRecord.h"
#interface ViewController ()
{
NSString *docsDir;
NSArray *dirPaths;
NSString *databasePath;
}
#end
#implementation ViewController
#synthesize name, address,status,no;
- (void)viewDidLoad
{
[self LoadDB];
[status setHidden:TRUE];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
self.name = nil;
self.address = nil;
self.status = nil;
}
-(void)LoadDB
{
// 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:#"student.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS stud (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = #"Failed to create table";
}
else
{
status.text = #"success Created table";
}
sqlite3_close(contactDB);
}
else
{
status.text = #"Failed to open/create database";
}
}
}
- (IBAction)SaveData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO stud (name, address) VALUES (\"%#\", \"%#\")", name.text, address.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = #"Contact added";
name.text = #"";
address.text = #"";
}
else
{
status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (IBAction)UpdateData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
NSString *updateSQl=[NSString stringWithFormat:#"update stud set name=\"%#\",address=\"%#\" where id=\"%#\" ",name.text,address.text,no.text];
const char *update_stmt=[updateSQl UTF8String];
sqlite3_prepare_v2(contactDB, update_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
status.text=#"Record Updated";
name.text=#"";
address.text=#"";
no.text=#"";
}
else
{
status.text=#"Record Not Updated";
}
}
}
- (IBAction)DeleteData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) {
NSString *deleteSql=[NSString stringWithFormat:#"delete from stud where id=\"%#\"",no.text];
const char *delete_stmt=[deleteSql UTF8String];
sqlite3_prepare_v2(contactDB, delete_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE)
{
status.text=#"Record Deleted";
name.text=#"";
address.text=#"";
no.text=#"";
}
else
{
status.text=#"Record Not Deleted ";
}
}
}
- (IBAction)ClearData:(id)sender
{
name.text=#"";
no.text=#"";
address.text=#"";
}
- (IBAction)ShowData:(id)sender
{
ShowRecord *showrecord=[[ShowRecord alloc]initWithNibName:#"ShowRecord" bundle:nil];
[self. pushViewController:showrecord animated:YES];
// ShowRecord *vc1 = [[ShowRecord alloc] initWithNibName:#"ViewControllerNext" bundle:nil];
//[self.navigationController pushViewController:vc1 animated:YES];
}
- (IBAction)FindData:(id)sender
{
[status setHidden:false];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT name,address FROM stud WHERE id=\"%#\"",
no.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *namefield=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
NSString *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
name.text=namefield;
address.text = addressField;
status.text = #"Record Found";
}
else
{
status.text = #"Record Not Found";
address.text = #"";
name.text=#"";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
#end