UITableview images from Sqlite database - ios

I want to display images in a tableView from SQLite. Here is my retrieve image code from SQLite code. How do I load the images in the tableview?
-(void) retrieveData{
sqlite3 * database;
NSMutableArray *prodnamemutable = [[NSMutableArray alloc] init];
NSMutableArray *prodpricemutable = [[NSMutableArray alloc] init];
NSMutableArray *prodimagemutable = [[NSMutableArray alloc] init];
NSString *databasename=#"contacts.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 contacts"; // Your Tablename
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[prodnamemutable removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[prodnamemutable addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 1)]];
[prodpricemutable addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 3)]];
int length = sqlite3_column_bytes(compiledStatement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(compiledStatement, 0) length:length];
[prodimagemutable addObject:imageData];
NSLog(#"Length from db : %lu", (unsigned long)[imageData length]);
imageArray = [NSArray arrayWithArray:prodimagemutable];
NSLog(#"image found.%#",imageArray);
}
}
nameArray = [[NSArray alloc]initWithArray:prodnamemutable];
priceArray = [[NSArray alloc]initWithArray:prodpricemutable];
NSLog(#"nameArray:%#",nameArray);
[[self navigationController] tabBarItem].badgeValue = [NSString stringWithFormat:#"%lu",(unsigned long)[nameArray count]];
sqlite3_finalize(compiledStatement);
[self.tableView reloadData];
}
sqlite3_close(database);
}

UIImage *image = [UIImage imageWithData:data];
This will convert your image NSData to UIImage now this image can be shown on any UIImageView.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1; //count of section
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [prodimagemutable count]; //count number of row from image array.
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
cell.imageView.image = [UIImage imageWithData:[prodimagemutable objectAtIndex: indexpath.row]] ;
return cell;
}
//Below use for set height of cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;// or the height you want.
}

it will be better if you separated the code into multiple classes like the following
1. DBManager
#interface DBManager : NSObject
- (NSArray *)getImages;
#end
#implementation DBManager
- (NSArray *)getImages {
// put your code to retrieve the images from the database
// use the following to convert from NSData to UIImage
UIImage *image = [UIImage imageWithData:imageData];
}
#end
2. ImagesTableViewController
#interface ImagesTableViewController : UITableViewController
#property(nonatomic,strong) NSArray* images;
#end
#implementation ImagesTableViewController
- (void)viewDidLoad {
self.images = [dbManager getImages];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.images.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"myCell"];
}
cell.imageView.image = self.images[indexpath.row];
return cell;
}
#end

Related

It seems that my App can't retrieve info from SQL database.. why? (Xcode, Objective-C)

Function to load/read database
- (void) cargarBaseDeDatos
{
BOOL exito;
NSFileManager *filemanager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"territoriumDB.sql"];
exito = [filemanager fileExistsAtPath:writableDBPath];
if (exito) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"territoriumDB.sql"];
exito = [filemanager copyItemAtPath:defaultDBPath toPath: writableDBPath error: &error];
if(!exito)
{
NSLog(#"%#", [error localizedDescription]);
}
}
List Events class, supposed to retrieve the events title from the database and display it on a table view controller, but when I run the app the rows are blank. I already linked the table view controller to the class.
#import "ListarEventoViewController.h"
#import "AppDelegate.h"
#import <sqlite3.h>
#interface ListarEventoViewController ()
{
NSMutableArray *eventos;
}
#end
#implementation ListarEventoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
eventos = [[NSMutableArray alloc] init];
[self cargarEventos];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section
{
return [eventos count];
}
- (UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSDictionary *dic = [eventos objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [dic objectForKey:#"titulo"];
return cell;
}
- (void) cargarEventos
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
sqlite3 *database;
sqlite3_stmt *sentencia;
if (sqlite3_open([appDelegate.dataBasePath UTF8String], &database)==SQLITE_OK)
{
NSString *sentenciaSQL = [NSString stringWithFormat:#"select * from eventos"];
if(sqlite3_prepare_v2(database,[sentenciaSQL UTF8String], -1, &sentencia, NULL) == SQLITE_OK)
{
while (sqlite3_step(sentencia)==SQLITE_ROW)
{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSString *titulo = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sentencia, 0)];
[dic setValue:titulo forKey:#"titulo"];
[eventos addObject:dic];
}
}
sqlite3_finalize(sentencia);
}
sqlite3_close(database);
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
}
-(CGFloat) tableView:(UITableView*)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
return 44;
}
#end

Xcode MultipleCellSelection Selection names

I have a tableview. I want to create string from selected cell names. For example My Cell names : Row No 1 - Row No 2 - Row No 3 - Row No 4 - Row No 5. When selected Row No 1 - Row No 2 - Row No 5 mystring value = Selected Items Row No 1 , Row No 2 , Row No 5. When i deselect Row No 1 mystring value = Selected items Row No 2 , Row No 5 or Row No 5 , Row No 2. It does not matter.
Is it possible? If possible how can i do? Thanks.
//EDIT
My code is here ;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tableData = [[NSMutableArray alloc] init];
[tableData retain];
for (int i=1; i<=10; i++)
{
NSString *rowInString= [[NSString alloc ]initWithFormat:#"Row No %d",i];
[tableData addObject:rowInString];
rowInString=nil;
}
_mytable.allowsMultipleSelectionDuringEditing = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"self.Data count: %lu", (unsigned long)[tableData count]);
return tableData.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];
}
NSString *cellValue;
cellValue=[tableData objectAtIndex:[indexPath row]];
[_mytable setEditing: YES];
cell.textLabel.text=cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *selectedText = #"Selected Items";
NSArray *selectedRows = [_mytable indexPathsForSelectedRows];
NSLog(#"%lu" , (unsigned long)selectedRows.count);
}
- (void)dealloc {
[_mytable release];
[super dealloc];
}
#end
First add in your tableview.
self.myTableView.allowsMultipleSelection = YES;
then
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//you need an array in which you can add and remove strings
//adding the selected row string to array.
[stringArray addObject:[tableData objectAtIndex:[indexPath row]];
NSString *string;
for(NSString *str in stringArray)
{
string = [NSString stringWithFormat:"%#%#",string,str];
}
NSLog(#"Selected Row %#"string);
}
- (void)tableView:(UITableView *)tableView didDeSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//removing the selected string from array
for(NSString *stringInArray in stringArray)
{
if([stringInArray isEqualToString:[tableData objectAtIndex:[indexPath row]])
{
[stringArray removeObject:stringInArray];
}
}
NSString *string;
for(NSString *str in stringArray)
{
string = [NSString stringWithFormat:"%#%#",string,str];
}
NSLog(#"Selected Row %#"string);
}
Here is how you can do it:
Create a NSString *selectedText=#"Selected Items";
Now when you press a item in tableview, didselectitematibdexpath will be called.
Using the indexpath get the cell's name. Now compare if that text exist in the selectedText string. If it exist remove it from string
NSRange check = [selectedText rangeOfString:#" one"];
if (check.location != NSNotFound) {
selectedText = [selectedText stringByReplacingCharactersInRange:check withString:#""];
}
else add it to string using
selectedText=[selectedText stringWithFormat:#" %#",cellName];
Here is your code(i have changed as per your requirement):
NSString *selectedText = #"Selected Items";
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tableData = [[NSMutableArray alloc] init];
[tableData retain];
for (int i=1; i<=10; i++)
{
NSString *rowInString= [[NSString alloc ]initWithFormat:#"Row No %d",i];
[tableData addObject:rowInString];
rowInString=nil;
}
_mytable.allowsMultipleSelectionDuringEditing = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"self.Data count: %lu", (unsigned long)[tableData count]);
return tableData.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];
}
NSString *cellValue;
cellValue=[tableData objectAtIndex:[indexPath row]];
[_mytable setEditing: YES];
cell.textLabel.text=cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSRange check = [selectedText rangeOfString:[tableData objectAtIndex:[indexPath row]]];
if (check.location != NSNotFound) {
selectedText = [selectedText stringByReplacingCharactersInRange:check withString:#""];
} else {
selectedText = [NSString stringwithFormat:#"%# %#",selectedText, [tableData objectAtIndex:[indexPath row]]];
}
NSArray *selectedRows = [_mytable indexPathsForSelectedRows];
NSLog(#"%lu" , (unsigned long)selectedRows.count);
}
- (void)dealloc {
[_mytable release];
[super dealloc];
}
#end

Passing data from sqlitedatabase to a Detailview

I'm creating an iOS app which is a directory system, where on the first page I load data such as a list of some states in a tableview (from a sqlite database). When clicking on a state only the districts under that particular state have to be displayed in the detailview's tableview. My problem is that when clicking on each district the phonenumber of that district must be shown in the next view controller. Can somebody please help?
This is the firstview.
#implementation firstview
#synthesize ddetails=_ddetails;
#synthesize at,arraydata,show,table;
static firstview *_database;
+ (firstview*)database {
if (_database == nil) {
_database = [[firstview alloc] init];
}
return _database;}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [theauthors count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
menu *me = [self.theauthors objectAtIndex:indexPath.row];
cell.textLabel.text=me.state;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[_button setTitle:cellText forState:UIControlStateNormal];
menu *infos=[theauthors objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"detailViewController"] ;
_ddetails.uniqueId=infos.id;
// NSLog(#"%#",infos.state);
// NSLog(#"%d",infos.id);
[self.navigationController pushViewController:_ddetails animated:NO];
}
-(NSMutableArray *) authorList{
theauthors = [[NSMutableArray alloc]init] ;
show=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.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: %s", sqlite3_errmsg(db));
}
NSString *query =[NSString stringWithFormat:#"SELECT id,category FROM category "];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &selectstmt, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt)==SQLITE_ROW) {
menu * men = [[menu alloc] init];
men.id= sqlite3_column_int(selectstmt,0);
men.state=[NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt,1)];
[theauthors addObject:men];
// NSLog(#"%#",men.category);
// NSLog(#"%d",men.id);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return theauthors;
}
}
- (detailsnews *)Detailsnews:(int)uniqueId{
NSLog(#"%d",uniqueId);
detailsnews *get=nil;
_the=[[NSMutableArray alloc]init];
_gets=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.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: %s", sqlite3_errmsg(db));
}
NSString *sqls =[NSString stringWithFormat:#"SELECT * FROM menulist where category=%d",uniqueId];
// NSLog(#"%d",uniqueId);
sqlite3_stmt *selectstmt6;
if(sqlite3_prepare(db, [sqls UTF8String], -1, &selectstmt6, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt6)==SQLITE_ROW) {
// NSLog(#"%d",uniqueid);
int totalValue = 0;
int uniqueId = sqlite3_column_int(selectstmt6,0);
// NSLog(#"%d",uniqueid);
[_gets addObject:[NSNumber numberWithInt:uniqueId]];
for(NSNumber *number in _gets) // Use fast enumeration to iterate through the array
{
totalValue = [number intValue];
// NSLog(#"%d",totalValue);
}
char *nameChars = (char *) sqlite3_column_text(selectstmt6, 2);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
char *rec = (char *) sqlite3_column_text(selectstmt6, 1);
NSString *rece = [[NSString alloc] initWithUTF8String:rec];
// NSLog(#"%#",rece);
[_the addObject:rece];
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in _the)
{
[result appendString:[obj description]];
result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
}
//[_the addObject:[NSNumber numberWithInt:uniqueid]];
// int totalValue = 0;
// for(NSNumber *number in _the) // Use fast enumeration to iterate through the array
// {
// totalValue = [number intValue];
// NSLog(#"%d",totalValue);
// }
//
// NSMutableString * result = [[NSMutableString alloc] init];
// int totalValue = 0;
//for (NSObject * obj in _the)
// {
// [result appendString:[obj description]];
// result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
// }
//NSArray *arr=[result componentsSeparatedByString:#"\r"];
// NSMutableString * vgh = [[NSMutableString alloc] init];
// for (NSObject * obj in arr)
// {
//[vgh appendString:[obj description]];
// vgh = [arr componentsJoinedByString: #"\r"];
// }
get = [[detailsnews alloc] initWithUniqueId:totalValue district:result phonenumber:name ];
//NSLog(#"%#",_the);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return get;
}
}
detailview controller
- (void)viewDidLoad
{
[super viewDidLoad];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
if (details != nil) {
NSArray *arrComponents = [details.district componentsSeparatedByString:#"\r"];
arr = [[NSMutableArray alloc] init];
for(int i = 0; i < [arrComponents count] ;i++)
{
NSString *str = [arrComponents objectAtIndex:i];
[arr addObject:str];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[button2 setTitle:cellText forState:UIControlStateNormal];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
//NSLog(#"%d",details.uniqueId);
// NSLog(#"%#",details.rece);
// detailsnews *infos=[arr objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.uniqueId=details.uniqueId;
// NSLog(#"%d",details.uniqueId);
[self.navigationController pushViewController:_ddetails animated:NO];
}
You need to Pass the data including the phoneNumbers from first stateViewController to District and then from District to DetailsPage…I would suggest pass an NSdictionary which Includes the data from one view to another such as..In second ViewController declare a global Dictionary as mainDictionary..
and in didSelectRowAtIndexPath just pass the data as
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.mainDict=AllThe Details;
Do the same thing with PhoneNumbers also

UISearchBar not filtering sqlite UITableView

Hi I have a TableView that is populated by an sqlite database, I've set up a UISearchBar to filter it but it returns no results. Here is my code for the search bar:
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
entriesFiltered = [[NSMutableArray alloc] init];
NSString *queryPart1 = #"SELECT * FROM table WHERE name LIKE '%";
NSString *queryPart2 = #"'% ORDER BY name";
NSString *sql = [NSString stringWithFormat:#"%#%#%#", queryPart1, text, queryPart2];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW) {
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
NSString *str = [[NSString alloc]initWithFormat:#"%#", field2Str];
[entriesFiltered addObject:str ];
}
sqlite3_finalize(statement);
}
}
[self.theTable reloadData];
}
Here is the code for the table view
-(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
if(isFiltered){
return [entriesFiltered count];
} else {
return [entries count];
}
}
- (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];
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Congigure the cell...
if(isFiltered){
cell.textLabel.text = [entriesFiltered objectAtIndex:indexPath.row];
return cell;
} else {
cell.textLabel.text = [entries objectAtIndex:indexPath.row];
return cell;
}
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.theTable indexPathForSelectedRow];
NSLog(#" indexPath row %ld",(long)indexPath.row);
speakerViewController *svc = [segue destinationViewController];
svc.labelText = descriptions[indexPath.row];
svc.url = urls[indexPath.row];
}
Is the problem the sql query for searching? Would it be better to just search the array instead of querying the database? if so how would i do this?
Any help would be much appreciated.

Exception in UISearchBar

I'm trying to implement the searchBar following steps in this Video
But I got the following exception when I press the searchBar
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <Authors: 0x10960c1e0>.'
AuthorsTableViewController.h
#interface AuthorsTableViewController : UITableViewController <UISearchBarDelegate> {
NSMutableArray *authorsArray;
NSMutableArray *resultArray;
QuotesNavController *quotes;
}
#property (nonatomic, strong) IBOutlet UISearchBar *SearchBar;
#property (nonatomic, retain) NSMutableArray *authorsArray;
#property (nonatomic, retain) NSMutableArray *resultArray;
-(sqlite3 *) openDataBase;
-(IBAction)backToQuotes:(id)sender;
#end
AuthorsTableViewController.m
#import "AuthorsTableViewController.h"
#interface AuthorsTableViewController ()
#end
#implementation AuthorsTableViewController
#synthesize authorsArray, resultArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self retrieveDataFromSqlite];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)backToQuotes:(id)sender{
[self performSegueWithIdentifier:#"backToQuotes" sender:sender];
}
-(sqlite3 *) openDataBase{
sqlite3 *database;
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:#"SuccessQuotes" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}else{
NSLog(#"database opened!");
}
return database;
}
-(void) retrieveDataFromSqlite{
authorsArray = [[NSMutableArray alloc] init];
sqlite3 *myDatabase = [self openDataBase];
const char *sqlSelect = "SELECT *, COUNT(qu_author) AS count FROM authors JOIN quotes ON _auid = qu_author GROUP BY au_name ORDER BY au_name ASC";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(myDatabase, sqlSelect, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int author_id = sqlite3_column_int(compiledStatement, 0);
NSString *au_name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 1)];
NSString *au_picture = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 2)];
int quotes_id = sqlite3_column_int(compiledStatement, 3);
NSString *quotes_content = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 4)];
int quotes_author = sqlite3_column_int(compiledStatement, 5);
NSString *quotes_favorite = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 6)];
int count = sqlite3_column_int(compiledStatement, 7);
Authors *authors = [[Authors alloc] initWithUniqueId:author_id au_name:au_name au_picture:au_picture quotes_id:quotes_id quotes_content:quotes_content quotes_author:quotes_author quotes_author:quotes_author quotes_favorite:quotes_favorite count:count];
[authorsArray addObject:authors];
} // while end
}// prepare end
sqlite3_finalize(compiledStatement);
sqlite3_close(myDatabase);
}
- (void) searchThroughtData {
self.resultArray = nil;
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF like[c] %#",[NSString stringWithFormat:#"%#*",self.SearchBar.text]];
self.resultArray = [[self.authorsArray filteredArrayUsingPredicate:resultPredicate] mutableCopy];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [authorsArray count];
} else {
[self searchThroughtData];
return [resultArray count];
}
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self searchThroughtData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"authorCell";
AuthorsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[AuthorsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
Authors *temp_items;
if (tableView == self.tableView) {
temp_items = [self.authorsArray objectAtIndex:indexPath.row];
}else{
temp_items = [self.resultArray objectAtIndex:indexPath.row];
}
[cell.authorName setText:[NSString stringWithFormat:#"%#",temp_items.au_name]];
[cell.count setTitle:[NSString stringWithFormat:#"%d",temp_items.count] forState:UIControlStateNormal];
UIImage *theImage = [UIImage imageNamed:temp_items.au_picture];
cell.authorPic.image = theImage;
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:93/255.0
green:45/255.0
blue:22/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Authors *temp_items = [self.authorsArray objectAtIndex:indexPath.row];
quotes = [self.storyboard instantiateViewControllerWithIdentifier:#"QuotesNavController"];
quotes.quType = 3;
quotes.authorId = temp_items.author_id;
[self presentModalViewController:quotes animated:YES];
}
#end

Resources