search in Sqlite then display result in table view

Discussion in 'iOS Programming' started by ITCreative, Nov 28, 2011.

  1. ITCreative macrumors member

    Joined:
    Aug 4, 2011
    #1
    in my project i use search bar i want take search kay from user then display match in table view

    in interface :

    Code:
    
    IBOutlet UITableView *libraryTV;
    IBOutlet UISearchBar *searchBar; //search bar
    
         // Database variables
    
         NSString *databaseName;
    
         NSString *databasePath;
    
         NSString *keysearch;
    
         NSMutableArray *sbook;     
    
         NSString *title;
    
         NSString *authorName;
    
         NSString *pubName;
    
         NSString *info;
         BOOL searching;
    

    in implementation :


    Code:
    - (void)viewDidLoad {
    
         
    
         databaseName = @"iKSUdataBase.db";
    
         
    
         // 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];
    
         
    
         sbook = [[NSMutableArray alloc]init];
    
         searching = NO;
    
    
     [super viewDidLoad];
    
    }
    
    
    
    
    
    
    
    #pragma mark -
    
    #pragma mark Table view data source
    
    
    
    
    
    - (NSInteger)tableView:(UITableView *)tableView 
    
     numberOfRowsInSection:(NSInteger)section {
    
         
    
         if (searching)
    
         {
    
         
    
         return [sbook count];
    
              
    
         }
    
         else return 1;
    
         
    
    }
    
    
    
    - (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 = [sbook objectAtIndex:indexPath.row];     
    
         }
    
         
    
         return cell;
    
         
    
    }
    
    
    
    
    
    -(void) checkAndCreateDatabase{
    
         // Check if the SQL database has already been saved to the users phone, if not then copy it over
    
         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];
    
         
    
         // If the database already exists then return without doing anything
    
         if(success) return;
    
         
    
         // If not then proceed to copy the database from the application to the users filesystem
    
         
    
         // Get the path to the database in the application package
    
         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) readbookFromDatabase {
    
         // Setup the database object
    
         sqlite3 *database;
    
         
    
         
    
         
    
         // Open the database from the users filessytem
    
         if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    
              // Setup the SQL Statement and compile it for faster access
    
              
    
              
    
               NSString *sqlS =[NSString stringWithFormat: @"select book.title,author.auth_name ,publisher.pub_name , book.info from book ,author, publisher where book.auth_id = author.auth_id and book.pub_id = publisher.pub_id and book.title =%@ ",keysearch];
    
              const char *sqlStatement = [sqlS UTF8String];
    
                        
    
               
    
              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
    
                        
    
                        char * str = (char*)sqlite3_column_text(compiledStatement, 0);
    
                        if (str){
    
                        title = [NSString stringWithUTF8String:str];
    
                        }
    
                        else{
    
                      title =@" ";
    
                        }
    
                        
    
                        char * str1 = (char*)sqlite3_column_text(compiledStatement, 1);
    
                        if (str1){
    
                             authorName = [NSString stringWithUTF8String:str1];
    
                        }
    
                        else{
    
                        authorName =@" ";
    
                        }
    
                        
    
                        char * str2 = (char*)sqlite3_column_text(compiledStatement, 2);
    
                        if (str2){
    
                             pubName = [NSString stringWithUTF8String:str2];
    
                        }
    
                        else{
    
                   pubName =@" ";
    
                        }
    
                        
    
                        char * str3 = (char*)sqlite3_column_text(compiledStatement,3);
    
                        if (str3){
    
                   info = [NSString stringWithUTF8String:str3];
    
                        }
    
                        else{
    
                        info =@" ";
    
                        }
    
                        
    
                        // Create a new book object with the data from the database
    
                        
    
                        book *bok  = [[book alloc] initWithbook:title autname:authorName pubname:pubName infobook:info];
    
    
    
                        
    
                        [sbook addObject:bok];
    
                        
    
                        [bok release];
    
                   }
    
              }
    
              // Release the compiled statement from memory
    
              sqlite3_finalize(compiledStatement);
    
              
    
         }
    
         sqlite3_close(database);
    
         
    
    }
    
    #pragma mark UISearchBarDelegate
    
    
    
    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
    
    
    
    {
    
         // only show the status bar’s cancel button while in edit mode
    
         
    
         searchBar.showsCancelButton = YES;
    
         searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    
              
    
         // flush the previous search content
    
    [sbook removeAllObjects];
    
    }
    
    
    
    - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
    
    
    
    {
    
         
    
         searchBar.showsCancelButton = NO;
    
         
    
    }
    
    
    
    
    
    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
    
    
    
    {
    
         
    
         [sbook removeAllObjects];// remove all data that belongs to previous search
    
         if([searchText isEqualToString:@""]|| searchText==nil){
    
    [libraryTV reloadData];
    
              
    
              return;
    
              
    
         }
    
         
    
    
    
              
    
              keysearch = searchBar.text;
    
              [self checkAndCreateDatabase];
    
              [self readbookFromDatabase];
    
         searching = YES;
    
         [libraryTV reloadData];
    
    for(NSInteger i=0;i<sbook.count;i++)
    
              
    
         {
    
              book *bok = (book *)[self.sbook objectAtIndex:i];
    
              NSString *name =bok.book_title;
    
              NSString *auth = bok.author_name;
    
              NSString *pub = bok.pub_name;
    
              
    
              NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    
              
    
              NSRange r = [name rangeOfString:searchText];
    
              NSRange a = [auth rangeOfString:searchText];
    
              NSRange p = [pub rangeOfString:searchText];
    
              
    
              if((r.location != NSNotFound) || (a.location != NSNotFound) || (p.location != NSNotFound))
    
                   
    
              {
    
                   
    
                   if((r.location== 0)||(a.location== 0)||(p.location== 0))
    
                        
    
                   {
    
                        
    
                        [sbook addObject:bok];
    
                        
    
                   }
    
                   
    
              }
    
                        
    
              [pool release];
    
              
    
         }
    
         
    
         [libraryTV reloadData];
    
         
    
         
    
    }
    
    
    
    -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
    
    
    
    {
    
         
    
         
    
         // if a valid search was entered but the user wanted to cancel, bring back the main list content
    
         
    
         [sbook removeAllObjects];
    
    @try{
    
              
    
         [libraryTV reloadData];
    
              
    
         }
    
         
    
         @catch(NSException *e){
    
              
    
         }
    
         
    
         [searchBar resignFirstResponder];
    
         
    
         searchBar.text = @" ";
    
         
    
    }
    
    
    
    // called when Search (in our case “Done”) button pressed
    
    
    
    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    
    
    
    {
    
         
    
         [searchBar resignFirstResponder];    
    
    }
    
    

    but No result how i can do this ? :(
     
  2. 1458279 Suspended

    1458279

    Joined:
    May 1, 2010
    Location:
    California
    #2
    When you say no results, you mean no results from the search or the results from the search don't display in the table.
    I just did one of these and got it working well. I might be able to help, just let me know if your problem is getting info into the table or out of the database.
     
  3. ITCreative thread starter macrumors member

    Joined:
    Aug 4, 2011
    #3
    my problem when enter key search in search bar my app is close

    when i open console


    i didn't know where is problem in code
     
  4. 1458279 Suspended

    1458279

    Joined:
    May 1, 2010
    Location:
    California
    #4
    I just posted the complete code for one that works. I didn't post the or attach the .db, but you can pretty much cut and paste the code into your app, change the fields to yours and it should run.

    Look for my name as the thread starter, I just posted to it, so it's near the top.

    Hope that helps!

    I can post some directions for the .db sql file if you want, just ask.
     
  5. ITCreative thread starter macrumors member

    Joined:
    Aug 4, 2011
    #5
    Thank you very mucccch for your help :eek:

    really i'm tried with this part because i didn't know what is wrong :(
     

Share This Page