Automatically suggest name(s) from contact list with respect to letter entered in textfield - iphone

I have a textfield where the user enters the name.Now when a letter is typed in the textfield,let's say "T",then how can I get suggestions of names from contact list in iphone with respect to that letter entered.
Also I need to display the appropriate number corresponding to the name entered.
I have gone through apple documentation,
Can anyone please help me out with valuable suggestions or sample code snippet:
Thanks in advance :)
EDIT
I was able to view the contacts in log(console),as I wrote the code suggested by Mr.Anil Kothari in viewDidLoad method
As suggested by Mr.Anil Kothari,I have implemented the search bar code for textfield delegate methods as follows:
- (void)textFieldDidBeginEditing:(UITextField *)atextField
{
if(searching)
return;
searching = YES;
}
- (void) searchTableView
{
textField = [self.fields objectAtIndex:0];
NSString *searchText = textField.text;
for (UIView *subview in searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]])
{
textField = (UITextField *)subview;
break;
}
}
textField.enablesReturnKeyAutomatically = NO;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
//searchArray contains matched names of friends with the searching string
for (NSString *sTemp in contactList)
{
txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
textField = [self.fields objectAtIndex:0];
txtToSearch = textField.text;
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
-(BOOL)textField:(UITextField *)atextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[copyListOfItems removeAllObjects];
if([string length] > 0)
{
searching = YES;
[self searchTableView];
}
else
{
searching = NO;
}
}
But still not working :(

Check the Code I have already done in some application this kind of stuff:-
- (void)viewDidLoad {
[super viewDidLoad];
self.tblSearchList.tableHeaderView = searchBar;
contactList=[[NSMutableArray alloc]init];
copyListOfItems=[[NSMutableArray alloc]init];
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBook );
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex( allPeople, i );
NSString *contactName =[[NSString alloc] initWithString:(NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty)];
NSLog(#"% # ",contactName);
[contactList addObject:contactName];
[contactName release];
}
}
searchBar Delegate's
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
if(searching)
return;
searching = YES;
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
[copyListOfItems removeAllObjects];
if([searchText length] > 0) {
searching = YES;
[self searchTableView];
}
else {
searching = NO;
}
[self.tblSearchList reloadData];
}
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
//searchArray contains matched names of friends with the searching string
for (NSString *sTemp in contactList)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
- (void) doneSearching_Clicked:(id)sender {
searchBar.text = #"";
[searchBar resignFirstResponder];
searching = NO;
[self.tblSearchList reloadData];
}
tableView Delegate's
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(searching)
return #"Search Results";
return #"";
}
// 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if(searching)
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
return cell;
}
fell free to ask for any further queries..

You should use UISearchBar, implement the delegate method:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
Take the letter\s from searchText and fetch the contacts using ABAddressBookRef then update the SearchDisplayController accordingly..
hope this helps a little

Related

How to pass value of db to auto complete text filed?

I created auto complete text box my problem is that how to pass array is stored value which is retrive from db
When use _category detail my app will crash .
if i'm using NSArray with objects there is no problem.
When I debug code i found problem in search method plz help to solve my problem
Thank you so much
My function
- (void)viewDidLoad
{
self.categoryDetail = [CompanyDetailDatabase database].categoryDetail;
NSMutableArray *arrt = [[NSMutableArray alloc]init];
//arrt = [NSMutableArray arrayWithArray:_categoryDetail];
arrt=[NSArray arrayWithArray:_categoryDetail];
self.pastUrls = [[NSMutableArray alloc]initWithArray:arrt];
// self.pastUrls = [[NSMutableArray alloc] initWithObjects:#"Hello1",#"Hello2",#"Hello3", nil];
self.autocompleteUrls = [[NSMutableArray alloc] init];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 50) style:UITableViewStylePlain];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
[txtProduct setDelegate:self];
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autocompleteUrls removeAllObjects];
for(NSString *curString in pastUrls)
{
NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]];
NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]];
if (substringRangeLowerCase.length !=0 || substringRangeUpperCase.length !=0)
{
[autocompleteUrls addObject:curString];
}
}
autocompleteTableView.hidden =NO;
[autocompleteTableView reloadData];
}
#pragma mark UITextFieldDelegate methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
#pragma mark UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
return autocompleteUrls.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
}
cell.textLabel.text = [autocompleteUrls objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
txtProduct.text = selectedCell.textLabel.text;
}
Now view of scene image
I'm not sure about your methods. But, it is very simple to achieve. First you've to insert some records in your database table. And, while editing on your UITextField you have to pass the text to your database table as sqlite query with your conditions and returns as NSArray or NSMutableArray Some code snippets -
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == listTableView)
{
recordsArray = [self getRecords:string];
if ([recordsArray count] == 0 || recordsArray == NULL)
{
[[[UIAlertView alloc] initWithTitle:nil message:#"No Records Were found" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil] show];
}
else
{
tableV.hidden = NO;
[tableV reloadData];
}
}
return YES;
}
Above will get your typed string and pass to database method named as getRecords with typed string.
-(NSMutableArray*)getRecords:(NSString *)srchString
{
NSMutableArray *mutArray = [[NSMutableArray alloc]init];
sqlite3 *servicesDB;
NSString *filePath=[AppDelegate dbPath];
if(sqlite3_open([filePath UTF8String], &servicesDB) == SQLITE_OK)
{
NSString *sqlStatement;
sqlStatement = [NSString stringWithFormat:#"SELECT * FROM Records WHERE record = '%%%#%%'", srchString];
const char *sql = [sqlStatement UTF8String];
sqlite3_stmt *select_statement;
if (sqlite3_prepare_v2(servicesDB, sql, -1, &select_statement, nil) == SQLITE_OK)
{
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
char *record = (char *)sqlite3_column_text(select_statement, 0);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithUTF8String:record] forKey:#"record"];
[mutArray addObject:[dict copy]];
}
}
else
{
NSLog(#"Error while fetching data. '%s'", sqlite3_errmsg(servicesDB));
}
sqlite3_finalize(select_statement);
}
sqlite3_close(servicesDB);
return mutArray;
}
Above database method will execute and fetch the data which are all having word whatever you're typed. You can find the details about LIKE clause here
You'll get your final result once the executions are completed. Simply find a sample project here

Search Bar only works in console and not in simulator

My Search Bar works in console but in the simulator doesn't work and i don't know why.
I have tried with many codes but nothing works. I'm looking for restaurant names in my tableview but when i type nothing happen, everything stays equal in the simulator.
This is my code:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if([searchText length] == 0){
[jsonObject2 removeAllObjects];
[jsonObject2 addObjectsFromArray:jsonObject];
}else{
[jsonObject2 removeAllObjects];
for(NSDictionary *dictionary in jsonObject)
{
NSObject *ob = [dictionary objectForKey:#"nombres"];
if([ob isKindOfClass: [NSString class]])
{
NSString*string=[ob description];
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[jsonObject2 addObject:ob];
NSLog(#"%#",jsonObject2);
}
}
}
}
[myTableView reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar{
[searchBar resignFirstResponder];
}
There may be two reasons for this issue
You are using jsonObject as your data source of table view. If so use jsonObject2.
If first case is wrong then may be you should log your jsonObject2 after all search component are added in that. And fix that in case it doesn't string objects in it.
I found my problem and i add this code to search textDidChange method:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if([searchText length] == 0){
[jsonObject2 removeAllObjects];
[jsonObject2 addObjectsFromArray:jsonObject];
//NSLog(#"%#",jsonObject2);
}else{
[jsonObject2 removeAllObjects];
for(NSDictionary *dictionary in jsonObject)
{
NSString*string=[dictionary objectForKey:#"nombres"];
NSRange range=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[jsonObject2 addObject:dictionary];
NSLog(#"%#",jsonObject2);
}
}
}
[myTableView reloadData];
}
First check UITableView and UISearchBar are add properly or not ??? ... and then Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following Methos of code
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
And Write in cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Foobar"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Foobar"];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.textColor = [UIColor blackColor];
}
cell.textLabel.text = [self.listOfTemArray objectAtIndex: indexPath.row];
return cell;
}
This code might helpful for you...thanks :)

UITextView Auto Complete text not i order

I have a UITextView which is connected to UITableView for Autocompletion.
The problem is the table display is not properly formatted, i have following problems with this:
the details are not in order(ex: if i press a it is not displaying words starts with a first, it display as it likes).
i have three kind of words in my txt file(like Apple, A pple, A.pple);
in my table it display only A pple and A.pple but not Apple if i start search with letter 'Ap' even it displays A pple till i write 'A P' then it stops displaying the words.
Can any one let me know what to do that?
Please find my code for your reference:
Sorry for posting all the code, i am doing because i cannot find were its going wrong!!!
- (void) finishedSearching {
[usernameField resignFirstResponder];
autoCompleteTableView.hidden = YES;
}
- (void)viewDidLoad
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"employee.txt" ofType:nil];
NSData* data = [NSData dataWithContentsOfFile:filePath];
//Convert the bytes from the file into a string
NSString* string = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
//Split the string around newline characters to create an array
NSString* delimiter = #"\n";
NSArray *item = [string componentsSeparatedByString:delimiter];
elementArray = [[NSMutableArray alloc] initWithArray:item];
usernameField = [[UITextField alloc] initWithFrame:CGRectMake(204, 405, 264, 31)];
usernameField.borderStyle = 3; // rounded, recessed rectangle
usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
usernameField.textAlignment = UITextAlignmentLeft;
usernameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
usernameField.returnKeyType = UIReturnKeyDone;
usernameField.font = [UIFont fontWithName:#"Trebuchet MS" size:20];
usernameField.textColor = [UIColor blackColor];
usernameField.placeholder=#"Login id";
[usernameField setDelegate:self];
[self.view addSubview:usernameField];
autoCompleteArray = [[NSMutableArray alloc] init];
autoCompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(204, 450, 264, tableHeight) style:UITableViewStylePlain];
autoCompleteTableView.delegate = self;
autoCompleteTableView.dataSource = self;
autoCompleteTableView.scrollEnabled = YES;
autoCompleteTableView.hidden = YES;
autoCompleteTableView.rowHeight = tableHeight;
[self.view addSubview:autoCompleteTableView];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
// Put anything that starts with this substring into the autoCompleteArray
// The items in this array is what will show up in the table view
[autoCompleteArray removeAllObjects];
for(NSString *curString in elementArray) {
NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]];
NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]];
if (substringRangeLowerCase.length != 0 || substringRangeUpperCase.length != 0) {
[autoCompleteArray addObject:curString];
}
}
autoCompleteTableView.hidden = NO;
[autoCompleteTableView reloadData];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
[self finishedSearching];
}
#pragma mark UITextFieldDelegate methods
// Close keyboard when Enter or Done is pressed
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
BOOL isDone = YES;
if (isDone) {
[self finishedSearching];
return YES;
} else {
return NO;
}
}
// String in Search textfield
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
#pragma mark UITableViewDelegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
//Resize auto complete table based on how many elements will be displayed in the table
if (autoCompleteArray.count >=3) {
autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight*3);
return autoCompleteArray.count;
}
else if (autoCompleteArray.count == 2) {
autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight*2);
return autoCompleteArray.count;
}
else {
autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight);
return autoCompleteArray.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] ;
}
cell.textLabel.text = [autoCompleteArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
usernameField.text = selectedCell.textLabel.text;
usernameField.text=[usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"%#",usernameField.text);
[self finishedSearching];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
Thanks in Advance!!!!
follow this code.. U have done all correctly but searching the element is the problem. U have written the code. if your checking length alone. if its not null it will show data. but u have to compare the first letter with element array. so that it works fine.
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
[autocompleteArray removeAllObjects];
for(NSString *curString in elementArray) {
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[autocompleteArray addObject:curString];
}
[autocompleteTableView reloadData];
}
}

search bar not working?

i have a SQL file where 5 different type of data is stored. I am adding this data in a dictionary specified with keys. and then i am adding this dictionary to tableData array as a dataSource for table and searchBar. But it is not searching anything.
adding code below
- (void)viewDidLoad {
[super viewDidLoad];
dataSource =[[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc]init];
searchedData = [[NSMutableArray alloc]init];
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Vegetables"];
SQLite *sqlObj1 = [[SQLite alloc] initWithSQLFile:#"ShoppersWorld.sqlite"];
[sqlObj1 openDb];
[sqlObj1 readDb:query];
// [query release];
for (int i=0; i<[dataSource count]; i++) {
NSLog(#"data:%#",[dataSource objectAtIndex:i]);
}
while ([sqlObj1 hasNextRow])
{
NSString *name=[sqlObj1 getColumn:1 type:#"text"];
NSString *price=[sqlObj1 getColumn:2 type:#"text"];
NSString *quantity=[sqlObj1 getColumn:3 type:#"text"];
NSString *unit=[sqlObj1 getColumn:4 type:#"text"];
NSString *total=[sqlObj1 getColumn:5 type:#"text"];
dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: name,#"nameOfVegetables",
price,#"priceOfVegetables",
quantity,#"quantityOfVegetables",
unit,#"unitOfVegetables",
total,#"totalPriceOfVegetables",nil];
//NSLog(#"results:%# %#",dict);
[dataSource addObject:dict];
}
[tableData addObjectsFromArray:dataSource];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
// Configure the cell.
else {
cell.productLbl.text= [NSString stringWithFormat:#"%#",[[tableData objectAtIndex:indexPath.row]objectForKey:#"nameOfVegetables"] ];
cell.bPriceLbl.text = [NSString stringWithFormat:#"Rs %d/Kg",
[[[tableData objectAtIndex:indexPath.row] objectForKey:#"priceOfVegetables"] intValue]];
cell.qtyLbl.text = [NSString stringWithFormat:#"QTY: %# %#",[[tableData objectAtIndex:indexPath.row]
objectForKey:#"quantityOfVegetables"],[[tableData objectAtIndex:indexPath.row] objectForKey:#"unitOfVegetables"]] ;
cell.tPriceLbl.text = [NSString stringWithFormat:#"TOTAL: %#",[[tableData objectAtIndex:indexPath.row]
objectForKey:#"totalPriceOfVegetables"]];
}
return cell;
}
#pragma search operations
- (IBAction)search:(id)sender{
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,40,320,30)];
sBar.delegate = self;
[self.view addSubview:sBar];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
// only show the status bar’s cancel button while in edit mode
[sBar setShowsCancelButton:YES animated:YES];
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
[sBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] || searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
for (int i = 0; i < [dataSource count]; i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [dataSource objectAtIndex:i];
NSString *name = [NSString stringWithFormat:#"%#", [temp valueForKey:#"nameOfVegetables"]];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
sBar.hidden= YES;
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
[tableData addObjectsFromArray:dataSource];
#try{
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
In search delegate methods you manipulate not with searchedData but tableData array. As these name suggest, array searchedData is supposed to store filtered data.
By the way, your approach to use sqlite for data source and absorbing all database into array is wrong. In cellForRowAtIndexPath read from sqlite database only data you need at the moment.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// load from sqlite only data for this cell.
// Use searchBar.text with sqlite's LIKE to filter data from database
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = #"SignsCellIdentifier";
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSString *sql = [NSString stringWithFormat:#"SELECT fieldNameFromTable FROM TableName WHERE FieldToLookForIn LIKE \"%%%#%%\" LIMIT 1 OFFSET %u", searchBar.text ? searchBar.text : #"", row];
sqlite3_stmt *stmt;
int res = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
if (res != SQLITE_OK) {
NSLog(#"sqlite3_prepare_v2() failed"];
return nil;
}
if (sqlite3_step(stmt) == SQLITE_ROW) {
const unsigned char *name = sqlite3_column_text(stmt, 0);
cell.text = [NSString stringWithUTF8String:(const char*)name];
}
sqlite3_finalize(stmt);
return cell;
}
How to apply search in this approach? In textDidChange do nothing but call [tableView reloadData]. And in cellForRowAtIndexPath load data with sqlite LIKE using searchBar.text as search term. So reloadData will load only filtered records. searchBarSearchButtonClicked will call only resignFirstResponder of it's caller, removing keyboard off screen. It doesn't need to do anything more because search is already done. searchBarCancelButtonClicked will set text property of it's caller to nil, call reload data and again call resignFirstResponder.
- (void)searchBarCancelButtonClicked:(UISearchBar *)s {
s.text = nil;
[tableView reloadData];
[s resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)s {
// search is already done
[s resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[tableView reloadData];
}
numberOfRowsInSection should also request db with the same SELECT as in cellForRowAtIndexPath, but with SELECT COUNT. Writing this method will be your homework)

iPhone TableView Search XML

I have a question about adding XML to the searchbar in a tableview. I can get all the external XML file to load in the tableview, but when I hit the searchbar up top, and hit a letter, it crashes.
I think it's something really simple that I'm doing wrong. In my RootViewController, there's a function called searchTableView. I feel like that's where it's not picking up the search items. I think it's somewhere around the objectForKey:#"title". When I debug, I get this error message also: "NSCFArray objectForKey unrecognized selector". Here's my searchTableView function:
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"title"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
Ok figured it out. For some reason this was really hard to find documentation how to do this.
Here's my RootViewController.m below.
My pList is configured as:
Root (Array)
Item0 (Dictionary)
Name (String)
Item1 (Dictionary)
Name (String)..
Here's my code, hopefully this helps anyone else looking for help on this:
#implementation RootViewController
#synthesize listOfItems, copyListOfItems;
- (void)viewDidLoad {
[super viewDidLoad];
//Initialize the array.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"plistArray" ofType:#"plist"];
NSMutableArray* tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
self.listOfItems = tmpArray;
[tmpArray release];
//Initialize the copy array.
copyListOfItems = [[NSMutableArray alloc] init];
//Set the title
self.navigationItem.title = #"Search";
//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searching = NO;
letUserSelectRow = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (searching)
return 1;
else
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
else {
//Number of rows it should expect should be based on the section
return [listOfItems count];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Get the selected country
NSString *selectedCountry = nil;
if(searching)
selectedCountry = [copyListOfItems objectAtIndex:indexPath.row];
else {
// Navigation logic may go here. Create and push another view controller.
}
NSDictionary *dictionary = [self.listOfItems objectAtIndex:indexPath.row];
FoodDetail *dvController = [[FoodDetail alloc] initWithNibName:#"FoodDetail" bundle:nil andDictionary: dictionary];
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
}
// 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
if(searching)
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
else {
cell.textLabel.text = [[self.listOfItems objectAtIndex:indexPath.row]
objectForKey:#"Name"];
}
return cell;
}
- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(letUserSelectRow)
return indexPath;
else
return nil;
}
#pragma mark -
#pragma mark Search Bar
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from the detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
searching = YES;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)] autorelease];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
//Remove all objects first.
[copyListOfItems removeAllObjects];
if([searchText length] > 0) {
[ovController.view removeFromSuperview];
searching = YES;
letUserSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchTableView];
}
else {
[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
searching = NO;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchTableView];
}
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSString *text1 = [dictionary objectForKey:#"Name"];
[searchArray addObject:text1];
}
NSLog(#"%s: searchArray=%#", __func__, searchArray);
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
- (void) doneSearching_Clicked:(id)sender {
searchBar.text = #"";
[searchBar resignFirstResponder];
letUserSelectRow = YES;
searching = NO;
self.navigationItem.rightBarButtonItem = nil;
self.tableView.scrollEnabled = YES;
[ovController.view removeFromSuperview];
[ovController release];
ovController = nil;
[self.tableView reloadData];
}
- (void)dealloc {
[ovController release];
[copyListOfItems release];
[searchBar release];
[listOfItems release];
[super dealloc];
}
#end