Multiple images not showing from database - iphone

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

Related

current image not deleting from array

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.

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.

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.

Strange crash (EXC_BAD_ACCESS) scrolling UITableView reentering app after background

I'm using an UITableView with standard cell with subtitle and UIImageView. The scrolling is ok till I exit from the app. Then it goes background (I make nothing on delegate backgroun methods) and when I rerun the app, on the same view with the uitable, the scroll it's ok for some rows then the app crash in the method:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
the code of the method is:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
ALog(#"TRACE");
}
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSDictionary *cellContent = (NSDictionary *)[self.items objectAtIndex:indexPath.row];
Restaurant * r = (Restaurant *)[cellContent valueForKey:#"ristorante"];
cell.textLabel.textColor = [UIColor colorWithRed:245.0 green:245.0 blue:245.0 alpha:0.8];
cell.textLabel.text = r.nome;
cell.detailTextLabel.textColor = [UIColor lightTextColor];
cell.detailTextLabel.text = [r.indirizzo convertToString];
UIImage *img = r.tipo.image; //[UIImage imageNamed:#"loghetto_pne.png"];
cell.imageView.image = img;
//cell.imageView.clipsToBounds = YES;
//cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
float sw= 48/img.size.width;
float sh= 48/img.size.height;
cell.imageView.transform = CGAffineTransformMakeScale(sw,sh);
//[img release];
return cell;
The crash is in the line:
cell.imageView.image = img;
From the stack trace I see that the execution goes on some internal framework code and then crash. The exception is not always the same (often is CATransaction count --> object di not respond to selector etc)
The code for Restaurant and Tipologia:
#import <Foundation/Foundation.h>
#class Zona;
#class Indirizzo;
#class Tipologia;
#interface Restaurant : NSObject {
#private
NSUInteger idx;
NSString *nome;
NSString *telefono;
Indirizzo *indirizzo;
Zona *zona;
Tipologia *tipo;
}
-(id)initWithIdx:(NSUInteger)index name:(NSString *)ristoName tel:(NSString *)ristoTel address:(Indirizzo *)ristoAdd zone:(Zona *)ristoZone;
#property (nonatomic) NSUInteger idx;
#property (nonatomic,retain) NSString *nome;
#property (nonatomic,retain) NSString *telefono;
#property (nonatomic,retain) Indirizzo *indirizzo;
#property (nonatomic,retain) Zona *zona;
#property (nonatomic,retain) Tipologia *tipo;
#end
Restaurant implementation:
#import "Restaurant.h"
#import "Zona.h"
#import "Indirizzo.h"
#import "Macro.h"
#implementation Restaurant
#synthesize idx, nome, indirizzo, telefono, zona, tipo;
-(id)initWithIdx:(NSUInteger)index name:(NSString *)ristoName tel:(NSString *)ristoTel address:(Indirizzo *)ristoAdd zone:(Zona *)ristoZone {
[self init];
bool error = NO;
if (self) {
idx = index;
nome = [ristoName retain];
telefono = [ristoTel retain];
indirizzo = [ristoAdd retain];
zona = [ristoZone retain];
}
return (error) ? nil : self;
}
- (id)init {
self = [super init];
if (self) {
idx = 0;
nome = #"";
telefono = #"";
indirizzo = nil;
zona = nil;
tipo = nil;
}
return self;
}
- (void)dealloc {
[nome release];
[indirizzo release];
[telefono release];
[zona release];
ALog(#"TRACE");
[tipo release];
ALog(#"TRACE");
[super dealloc];
}
#end
Tipologia interface and implementation:
#import <Foundation/Foundation.h>
typedef enum {
kTipoRestUnknown = 0,
kTipoRestRestaurant,
kTipoRestBrunch,
kTipoRestPizza,
kTipoRestRegional,
kTipoRestEthnic
} TipoRest;
#class ImageTest;
#interface Tipologia : NSObject {
#private
NSInteger idx;
NSString *desc;
UIImage *image;
TipoRest type;
}
-(id)initWithIndex:(NSInteger) index description:(NSString *)descr ofType:(TipoRest) type;
#property (nonatomic) NSInteger idx;
#property (nonatomic) TipoRest type;
#property (nonatomic,retain) NSString *desc;
#property (nonatomic,retain) UIImage *image;
#end
#import "Tipologia.h"
#import "Macro.h"
#implementation Tipologia
#synthesize desc, idx, image, type;
#pragma mark -
#pragma mark Memory Management
-(id)initWithIndex:(NSInteger) index description:(NSString *)descr ofType:(TipoRest) type {
self = [super init];
if (self != nil) {
self.idx = index;
self.desc = descr;
self.image = [UIImage imageNamed:#"immagineNA.png"];;
self.type = type;
}
return self;
}
-(void)dealloc {
[desc release];
desc = nil;
ALog(#"TRACE");
[image release];
image = nil;
ALog(#"TRACE");
[super dealloc];
}
-(void)release {
ALog(#"tipo.idx: %i, tipo.count: %i, tipo.imag: %#, tipo.img.count: %i", idx, [self retainCount], image, [image retainCount]);
[super release];
}
EDIT 2 Some other code. The snippet where I initialize the images based on the type
if (sqlite3_prepare_v2(db, queryStrTipo, -1, &query, NULL) == SQLITE_OK) {
restImage = [UIImage imageNamed:#"rest.png"];
pizzaImage = [UIImage imageNamed:#"pizza.png"];
etnImage = [UIImage imageNamed:#"etnico.png"];
brunchImage = [UIImage imageNamed:#"wineglass-blue.png"];
while(sqlite3_step(query) == SQLITE_ROW) {
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(query, 1)];
tipo = [[Tipologia alloc] initWithIndex:sqlite3_column_int(query, 0)
description:desc ofType:kTipoRestUnknown];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
if ([desc compare:kTipoDescRestaurant options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRestaurant;
tipo.image = restImage;
} else
if ([desc compare:kTipoDescPizza options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestPizza;
tipo.image = pizzaImage;
} else
if ([desc compare:kTipoDescEtnico options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestEthnic;
tipo.image = etnImage;
} else
if ([desc compare:kTipoDescBrunch options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestBrunch;
tipo.image = brunchImage;
} else
if ([desc compare:kTipoDescRegionale options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRegional;
}
dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:tipo.idx], #"index", tipo.desc, #"desc", nil];
[listaTipologie addObject:tipo];
[listaTemp addObject:dictionary];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
[tipo release];
[dictionary release];
}
[restImage release];
[pizzaImage release];
[etnImage release];
[brunchImage release];
}
You are missing a retain on either r.tipo, or r.tipo.image.
if they are both synthesized properties, check that the property declaration contains a retain.
If you implemented you own getters and/or setters, check that you are retaining and releasing everything properly.
Edit:
I just saw the new code you posted. Your problem is you are releasing UIImages that your code does not own. Excluding all the conditional logic you basically do this:
//Incorrect
UIImage *myImagename = [UIImage imageNamed:#"foo.png"]
yourclass.image = restImage;
[myImagename release];
This is incorrect because you never called alloc, copy or retain on the myImage object. [UIImage imageMamed] returns an autoreleased instance of a UIImage. It is the same as doing this (also incorrect):
//Incorrect
UIImage *myImagename = [[UIImage alloc] initWithImage:#"foo.png"] autorelease];
yourclass.image = restImage;
[myImagename release];
You have two options. Either manage the release yourself:
UIImage *myImagename = [UIImage alloc] initWithImage:#"foo.png"];
yourclass.image = restImage;
[myImagename release];
Or let the autoreleased object do its thing:
UIImage *myImagename = [UIImage imageNamed:#"foo.png"]
yourclass.image = restImage;
//Note: no release needed on yourClass.
In your specific code, you can take the second approach and it will look like this:
if (sqlite3_prepare_v2(db, queryStrTipo, -1, &query, NULL) == SQLITE_OK) {
restImage = [UIImage imageNamed:#"rest.png"];
pizzaImage = [UIImage imageNamed:#"pizza.png"];
etnImage = [UIImage imageNamed:#"etnico.png"];
brunchImage = [UIImage imageNamed:#"wineglass-blue.png"];
while(sqlite3_step(query) == SQLITE_ROW) {
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(query, 1)];
tipo = [[Tipologia alloc] initWithIndex:sqlite3_column_int(query, 0)
description:desc ofType:kTipoRestUnknown];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
if ([desc compare:kTipoDescRestaurant options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRestaurant;
tipo.image = restImage;
} else
if ([desc compare:kTipoDescPizza options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestPizza;
tipo.image = pizzaImage;
} else
if ([desc compare:kTipoDescEtnico options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestEthnic;
tipo.image = etnImage;
} else
if ([desc compare:kTipoDescBrunch options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestBrunch;
tipo.image = brunchImage;
} else
if ([desc compare:kTipoDescRegionale options:NSCaseInsensitiveSearch] == NSOrderedSame) {
tipo.type = kTipoRestRegional;
}
dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:tipo.idx], #"index", tipo.desc, #"desc", nil];
[listaTipologie addObject:tipo];
[listaTemp addObject:dictionary];
ALog(#"tipo.idx: %i, retain count: %i",tipo.idx, [tipo retainCount]);
[tipo release];
[dictionary release];
}
}
Remember, the golden rule of iOS memory management:
If you use any method with the word copy, alloc, or new, you need to have a corresponding release.
And, of course, Apple's Memory Management Programming Guide is the definitive resourse
I resolved the issue.
UIImage imageNamed return an autorelease object (I didn't know about it) and I use it to alloc the 4 image variables that then will be assigned to the property (via . sintax) and I release them after assigning.
Build & Analyze told me that the release statement could be wrong cause I didn't own the object anymore. Commented it out and the crash goes out...
The fault lines was the last in "EDIT 2" snippet of my question.
Thanks to all.

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