how to display data from sqlite in UITableView in Storyboard

I create one application. in my application I store 2 array in sqlite table DataBase but I can't display from sqlite in UItableView. I searching in google but not found about display data in storyboard from sqlite.!!! please guide me that how to display data from sqlite DB in tableview. this is my code :

#import "ViewController.h"
#define DataName @"DB.sqlite"

@implementation ViewController
{
    NSDictionary * dictionary;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *Name = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *Team = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        NSString * name = [Name objectAtIndex:i];
        NSString * team = [Team objectAtIndex:i];
        dictionary = [NSDictionary dictionaryWithObjectsAndKeys:name,@"Name",team,@"Team",nil];
        NSString *query = [NSString stringWithFormat:@"insert into tableFootball (Name,Team) values('%@','%@')",[dictionary objectForKey:@"Name"],[dictionary objectForKey:@"Team"]];
        [self executeQuery:query];
    }

}
-(NSString *) dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DataName]);
    return [documentsDirectory stringByAppendingPathComponent:DataName];
}
-(void)executeQuery:(NSString *)query
{
    //NSLog(@"QUERY : %@",query);

    sqlite3_stmt *statement;
    if(sqlite3_open([[self dataFilePath] UTF8String], &DataBase) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(DataBase, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) != SQLITE_DONE)
            {
                sqlite3_finalize(statement);
            }
        }
        else
        {
            NSLog(@"query Statement Not Compiled");
        }

        sqlite3_finalize(statement);
        sqlite3_close(DataBase);
    }
    else
    {
        NSLog(@"Data not Opened");
    }
}
#pragma mark - Table view data source
- (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.
    return 1;
}
- (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];
    }
    //I dont know what put here for display from sqlite
    return cell;
}

Answers


Create a method which will fetch all players stored in sqlite say findAllPlayers . Create a dataSourceArray which will hold the players returned from the previous method. It would be easy to form model custom objects instead of dictionary for ease of use.

//Player.h

@interface Player : NSObject

@property (nonatomic) NSUInteger playerID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *team;

A utility PlayerDatabase which inserts and fetches player instances from sqlite.

//PlayerDatabase.h

@class Player;
@interface PlayersDatabase : NSObject

+ (PlayersDatabase*)database;
- (NSArray *)findAllPlayers;
- (BOOL)insertPlayer:(Player *)player;

//PlayerDatabase.m
@implementation PlayersDatabase

static PlayersDatabase *_database;

+ (PlayersDatabase*)database {
    if (_database == nil) {
        _database = [[PlayersDatabase alloc] init];
    }
    return _database;
}

- (id)init {
    if ((self = [super init])) {

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [self databasePath];
        if (![fileManager fileExistsAtPath:filePath]) {
            NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"Players"
                                                                 ofType:@"db"];
            [fileManager copyItemAtPath:sqLiteDb
                                 toPath:filePath
                                  error:NULL];
        }

    }
    return self;
}

- (NSString *)databasePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    return [documentsDirectory stringByAppendingPathComponent:@"Players.db"];
}

- (NSArray *)findAllPlayers
{
    NSMutableArray *players = [NSMutableArray array];
    FMDatabase *database = [FMDatabase databaseWithPath:[self databasePath]];
    [database open];

    FMResultSet *resultSet = [database executeQuery:@"SELECT * from Player ORDER BY Name"];

    while ([resultSet next]) {

        Player *player = [[Player alloc]init];

        player.playerID = [resultSet intForColumn:@"PlayerID"];
        player.name     = [resultSet stringForColumn:@"Name"];
        player.team     = [resultSet stringForColumn:@"Team"];

        [players addObject:player];

    }

    [database close];

    return players;
}

- (BOOL)insertPlayer:(Player *)player
{
     FMDatabase *db = [FMDatabase databaseWithPath:[self databasePath]];
     [db open];
     BOOL success =  [db executeUpdate:@"INSERT INTO Player (Name,Team) VALUES (?,?);",player.name,player.team, nil];
     [db close];
     return success;
}

Now in the viewController with tableView, first populate the sqlite and then reload the tableView

//YourViewController.h 
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *names = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *teams = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        Player *player = [[Player alloc]init];

        player.name = names[i];
        player.team = teams[i];

        [[PlayerDatabase database] insertPlayer:player];
    }

    self.players = [self findAllPlayers];
    [self.tableView reloadData];

}

#pragma mark - Table view data source
- (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.
    return [self.players 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];
    }
    //Here the dataSource array is of dictionary objects
    Player *player = self.players[indexPath.row];
    cell.textLabel.text = player.name;
    cell.detailTextLabel.text = player.team;

    return cell;
}

I have worked out a sample project following the above mentioned tutorial, the data was preloaded into the sqlite. So you might need to tweak it for your use.

Source Code


Need Your Help

Angular JS dynamically create ng-grid within accordion

javascript angularjs accordion ng-grid

I'm having a problem creating accordion elements dynamically with a ng-grid inside. I can create the grids dynamically but the dataset is the same across all the grid. I'd like each

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.