how to fetch data from sqlite database table in ios? [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i want to fetch data from my database table when i enter the name of the star in textfield the it give me all the quotes of that star for random names of star.
-(NSMutableArray *)searchAllQuotesOfStar
{
NSString *starName = [[NSString alloc] init];
// NSString *name = [NSString stringWithFormat:#"starName"];
NSMutableArray *starQuoteArray = [[NSMutableArray alloc] init];
NSString *sqlStr = [NSString stringWithFormat:#"SELECT quote FROM quotes where star like '%%starName%%'"];
//SELECT count(quote) from quotes where star like '%ac%'
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement:sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
searchStarQuoteDC *searchQoute = [[searchStarQuoteDC alloc] init];
NSString *quote = [NSString stringWithUTF8String:(char*)sqlite3_column_text(ReturnStatement, 0)];
searchQoute.quote = quote;
// NSLog(#"%#", quote);
[starQuoteArray addObject:searchQoute];
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
}
return starQuoteArray;
}

First Get Data From Sqlite Like this Below Code.
-(void)getdataMT
{
sqlite3 * database;
NSString *databasename=#"MathsTricks.sqlite"; // Your database Name.
NSArray * documentpath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
NSString * DocDir=[documentpath objectAtIndex:0];
NSString * databasepath=[DocDir stringByAppendingPathComponent:databasename];
if(sqlite3_open([databasepath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement = "SELECT * FROM Mathematicstricks"; // Your Tablename
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[name removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[name addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
And Stored it into Tableview
like this
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.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];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this.
I hope this is really helpful.

Add this code to databaseFlipsideViewController
//databaseFlipsideViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
detailController = segue.destinationViewController;
detailController.customerName = [keys objectAtIndex:indexPath.row];
NSLog(#"%#", detailController.customerName);
}
}
And my detailViewController code is this:
#implementation detailViewController
#synthesize customerLabel,code1Label,code2Label,dateLabel,customerName,code1Name;
//file path to database
-(NSString*)filePath {
NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0]stringByAppendingPathComponent:#"bp.sql"];
}
//open database
-(void)openDB {
if(sqlite3_open([[self filePath]UTF8String], &db) !=SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Databese failed to open");
}
else {
NSLog(#"database opened");
}
}
- (IBAction)back:(id)sender
{
[self.delegate detailViewControllerDidFinish:self];
}
- (void)viewDidLoad
{
[self openDB];
NSString*sql = [NSString stringWithFormat:#"SELECT theDate, customer,code1,code2 FROM summary WHERE key=\"%#\"", customerName];
const char *query_stmt = [sql UTF8String];
sqlite3_stmt*statement;
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil)==SQLITE_OK) {
if (sqlite3_step(statement)==SQLITE_ROW) {
NSString *date = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
dateLabel.text = date;
NSString *customer = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
customerLabel.text = customer;
NSString *code1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
code1Label.text = code1;
NSString *code2 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,3)];
code2Label.text = code2;
}
sqlite3_finalize(statement);
[super viewDidLoad];
}
sqlite3_close(db);
}

Related

Not calling Method didSelectRowAtIndexPath:

didSelectRowAtIndexPath: method is not calling even after connecting table delegate and DataSource to file owner.
when i am trying to print something it is not printing in this methods
find my code below for your reference:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [favorite count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell= nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"mycell"];}
db * temp =(db *)[self.favorite objectAtIndex:indexPath.row];
cell.textLabel.text=temp.name;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"b");
UITableViewCell *selectedCell = [secondTable cellForRowAtIndexPath:indexPath];
[secondTable.delegate tableView:secondTable didSelectRowAtIndexPath:indexPath];
cellText = selectedCell.textLabel.text;
NSLog(#"%#",cellText);
[fav addObject:cellText];
arrayTwo = tableTw.tableTwo;
msg = [NSString stringWithFormat: #" %# ",[arrayTwo objectAtIndex:0]];
NSLog(#"%#",[arrayTwo objectAtIndex:0]);
}
-(void)checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager=[NSFileManager defaultManager];
success=[fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(IBAction)resPage:(id)sender{
NSLog(#"%#",fav);
sqlite3 *database;
favorite=[[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
NSString *sql=[NSString stringWithFormat:#"SELECT name,item_country.id,text.text FROM country,item_country,text WHERE country.name ='%#' AND text.item = item_country.item AND country.id = item_country.id", cellText];
const char *sqlStatement = [sql UTF8String];;
sqlite3_stmt *compiledStatement;
NSLog(#"a");
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK){
NSLog(#"A");
while (sqlite3_step(compiledStatement)==SQLITE_ROW) {
d=[NSString stringWithCString:(char *)sqlite3_column_text(compiledStatement, 2) encoding:NSUTF8StringEncoding];
a= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
db *info =[[db alloc]initWithText:(NSString *)d andAg:(NSString *)a];
[favorite addObject:info];
}
}
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
if(favorite.count >0){
txt.text = [NSString stringWithFormat:#"%# ", [favorite objectAtIndex:0] ];
}}
}
- (void)viewDidLoad {
{
databaseName=#"nobel10.db";
NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentDir = [documentPaths objectAtIndex:0];
databasePath=[documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
[super viewDidLoad];
if (tableOn == nil) {
tableOn = [[table1 alloc] init];
}
if (tableTw == nil) {
tableTw = [[table2 alloc] init];
}
if (tableThre == nil) {
tableThre = [[table3 alloc] init];
}
if (tableFou == nil) {
tableFou = [[table4 alloc] init];
}
[firstTable setDataSource:tableOn];
[secondTable setDataSource:tableTw];
[thirdTable setDataSource:tableThre];
[fourthTable setDataSource:tableFou];
[fifthTable setDataSource:tableFiv];
[firstTable setDelegate:tableOn];
[secondTable setDelegate:tableTw];
[thirdTable setDelegate:tableThre];
[fourthTable setDelegate:tableFou];
tableOn.view = tableOn.tableView;
tableTw.view = tableTw.tableView;
tableThre.view = tableThre.tableView;
tableFou.view = tableFou.tableView;
{fav=[[NSMutableArray alloc]init];
cellText =[[NSString alloc]init];
secondTable=[[UITableView alloc]init];
secondTable.delegate=self;
secondTable.dataSource=self;
secondTable.tag = 20;
[self.view addSubview:secondTable];
}
}
suggestions please !
I think secondTable isn't the object you work on.Make sure it.
Add in .h file and at the dalegate calling time call dataSource.
obj_TableView.delegate = self;
obj_TableView.dataSource = self;
Then try it.

Reload TaUITableViewbleView

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

viewWillAppear is never called [duplicate]

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

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.

Selected row in UITableView shows a different result in the next TabBarViewController

I have been trying to figure out what went wrong with this segment in my code. It was working fine for a normal UITableView, which has data extracted from a local database (results after clicking a button).
However, after I used this similar code for a UITableView that shows results of a search (I was trying to do a multiple category search but failed), there has been errors, differences between the selected row and the outcome or results on the TabBarViewController.
Following is my code for the linkage to the TabBarViewController.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
Here are my full codes for you to inspect:
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
databaseName = #"funsg.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];
//NSLog([NSString stringWithFormat:#"GetData %#", databasePath]);
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"abc.sql"];
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:#"abc.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
-(void) readAttractionsFromDatabase {
[self checkAndCreateDatabase];
// Open the database
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [[NSString stringWithFormat:#"select * from everything "] UTF8String];
//NSLog([NSString stringWithFormat:#"select * from everything"]);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *bus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *location = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *mrt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *image = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *carpark = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
// Create a new animal object with the data from the database
Attraction *att = [[Attraction alloc] initWithName:desc buses:bus add:location type:type mrt:mrt image:image name:name carpark:carpark];
if (attractions == NULL)
// There should not be a NULL name
NSLog(#"Null name!!");
else {
[attractions addObject:att];
// Apparently the addObject function in NSMutableArray does not
// keep a copy of our object, so, we can't release it.
//[name release];
[att release];
}
}
sqlite3_finalize(compiledStatement); // Cleanup the statement
}
else {
NSLog(#"Error retrieving data from database.");
}
sqlite3_close(database);
}
else {
NSLog(#"Error: Can't open database!");
}
}
-(void)viewDidLoad {
[super viewDidLoad];
attractions = [[NSMutableArray alloc] init];
searchedNames = [[NSMutableArray alloc] init];
[self loadData];
}
-(void) insertToDB :(Attraction*) att {
[self checkAndCreateDatabase];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
static sqlite3_stmt *compiledStatement;
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT INTO everything (Bus,Description,Location,MRT,Name,image,type,Carpark) SELECT '%#','%#','%#','%#', '%#', '%#', '%#', '%#' WHERE NOT EXISTS (SELECT 1 FROM everything WHERE Name = '%#');", att.buses,att.desc,att.add, att.mrt, att.name, att.image, att.type , att.carpark,att.name] UTF8String], NULL, NULL, NULL);
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
-(void) loadData {
//First fetch the data from the JSON
NSURL *url = nil;
NSString *querystring = [NSString stringWithFormat:#"http://mp15.bitproj1.com/testsearch.php"];
url = [NSURL URLWithString:querystring];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
//NSLog(#"jsonreturn"); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
self.data = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (data==nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"Unable to update the data." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
self.rows =[data objectForKey:#"attractions"];
for (int i=0; i<[self.rows count]; i++) {
NSDictionary *dict = [rows objectAtIndex: i];
Attraction* a = [[Attraction alloc] initWithName:[dict objectForKey:#"Description"]
buses:[dict objectForKey:#"Bus"]
add:[dict objectForKey:#"Location"]
type:[dict objectForKey:#"type"]
mrt:[dict objectForKey:#"MRT"]
image:[dict objectForKey:#"image"]
name:[dict objectForKey:#"Name"]
carpark:[dict objectForKey:#"Carpark"]];
//Here we insert the data, when inserting we check for the duplicates. If the record already exists we do not insert. Code also must be optimized later
[self insertToDB:a];
}
}
[jsonreturn release];
[self readAttractionsFromDatabase];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return(1);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return([searchedNames 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 *cellText = [searchedNames objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[searchedNames removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] || searchText==nil) {
// Nothing to search, empty result.
[myTableView reloadData];
return;
}
for (NSString *att in attractions) {
Attraction* p = ((Attraction *)att);
NSRange r = [p.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
[searchedNames addObject:p.name];
}
}
[myTableView reloadData];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewDidUnload {
}
-(void)dealloc {
[data release];
[attractions release];
[super dealloc];
}
#end
Are you using two different array as datasource? If so, I think you are not retrieving the value from the correct array.
And also I can't understand the use of this code:
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
You can change that code as:
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
Edit
You are using two diff arrays searchedNames, attractions. There is the problem:
if(searching==YES)
{
//retrieve the values from searchedNames array
}
else
{
//retrieve the values from attractions array
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
searching=YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searching=NO;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(searching==YES)
return([searchedNames count]);
else
return [attractions 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 *cellText;
if(searching==YES)
cellText = [searchedNames objectAtIndex:indexPath.row];
else
cellText = [attractions objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}