Attendance app with a database problem

Discussion in 'iOS Programming' started by leaf777, Oct 24, 2012.

  1. leaf777, Oct 24, 2012
    Last edited: Oct 24, 2012

    leaf777 macrumors newbie

    Joined:
    Apr 25, 2011
    #1
    Hello, I am trying to make an app that will take attendance for a classroom and I am having some problems with creating a database for the data. I am starting with taking attendance for only two seats. I have been only using the simple title of HelloWorld for the project so far.

    I have been trying to do this by having button where a user can enter a student's name and assign it to a seat. I want to record this information into a database and eventually have the database have a present or absent category.

    I have been able to assign a student to a seat but I have not been able to store or recall this data in a database.

    I have tried two different ways so far. The first way was with two separate header and implementation files. The label for the seat updated but the debug console did not give me any output for the database.

    The second way, with one header and implementation file, has given me a little better of a console output for the database with the following:

    2012-10-25 00:56:34.158 HelloWorld[1599:11303] seat 1 - user 30

    The problem is that I entered in a different name than "seat 1" (using the simulator) and this did not update in the database. To sum it up, the entered text does update to the label, but it does not update the database.

    Code:
    #import <UIKit/UIKit.h>
    #import "sqlite3.h"
    
    @interface HelloWorldViewController : UIViewController
    <UITextFieldDelegate>
    
    //database
    
    {
        sqlite3 *db;
    }
    
    -(NSString *) filePath;
    
    
    //seat 1
    
    - (IBAction)changeGreeting:(id)sender;
    @property (weak, nonatomic) IBOutlet UITextField *textField;
    @property (weak, nonatomic) IBOutlet UILabel *label;
    @property (copy, nonatomic) NSString *userName;
    
    
    
    //seat 2
    - (IBAction)changeGreeting2:(id)sender;
    @property (weak, nonatomic) IBOutlet UITextField *textField2;
    @property (weak, nonatomic) IBOutlet UILabel *label2;
    @property (copy, nonatomic) NSString *userName2;
    
    
    
    
    @end
    
    Code:
    #import "HelloWorldViewController.h"
    
    
    @interface HelloWorldViewController ()
    
    @end
    
    @implementation HelloWorldViewController
    
    @synthesize userName = _userName;
    @synthesize userName2 = _userName2;
    
    //database
    
    - (void)viewDidLoad
    {
        self.userName = self.textField.text;
        
        NSString *nameString = self.userName;
        
        if ([nameString length] == 0) {
            
            nameString = @"1";
        }
        
        NSString *greeting = [[NSString alloc] initWithFormat:@"%@", nameString];
        
        self.label.text = greeting;
        [super viewDidLoad];
    	// Do any additional setup after loading the view, typically from a nib.
        [self openDB];
        [self createTableNamed:@"Students" withField1:@"seat" withField2:@"name"];
    	
    	for (int i=1; i<=2; i++) {
            NSString *seat = [[NSString alloc] initWithFormat:
                              @"seat %@",nameString];              // import namestring
    		
            NSString *name = [[NSString alloc] initWithFormat: @"user %d",i];
            [self insertRecordIntoTableNamed:@"Students"
    							  withField1:@"seat" field1Value:seat
    							   andField2:@"name" field2Value:name];
            
        }
    	
    	[self getAllRowsFromTableNamed:@"Students"];
        sqlite3_close(db);
    	
        [super viewDidLoad];
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    // actions and buttons
    
    - (IBAction)changeGreeting:(id)sender {
        
        self.userName = self.textField.text;
        
        NSString *nameString = self.userName;
        
        if ([nameString length] == 0) {
            
            nameString = @"1";
        }
        
        NSString *greeting = [[NSString alloc] initWithFormat:@"%@", nameString];
        
        self.label.text = greeting;
        
    }
    
    - (IBAction)changeGreeting2:(id)sender {
        
        self.userName2 = self.textField2.text;
        
        NSString *nameString2 = self.userName2;
        
        if ([nameString2 length] == 0) {
            
            nameString2 = @"2";
        }
        
        NSString *greeting2 = [[NSString alloc] initWithFormat:@"%@", nameString2];
        
        self.label2.text = greeting2;
    }
    
    
    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == self.textField) {
            [theTextField resignFirstResponder];
        }
        
        if (theTextField == self.textField2) {
            [theTextField resignFirstResponder];
        }
        
        return YES; }
    
    //database continued
    
    -(NSString *) filePath {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                             NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];
        return [documentsDir stringByAppendingPathComponent:@"database.sql"];
    }
    
    -(void) openDB {
        //—-create database—-
        if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK ) {
    	    sqlite3_close(db);
    	    NSAssert(0, @"Database failed to open.");
    	}
    }
    
    -(void) createTableNamed:(NSString *) tableName
                  withField1:(NSString *) field1
                  withField2:(NSString *) field2 {
    	char *err;
        NSString *sql = [NSString stringWithFormat:
    					 @"CREATE TABLE IF NOT EXISTS '%@' ('%@' TEXT PRIMARY KEY, '%@' TEXT);",
    					 tableName, field1, field2];
    	
        if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
            sqlite3_close(db);
            NSAssert(0, @"Tabled failed to create.");
        }
    }
    
    -(void) insertRecordIntoTableNamed:(NSString *) tableName
                            withField1:(NSString *) field1
                           field1Value:(NSString *) field1Value
                             andField2:(NSString *) field2
                           field2Value:(NSString *) field2Value {
    	/*
         NSString *sql = [NSString stringWithFormat:
         @"INSERT OR REPLACE INTO '%@' ('%@', '%@') VALUES ('%@','%@')",
         tableName, field1, field2, field1Value, field2Value];
    	 
         char *err;
         if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
         sqlite3_close(db);
         NSAssert(0, @"Error updating table.");
         }
         */
        
    	NSString *sqlStr = [NSString stringWithFormat:
    						@"INSERT OR REPLACE INTO '%@' ('%@', '%@') VALUES (?,?)",
    						tableName, field1, field2];
    	
    	const char *sql = [sqlStr UTF8String];
    	sqlite3_stmt *statement;
    	
        if (sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK) {
            sqlite3_bind_text(statement, 1, [field1Value UTF8String], -1, NULL);
            sqlite3_bind_text(statement, 2, [field2Value UTF8String], -1, NULL);
        }
    	
    	if (sqlite3_step(statement) != SQLITE_DONE)
            NSAssert(0, @"Error updating table.");
        sqlite3_finalize(statement);
    }
    
    
    -(void) getAllRowsFromTableNamed: (NSString *) tableName {
        //—-retrieve rows—-
        NSString *qsql = [NSString stringWithFormat:@"SELECT * FROM %@", tableName];
        sqlite3_stmt *statement;
    	
        if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                char *field1 = (char *) sqlite3_column_text(statement, 0);
                NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
    			
                char *field2 = (char *) sqlite3_column_text(statement, 1);
                NSString *field2Str = [[NSString alloc] initWithUTF8String: field2];
    			
    			NSString *str = [[NSString alloc] initWithFormat:@"%@ - %@",
    							 field1Str, field2Str];
                NSLog(@"%@", str);
    			
                
            }
    		
            //—-deletes the compiled statement from memory—-
            sqlite3_finalize(statement);
        }
    }
    
    
    - (void)viewDidUnload {
    	// Release any retained subviews of the main view.
    	// e.g. self.myOutlet = nil;
    }
    
    
    
        
    
    @end
    
    

    I thank you for your help and apologize if I have not been clear enough.
     
  2. waterskier2007 macrumors 68000

    waterskier2007

    Joined:
    Jun 19, 2007
    Location:
    White Lake, MI
    #2
    How come it looks like the majority of what is happening in your code happens in the viewDidLoad section? You are getting the seat and name before the user has even had a chance to interact with the view.
     
  3. leaf777 thread starter macrumors newbie

    Joined:
    Apr 25, 2011
    #3
    Thanks for the tip! You hit the nail on the head. I moved a lot of the code related to creating the seat and name from the viewDidLoad section to the IBAction method.

    This caused the action of the button press to become linked with the database and the debug console is now giving me better results.

    Now I have to tweak and debug to get the exact results I want.

    Thanks again I truly appreciate it.
     
  4. waterskier2007 macrumors 68000

    waterskier2007

    Joined:
    Jun 19, 2007
    Location:
    White Lake, MI
    #4
    No problem. I'm relatively new to this stuff myself, so it makes me feel great that I can help other people. It shows I am actually learning stuff. Yay
     

Share This Page