How to set RGB color from database - iphone

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];

Related

iphone+UIscrollview or to use uitableview to display image in matrix format

I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html

Populate the table view sections with rows of table in sqlite database in an order

I have 2 view controller pages.Add Reminder page which contains save button as right bar button of navigation bar
I have earlier got issues regarding number of sections in table view for view reminder page based on number of saves in add reminder page:
I found out the solution for generating cells based on number of saved reminders
this is the code:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)view
{
NSInteger numTableRecords = -1;
sqlite3_stmt *statement;
if (sqlite3_open([self.databasePath UTF8String], &remindersDB) == SQLITE_OK)
{
NSString *sqlStatement = [NSString stringWithFormat: #"select count(*) from reminders"];
const char *sql = [sqlStatement cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(remindersDB, sql, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
numTableRecords = sqlite3_column_int(statement, 0);
}
}
else
{
printf("could not prepare statement: %s\n", sqlite3_errmsg(remindersDB));
}
}
else
{
NSLog(#"Error in Opening Database File");
}
sqlite3_close(remindersDB);
return numTableRecords;
}
Now my problem here is I am able to retrieve the data,but not in a proper way.I mean this is the code I used to retrieve the data
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellId] autorelease];
view.backgroundColor = [UIColor clearColor];
cell.backgroundColor = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:#"reminderbutton.png"]];
label1 = [[[UILabel alloc]initWithFrame:CGRectMake(26, 3, 30, 40)]autorelease];
label1.backgroundColor = [UIColor clearColor];
label1.textColor = [UIColor whiteColor];
label2 = [[[UILabel alloc]initWithFrame:CGRectMake(45, 3, 100, 40)]autorelease];
label2.backgroundColor = [UIColor clearColor];
label2.textColor = [UIColor whiteColor];
label3 = [[[UILabel alloc]initWithFrame:CGRectMake(119, 3, 100, 40)]autorelease];
label3.backgroundColor = [UIColor clearColor];
label3.textColor = [UIColor whiteColor];
label4 = [[[UILabel alloc]initWithFrame:CGRectMake(198, 3, 120, 40)]autorelease];
label4.backgroundColor = [UIColor clearColor];
label4.textColor = [UIColor whiteColor];
//Retrieve the values of database
const char *dbpath = [self.databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &remindersDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT * from reminders ORDER BY id"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(self.remindersDB ,query_stmt , -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *ID = [[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]autorelease];
NSString *nameField = [[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)]autorelease];
NSString *eventField = [[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]autorelease];
NSString *dateField = [[[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]autorelease];
label1.text = ID;
label2.text = nameField;
label3.text = eventField;
label4.text = dateField;
}
sqlite3_finalize(statement);
}
sqlite3_close(self.remindersDB);
}
[cell addSubview:label1];
[cell addSubview:label2];
[cell addSubview:label3];
[cell addSubview:label4];
}
return cell;
I have inserted 4 reminders,the 4 cells are appearing,but the problem is with displaying
It is appearing as following
How can I get the 4 reminders displayed in 4 cells consecutively,I mean the 1st reminder on 1st,2nd reminder on 2nd and so on..
Please help me to fix this issue,thanks all in advance :)
Sorry all...I found out the complete solution to the issue in the following link:
Retrieve all rows inserted in sqlite database and display in table view cells containing labels as subviews with different sections
Sorry for the question...Thanks every one who viewed this,take it If useful
Hence I am not removing this question,bye TC :)
I'm giving you one suggestion just try it. I hope it will work.
Do one thing, just retrieve data from sqlite in viewDidAppear or viewWillAppear and save the data in an nsmutableArray.
Then in - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section just return [yourArray count].
and for reloading table just try with [self.tableview reloadData]
I hope it'll be work. just let me know for any further clarification.
for making cell with that required color just write the following code in
cell.contentView.backgroundColor=[UIColor colorWithPatternImage:#"Give your cell image"]
in (UITableViewCell *)tableView:(UITableView *)view cellForRowAtIndexPath:(NSIndexPath *)indexPath
method and not in condition, outside the condition you should put it. and why you do database work in this method. it will slow your apps. let me know for any clarification.

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 can I add "load more" option to table view

My App is having a table which is populated by Sqlite DB contains huge amount of data
So it causes lazy loading in the table view
Here is the code
- (void) searchData {
//i=0;
[newSearchBar setShowsCancelButton:YES animated:YES];
NSLog(#"search data started ");
NSLog(#" checking value %#",newSearchBar.text);
NSString *databaseName = #"imeating.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDir=[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"with in if sqlite3 open");
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement ;
const char *sqlStatement ;
/* if ([searchFlag isEqualToString:#"DEF"])
{
sqlStatement = "select subitem_name, subitem_detail_id from subitem_detail limit 200" ;
}
else
{*/
sqlStatement = "select category_id, upper(subitem_name), subitem_detail_id, protein, carbohydrates, fat, calorie from subitem_detail where subitem_name LIKE ? order by subitem_name limit ?,?" ;
NSLog(#"inside search b4 wildsearch %#",searchString);
wildSearch = [NSString stringWithFormat:#"%#%#",searchString, #"%"];
NSLog(#"wildsearch %#",wildSearch);
[newSearchBar setShowsCancelButton:YES animated:YES];
//NSLog(#"inside search : %#", wildSearch);
//}
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSLog(#"with in if sqlite3 prepare v2");
// if (![searchFlag isEqualToString:#"DEF"])
// {
sqlite3_bind_text(compiledStatement, 1, [wildSearch UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(compiledStatement, 2, llimit);
sqlite3_bind_int(compiledStatement, 3, ulimit);
// }
// Loop through the results and add it to array
if (llimit <200){
NSLog(#"with in if limit < 200");
itemArray = [[NSMutableArray alloc] init] ;
}
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
//NSLog(#" while sqlite3 step");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] ;
//[itemDic release];
//itemDic = nil ;
itemDic = [[[NSMutableDictionary alloc] init] autorelease];
NSString *categoryId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *itemName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *itemId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *protein = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *carbo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *fat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *calorie = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
/* NSLog(#"itemname : %#", itemName);
NSLog(#"itemid : %#", itemId);
NSLog(#"\n");*/
[itemDic setObject:categoryId forKey:#"categoryId"];
[itemDic setObject:itemId forKey:#"itemId"];
[itemDic setObject:itemName forKey:#"itemName"];
[itemDic setObject:protein forKey:#"protein"];
[itemDic setObject:carbo forKey:#"carbohydrate"];
[itemDic setObject:fat forKey:#"fat"];
[itemDic setObject:calorie forKey:#"calorie"];
[itemArray addObject:itemDic];
if (ulimit%200 == 0)
{
//activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActionSheetStyleDefault];
//[activity startAnimating];
[newTableView reloadData];
//[newSearchBar setShowsCancelButton:YES animated:YES];
//NSLog(#"list all views after 1st reload: %#", [self.navigationController.viewControllers description]);
//[newTableView addSubview:activity];
//[activity stopAnimating];
//[activity release];
//NSLog(#" with in if");
}
[pool drain];
} /*else
{
UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:#"Error" message:#"sqlite rows not returned" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] ;
[alert show];
}*/
}
} else
{
UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:#"Error" message:#"DataBase Path doesn't exists" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] ;
[alert show];
}
//NSLog(#"itemArray desc : %#",[itemArray description]);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//NSLog(#"Inside number of sections in tableview");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [itemArray count] ;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
//NSLog(#"indexpath row val : %d", indexPath.row);
tableIndex = indexPath ;
//NSLog(#"print indexpath row : %d", indexPath.row);
//NSLog(#"print limit : %d", limit);
if (indexPath.row > limit)
{
llimit = llimit+200 ;
ulimit = ulimit+200 ;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//[opq cancelAllOperations];
NSLog(#"before ns operation");
opq = [NSOperationQueue new];
//opq = [[NSOperationQueue alloc] init];
//[opq setMaxConcurrentOperationCount:2];
// [self performSelectorOnMainThread:#selector(searchData) withObject:nil waitUntilDone:YES];
NSInvocationOperation *op = [[[NSInvocationOperation alloc] initWithTarget:self selector:#selector(searchData) object:nil] autorelease];
[opq addOperation:op];
NSLog(#"after ns operation");
//[op release];
//[opq release];
[pool drain];
i++;
limit = limit + 120 ;
NSLog(#"i=%d",i);
//[cell setText:[[itemArray objectAtIndex:indexPath.row] valueForKey:#"itemName"]];
}
// Configure the cell.
//[cell setText:[[itemArray objectAtIndex:indexPath.row] valueForKey:#"itemName"]];
cell.textLabel.text = [[itemArray objectAtIndex:indexPath.row] valueForKey:#"itemName"] ;
NSString *pval, *cval, *fval, *cal ;
if ([[[itemArray objectAtIndex:indexPath.row] valueForKey:#"protein"] length] <= 5)
pval = [[itemArray objectAtIndex:indexPath.row] valueForKey:#"protein"];
else
pval = [[[itemArray objectAtIndex:indexPath.row] valueForKey:#"protein"] substringWithRange:NSMakeRange(0, 5)];
if ([[[itemArray objectAtIndex:indexPath.row] valueForKey:#"carbohydrate"] length] <= 5)
cval = [[itemArray objectAtIndex:indexPath.row] valueForKey:#"carbohydrate"];
else
cval = [[[itemArray objectAtIndex:indexPath.row] valueForKey:#"carbohydrate"] substringWithRange:NSMakeRange(0, 5)];
if ([[[itemArray objectAtIndex:indexPath.row] valueForKey:#"fat"] length] <= 5)
fval = [[itemArray objectAtIndex:indexPath.row] valueForKey:#"fat"];
else
fval = [[[itemArray objectAtIndex:indexPath.row] valueForKey:#"fat"] substringWithRange:NSMakeRange(0, 5)];
if ([[[itemArray objectAtIndex:indexPath.row] valueForKey:#"calorie"] length] <= 5)
cal = [[itemArray objectAtIndex:indexPath.row] valueForKey:#"calorie"];
else
cal = [[[itemArray objectAtIndex:indexPath.row] valueForKey:#"calorie"] substringWithRange:NSMakeRange(0, 5)];
cell.detailTextLabel.text =
[NSString stringWithFormat:#"Prot: %# Carb: %# Fat: %# Cal: %#", pval, cval, fval, cal] ;
return cell;
}
I need "load more" button in the row for my table view to load records from sqlite DB in particular period of limit
Add a + 1 to the numbers of rows in section:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [itemArray count] + 1;
}
Then in the cellforrowatindexpath, see if the indexPath.row is bigger than [itemArray count]. If it is, then put the text "Load more..." as that cell's title.
In the didSelectRowAtIndexPath, see if the indexPath.row is equal to [itemArray count]. If that is the case, then add x more results to the itemArray and then call [tableView reloadData].
For some UI improvement you can add a UIActivityIndicator on top of the table view to show that some processing is going on in the background.

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