Thursday, 19 December 2013

Sqlite (create table and retrieve data from sqlite database and display in tableview)Reading data from DB. ADD/Update/Delete Operation

Student.h


#import "sqlite3.h"


@property (nonatomic, readwrite) NSInteger  StudentId,
                                            Age;

@property (nonatomic, retain) NSString  *Name,
                                        *Perc;

+ (NSMutableArray *)readRecords;
+ (NSInteger)addRecord:(Student *)sObj;
+ (BOOL)editRecord:(Student *)sObj;
+ (BOOL)deleteRecord:(Student *)sObj;

Student.m


@synthesize StudentId,
            Age,
            Name,
            Perc;


+ (NSMutableArray *)readRecords
{
    NSMutableArray *recordArr = [[NSMutableArray alloc] init];
   
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM student ORDER BY Name ASC"];
           
            sqlite3 *db;
   
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
   
    if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
            {
                        sqlite3_stmt *compiledStatement;
       
        if(sqlite3_prepare_v2(db,[query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
                        {
                                    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
                                    {
                                                Student *currentSObj = [[Student alloc] init];
                
                currentSObj.StudentId = sqlite3_column_int(compiledStatement, 0);
               
                currentSObj.Name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
               
                currentSObj.Age = sqlite3_column_int(compiledStatement, 2);
               
                currentSObj.Perc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
               
                [recordArr addObject:currentSObj];
                                    }
                        }
                        sqlite3_finalize(compiledStatement);
            }
            sqlite3_close(db);
   
    return recordArr;
}

+ (NSInteger)addRecord:(Student *)sObj
{
    NSInteger retVal = false;
   
    NSString *query;
   
    query = [NSString stringWithFormat:
             @"INSERT INTO student (Name, Age, Perc) VALUES ('%@', '%d', '%@')",
             sObj.Name,
             sObj.Age,
             sObj.Perc            
             ];
   
    sqlite3 *db;
   
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
   
    if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
            {
        sqlite3_stmt *compiledStatement;
       
        if(sqlite3_prepare_v2(db,[query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
                        {
            sqlite3_step(compiledStatement);
           
            retVal = true;
                        }
       
                        sqlite3_finalize(compiledStatement);
       
        if(retVal)
            retVal = sqlite3_last_insert_rowid(db);
    }
            sqlite3_close(db);
   
    return retVal;
}

+ (BOOL)editRecord:(Student *)sObj
{
    BOOL retVal = false;
   
    NSString *query;
   
    query = [NSString stringWithFormat:
             @"UPDATE student SET Name = '%@', Age = '%d', Perc = '%@' WHERE StudentId = '%d'",
             sObj.Name,
             sObj.Age,
             sObj.Perc,
             sObj.StudentId
             ];
   
    sqlite3 *db;
   
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
   
    if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
            {
        sqlite3_stmt *compiledStatement;
       
        if(sqlite3_prepare_v2(db,[query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
                        {
            sqlite3_step(compiledStatement);
           
            retVal = true;
                        }
       
                        sqlite3_finalize(compiledStatement);
            }
            sqlite3_close(db);
   
    return retVal;
}

+ (BOOL)deleteRecord:(Student *)sObj
{
    BOOL retVal = false;
   
    NSString *query = [NSString stringWithFormat:@"DELETE FROM student WHERE StudentId = '%d'", sObj.StudentId];
   
    sqlite3 *db;
   
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
   
    if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
    {
        sqlite3_stmt *compiledStatement;
       
        if(sqlite3_prepare_v2(db,[query UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
            sqlite3_step(compiledStatement);
       
        sqlite3_finalize(compiledStatement);
       
        retVal = true;
    }
    sqlite3_close(db);
   
    return retVal;
}

AppDelegate.h


@property (strong, nonatomic) IBOutlet UIWindow *window;

@property (strong, nonatomic) IBOutlet UINavigationController *nav;

AppDelegate.m


@synthesize nav;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self checkDatabase];
   
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)checkDatabase
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDir = [documentPaths objectAtIndex:0];
            NSString *databasePath = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];
            NSString *databaseName = @"test.sqlite";
            NSFileManager *fileManager = [NSFileManager defaultManager];
           
            if(![fileManager fileExistsAtPath:databasePath])
            {
                        NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
                        [fileManager removeItemAtPath:databasePath error:nil];
                        [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    }
            else
            {
                        NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
                        [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    }
}

ViewController.h


#import <UIKit/UIKit.h>

@interface ip22ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *studentRecordsArr;
}

@property (nonatomic, retain) IBOutlet UIBarButtonItem *addBarBtn;

@property (nonatomic, retain) IBOutlet UITableView *recordTblView;

- (IBAction)addRecBtnPressed:(id)sender;

@end

ViewController.m

 

#import "Student.h"
#import "StudentCellViewController.h"

@synthesize addBarBtn,
            recordTblView;

- (IBAction)addRecBtnPressed:(id)sender
{
    Student *tempSObj = [[Student alloc] init];
    tempSObj.Name = @"Alex";
    tempSObj.Age = 16;
    tempSObj.Perc = @"90.80";
   
    if(![Student addRecord:tempSObj])
    {
        [[[UIAlertView alloc] initWithTitle:@"Warning!"
                                    message:@"Details has not been saved.\nPlease verify your data."
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
   
   
    [self initAndLoadTable];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    self.navigationItem.rightBarButtonItem = addBarBtn;
   
    [self initAndLoadTable];
}

- (void)initAndLoadTable
{
    studentRecordsArr = [Student readRecords];

    [recordTblView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table Methods

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return studentRecordsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
   
    Student *sObj = [studentRecordsArr objectAtIndex:indexPath.row];
   
    StudentCellViewController *sVC = [[StudentCellViewController alloc] init];
    sVC.studentObj = sObj;
    [cell.contentView addSubview:sVC.view];
   
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Student *sObj = [studentRecordsArr objectAtIndex:indexPath.row];
   
    if(![Student deleteRecord:sObj])
    {
        [[[UIAlertView alloc] initWithTitle:@"Warning!"
                                    message:@"Something went wrong!"
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
    else
    {
        [studentRecordsArr removeObjectAtIndex:indexPath.row];
       
       
        [recordTblView beginUpdates];
        [recordTblView deleteRowsAtIndexPaths:[[NSArray alloc] initWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationMiddle];
        [recordTblView endUpdates];
    }
}

StudentCellViewController.h


@class Student;

@interface StudentCellViewController : UIViewController

@property (nonatomic, retain) IBOutlet UILabel  *NameLbl,
                                                *AgeLbl,
                                                *PercLbl;

@property (nonatomic, retain) Student *studentObj;

StudentCellViewController.m

 

#import "StudentCellViewController.h"
#import "Student.h"

@implementation StudentCellViewController

@synthesize NameLbl,
            AgeLbl,
            PercLbl;

@synthesize studentObj;

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    NameLbl.text = studentObj.Name;
    AgeLbl.text = [NSString stringWithFormat:@"%dyr", studentObj.Age];
    PercLbl.text = [NSString stringWithFormat:@"%.2f%%", studentObj.Perc.doubleValue];   
}

Read the Records using JSON in iPhone

APILinks.txt


Read:
            http://.../JSON/student.php?action=list

Add:
            http://…/JSON/student.php?action=add&Name=Alex&Age=16&Perc=90

Edit:
            http://.../JSON/student.php?action=edit&Name=Alex&Age=16&Perc=90.86&StudentId=3

Delete:
            http://.../JSON/student.php?action=delete&StudentId=3


student.php (Json File)

<?php
            $DB_Host = "localhost";
            $DB_Name = "test_ios_trainees";
            $DB_Username = "root";
            $DB_Password = "root123";
           
            $WEBSITE_URL = "http://.../JSON/";
           
            $con = mysql_connect($DB_Host, $DB_Username, $DB_Password) or die(mysql_errno());
            $db = mysql_select_db($DB_Name, $con) or die(mysql_error());
           
            $action = ( isset($_REQUEST["action"]) && trim($_REQUEST["action"]) != "" ) ? trim($_REQUEST["action"]) : "";
           
            if($action == "list")
            {
                        $jsonRecArr = array();
                       
                        $sqry = "SELECT * FROM students ORDER BY Name ASC";
                        $sres = mysql_query($sqry) or die("can not select form students - ".mysql_error());
                        while($srow = mysql_fetch_array($sres))
                        {
                                    $recStr = '{"StudentId":"'.trim($srow["StudentId"]).'", "Name":"'.trim($srow["Name"]).'", "Age":"'.trim($srow["Age"]).'", "Perc":"'.trim($srow["Perc"]).'"}';
                                   
                                    array_push($jsonRecArr, $recStr);
                        }
                        mysql_free_result($sres);
           
                        $json = '{"students":['.implode(",", $jsonRecArr).']}';
                       
                        echo $json;
                        exit;
            }
            else if($action == "add")
            {
                        if(        isset($_REQUEST["Name"]) && trim($_REQUEST["Name"]) != "" &&
                                    isset($_REQUEST["Age"]) && trim($_REQUEST["Age"]) != "" &&
                                    isset($_REQUEST["Perc"]) && trim($_REQUEST["Perc"]) != "")
                        {
                                    $iqry = "INSERT INTO students SET
                                                                                                                                    Name = '".trim($_REQUEST["Name"])."',
                                                                                                                                    Age = '".(int)trim($_REQUEST["Age"])."',
                                                                                                                                    Perc = '".(float)trim($_REQUEST["Perc"])."'";
                                                                                                                                                           
                                    mysql_query($iqry) or die("can not insert into students - ".mysql_error());              
                                   
                                    echo "OK";
                                    exit;                                                    
                        }
                        else
                        {
                                    echo "INVALID PARAMETER";
                                    exit;
                        }
            }
            else if($action == "edit")
            {
                        if(        isset($_REQUEST["StudentId"]) && trim($_REQUEST["StudentId"]) != "" &&
                                    isset($_REQUEST["Name"]) && trim($_REQUEST["Name"]) != "" &&
                                    isset($_REQUEST["Age"]) && trim($_REQUEST["Age"]) != "" &&
                                    isset($_REQUEST["Perc"]) && trim($_REQUEST["Perc"]) != "")
                        {
                                    $iqry = "UPDATE students SET
                                                                                                                        Name = '".trim($_REQUEST["Name"])."',
                                                                                                                        Age = '".(int)trim($_REQUEST["Age"])."',
                                                                                                                        Perc = '".(float)trim($_REQUEST["Perc"])."'
                                                                                                            WHERE StudentId = '".trim($_REQUEST["StudentId"])."'";
                                                                                                                                                           
                                    mysql_query($iqry) or die("can not update students - ".mysql_error());                                                                               
                                   
                                    echo "OK";
                                    exit;
                        }
                        else
                        {
                                    echo "INVALID PARAMETER";
                                    exit;
                        }
            }
            else if($action == "delete")
            {
                        if(        isset($_REQUEST["StudentId"]) && trim($_REQUEST["StudentId"]) != "")
                        {
                                    $iqry = "DELETE FROM students WHERE StudentId = '".trim($_REQUEST["StudentId"])."'";                                                                                                                                                         
                                    mysql_query($iqry) or die("can not delete from students - ".mysql_error());            
                                   
                                    echo "OK";
                                    exit;                                                    
                        }                     
                        else
                        {
                                    echo "INVALID PARAMETER";
                                    exit;
                        }
            }
            else
            {
                        echo "Nothing is here for you!";
                        exit;
            }
?>       


Import JSON Whole file for Framework


AppDelegate.h

@property (nonatomic, retain) NSString *apiURL;

AppDelegate.m

@synthesize apiURL;

In didfinisj=h method..
    apiURL = @"http://.../JSON/";

ViewController.h


#import <UIKit/UIKit.h>

@class AppDelegate;

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
    AppDelegate *appDel;
   
    NSMutableArray *recordsArr;
}

@property (nonatomic, retain) IBOutlet UITableView *recordTblView;

@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *processActView;

@end

ViewController.m


#import "ViewController.h"
#import "AppDelegate.h"
#import "Student.h"
#import "MyFunctions.h"
#import "StudentCellViewController.h"

@implementation ViewController

@synthesize recordTblView,
            processActView;

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    appDel = (ip24AppDelegate *)[[UIApplication sharedApplication] delegate];
   
    processActView.hidden = NO;
   
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(recordsRequest) object:nil];
    [queue addOperation:operation];
    [operation release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];   
}

- (void)recordsRequest
{
    NSString *post =[NSString stringWithFormat:@""];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
   
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@student.php?action=list", appDel.apiURL]]];
   
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
   
    NSURLResponse *response;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSString *data= [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
   
    [self performSelectorOnMainThread:@selector(recordResponse:) withObject:data waitUntilDone:NO];
}

- (void)recordResponse:(NSString *)str
{  
    recordsArr = [Student readRecords:str];
   
    [recordTblView reloadData];
   
    processActView.hidden = YES;
}

#pragma mark - Table Methods


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return recordsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
   
    Student *sObj = [recordsArr objectAtIndex:indexPath.row];
   
    StudentCellViewController *studentCellVC = [[StudentCellViewController alloc] init];
    studentCellVC.studentObj = sObj;
   
    [cell.contentView addSubview:studentCellVC.view];
   
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Student *sObj = [recordsArr objectAtIndex:indexPath.row];
   
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(deleteRecordRequest:) object:sObj];
    [queue addOperation:operation];
   
    [recordsArr removeObjectAtIndex:indexPath.row];
   
    [recordTblView beginUpdates];
    [recordTblView deleteRowsAtIndexPaths:[[NSArray alloc] initWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationMiddle];
    [recordTblView endUpdates];
}

- (void)dealloc
{
    [recordTblView release];
    [processActView release];
   
    [super dealloc];
}

@end

MyFunctions.h


#import <Foundation/Foundation.h>

@interface MyFunctions : NSObject

+ (NSString *)trim:(NSString *)stringToTrim;

@end

MyFunctions.m


#import "MyFunctions.h"
@implementation MyFunctions

+ (NSString *)trim:(NSString *)stringToTrim
{
            return [stringToTrim stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

@end

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property (nonatomic, retain) NSString  *StudentId,
                                        *Name,
                                        *Age,
                                        *Perc;

+ (NSMutableArray *)readRecords:(NSString *)dataStr;

@end


Student.m

 

#import "Student.h"
#import "SBJson.h"
#import "NSObject+SBJson.h"
#import "MyFunctions.h"

@implementation Student

@synthesize StudentId,
            Name,
            Age,
            Perc;

+ (NSMutableArray *)readRecords:(NSString *)dataStr
{
    NSMutableArray *recArr = [[NSMutableArray alloc] init];
   
    NSDictionary *json = [dataStr JSONValue];
   
    NSArray *items = [json valueForKey:@"students"];
    NSEnumerator *enumerator = [items objectEnumerator];
    NSDictionary *item;
   
    while((item = (NSDictionary *)[enumerator nextObject]))
    {
        Student *sObj = [[Student alloc] init];       
        sObj.StudentId = [MyFunctions trim:[item objectForKey:@"StudentId"]];
        sObj.Name = [MyFunctions trim:[item objectForKey:@"Name"]];
        sObj.Age = [MyFunctions trim:[item objectForKey:@"Age"]];
        sObj.Perc = [MyFunctions trim:[item objectForKey:@"Perc"]];
       
        [recArr addObject:sObj];
    }
   
    return recArr;
}

@end

StudentCellViewController.h


#import <UIKit/UIKit.h>

@class Student;

@interface StudentCellViewController : UIViewController

@property (nonatomic, retain) IBOutlet UILabel  *NameLbl,
                                                *AgeLbl,
                                                *PercLbl;

@property (nonatomic, retain) Student *studentObj;

@end

StudentCellViewController.m


#import "StudentCellViewController.h"
#import "Student.h"
#import "MyFunctions.h"

@implementation StudentCellViewController

@synthesize NameLbl,
            AgeLbl,
            PercLbl;

@synthesize studentObj;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    NameLbl.text = [MyFunctions trim:studentObj.Name];
    AgeLbl.text = [NSString stringWithFormat:@"%@yr", [MyFunctions trim:studentObj.Age]];
    PercLbl.text = [NSString stringWithFormat:@"%@%%", [MyFunctions trim:studentObj.Perc]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end