Application crashes while displaying many images - iphone

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.

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.

How to set RGB color from database

I'm new in iphone development.i want to set uilabel's background color from the database..i already stored RGB color into the database.but i'm not getting the background color.
const char *dbpath = [database_Path UTF8String];
sqlite3_stmt *statement;
[category_array removeAllObjects];
[category_arrDictionary removeAllObjects];
if (sqlite3_open(dbpath, &Payer_DB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Expense_Category"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(Payer_DB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
// NSLog(#"%i",SQLITE_ROW);
NSMutableString *Category_Id = [[NSMutableString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSMutableString *Category_Name = [[NSMutableString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
NSMutableString *Category_Image = [[NSMutableString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
NSMutableString *Category_Color = [[NSMutableString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
NSLog(#"%#",Category_Color);
[category_arrDictionary setObject:[NSMutableArray arrayWithObjects:Category_Name,Category_Image,Category_Color,nil] forKey:Category_Id];
[category_array addObject:Category_Id];
}
}
else {
NSLog(#"Value updated");
}
sqlite3_finalize(statement);
sqlite3_close(Payer_DB);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UILabel *lblCatColor = [[UILabel alloc] initWithFrame:CGRectMake(230,10, 70, 40)];
[lblCatColor setBackgroundColor:[[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3]];
//lblCatColor.text = [[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3];
[cell.contentView addSubview:lblCatColor];
return cell;
}
try this
NSString *strflg=[[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3]];
NSArray *colorArray=[strflg componentsSeparatedByString:#","];
float red;
float green;
float blue;
for (int j=0;j<[colorArray count]; j++) {
if (j==0) {
red=[[colorArray objectAtIndex:j] floatValue];
}
else if (j==1)
{
green=[[colorArray objectAtIndex:j] floatValue];
}
else{
blue=[[colorArray objectAtIndex:j] floatValue];
}
}
[lblCatColor setBackgroundColor:[UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1.0]];
You need to write a small method to parse the string you're extracting from the DB and create a UIColor from it. You can't directly set the color of the label using a string.
its may help you
NSString *strflg=[[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3]];
NSArray *colorArray=[strflg componentsSeparatedByString:#","];
[lblCatColor setBackgroundColor:[UIColor colorWithRed:[[colorArray objectAtIndex:0] floatValue]/255.0f green:[[colorArray objectAtIndex:1] floatValue]/255.0f blue:[[colorArray objectAtIndex:2] floatValue]/255.0f alpha:1.0]];
Please try to use this one.
Your dictionary will give you a string and after that you should seperate your component and then put your red,green and blue value on the place of red,green and blue variable.
[lblCatColor setBackgroundColor:[UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1.0f]];
[[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3] returns NSString like 199.0,21.0,133.0.
The following code will help you...
NSString *colorFormat = [[category_arrDictionary valueForKey:[category_array objectAtIndex:indexPath.row]] objectAtIndex:3];
NSArray *colorArr = [[colorFormat componentsSeparatedByString:#","];
float red = [[colorArr objectAtIndex:0]floatValue];
float green = [[colorArr objectAtIndex:1]floatValue];
float blue = [[colorArr objectAtIndex:2]floatValue];
[lblCatColor setBackgroundColor:[UIColor colorWithRed:(red/255.0) green:(green/255.0) blue:(blue/255.0) alpha:1.0]];
Use following code snippet to create UIColor from NSString
NSString *rgbstr = #"123.0,104.0,238.0";
NSArray *arrRGB = [rgbstr componentsSeparatedByString:#","];
UIColor *color = [UIColor colorWithRed:[arrRGB[0] floatValue]/255.0f green:[arrRGB[1] floatValue]/255.0f blue:[arrRGB[2] floatValue]/255.0f alpha:1.0f];

Memory warning though releasing the objects

please see the following method
-(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];
//NSLog(d.photoPath);
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++;
[img1 release];
[button release];
}
[scrollView setContentSize:CGSizeMake(horizontal, vertical+200)];
[self.view addSubview:scrollView];
[scrollView release];
}
also
-(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 ";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//sqlite3_bind_int(compiledStatement, 1,memoryId);
//(compiledStatement, 1, [header UTF8String], -1, SQLITE_TRANSIENT);
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
PhotoData *data=[[PhotoData alloc]init];
//create the MemoryData object to store the data of one record
//NSLog(#"Data is retrieved using mid=%i",memoryId);
// Read the data from the result row
int pId=sqlite3_column_int(compiledStatement, 1);
NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
///filePath=[self retrievePath:filePath];
[data setPhotoId:pId];
[data setPhotoPath:filePath];
//Store every object of MemoryData in t
[photoArray addObject:data];
[filePath release];
} // end of the while
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
NSLog(#"size of array is %i",[photoArray count]);
tableArray=[[NSArray alloc]initWithArray:photoArray];
//convert the MutableArray to NSArray
}
as you can see , i am releasing all objects, why following error occurs
2011-12-04 14:48:21.367 Memorable[110:707] Received memory warning. Level=2
2011-12-04 14:48:22.084 Memorable[110:707] Received memory warning. Level=2
2011-12-04 14:48:22.247 Memorable[110:707] Received memory warning. Level=2
2011-12-04 14:48:22.255 Memorable[110:707] Received memory warning. Level=2
2011-12-04 14:48:23.507 Memorable[110:707] Received memory warning. Level=1
2011-12-04 14:48:27.188 Memorable[110:707] Received memory warning. Level=1
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /xcode3/Platforms/iPhoneOS.platform/DeviceSupport/4.3.1 (8G4)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
At first you shouldn't release filePath,
method [NSString stringWithUTF8String... returns already autoreleased object.
You create PhotoData object with alloc, so you need to
release/autorelease it
NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
[data setPhotoId:pId];
[data setPhotoPath:filePath];
[photoArray addObject:data];
//[filePath release]; <-crash here
[data release]; // <-leaks were here
I don't see you releasing the data object anywhere.
EDIT:
as beryllium stated don't release filepath as you dont own it. its an autorelease object.

Problem while scrolling Table View

I have the following problem while i scroll the table view:
NSCFString objectAtIndex:]: unrecognized selector sent to instance
I create NSDictionary tableContents and when i scroll it becomes deallocated.
This is my code:
- (void)viewDidLoad {
lessonsInGroup1 = [NSMutableArray array];
lessonsInGroup2 = [NSMutableArray array];
lessonsInGroup1 = [self grabRowsInGroup:#"1"];
lessonsInGroup2 = [self grabRowsInGroup:#"2"];
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:lessonsInGroup1,#"General Information",lessonsInGroup2,#"LaTeX Examples", nil];
//[[tableContents alloc] init];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[lessonsInGroup1 release];
[lessonsInGroup2 release];
//[table reloadData];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
- (NSMutableArray *) grabRowsInGroup:(NSString*)GroupID{
NSMutableArray *groupOfLessons;
groupOfLessons = [[NSMutableArray alloc] init];
char *sqlStatement;
int returnCode;
sqlite3_stmt *statement;
NSString *databaseName;
NSString *databasePath;
// Setup some globals
databaseName = #"TexDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
fprintf(stderr, "Error in opening the database. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
sqlStatement = sqlite3_mprintf(
"SELECT * FROM Lessons WHERE LessonGroup = '%s';", [GroupID UTF8String]);
returnCode =
sqlite3_prepare_v2(database,
sqlStatement, strlen(sqlStatement),
&statement, NULL);
if(returnCode != SQLITE_OK) {
fprintf(stderr, "Error in preparation of query. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
returnCode = sqlite3_step(statement);
while(returnCode == SQLITE_ROW) {
NSString *aLessonID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *aLessonGroup = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSString *aLessonTopic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSString *aLessonText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
NSString *aLessonCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
NSString *aLessonPicture = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
/*NSLog(aLessonID);
NSLog(aLessonGroup);
NSLog(aLessonTopic);
NSLog(aLessonText);
NSLog(aLessonCode);
NSLog(aLessonPicture);*/
// Create a new busCit object with the data from the database
Lesson *lesson = [[Lesson alloc] initWithLessonID:aLessonID LessonGroup:aLessonGroup LessonTopic:aLessonTopic LessonText:aLessonText LessonCode:aLessonCode LessonPicture:aLessonPicture];
[groupOfLessons addObject:lesson];
returnCode = sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_free(sqlStatement);
return [groupOfLessons autorelease];
}
What does your #property for tableofContents look like?
Also, you are going to run into issues with
[lessonsInGroup1 release];
[lessonsInGroup2 release];
because you are autoreleasing those in the grabRowsInGroup:
So, you don't need to call release them.
Looks like you are calling objectAtIndex on NSString. It should rather be some array

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