0

I have sqlite database and am retrieving data into another tableview how to do? And am struck with the how to add database values into array and how to add these values into tableview? This is my code dbmodelclass.h

        #import <UIKit/UIKit.h>
        #import <sqlite3.h>
        @interface dbModelClass :UIViewController
        {
        NSMutableDictionary *readDic;
        NSMutableArray *readArray;
         // sqlite3 *_database;

        }
        +(NSString *)connectDb;
        +(BOOL)createTable;
        +(BOOL)createTable3;
        +(int)saveData:(NSMutableArray *)data;
        +(int)saveData2:(NSMutableArray *)data;
        +(NSMutableArray *)getData;
        @end
        This is my dbmodelclass.m

        #import "dbModelClass.h"
        #import "Expences.h"
        @implementation dbModelClass;
        -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
        {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
        }

        - (void)didReceiveMemoryWarning
        {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];

        // Release any cached data, images, etc that aren't in use.
        }

        #pragma mark - View lifecycle

        - (void)viewDidLoad
        {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        }
        +(NSString *)connectDb
        {
            NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,         NSUserDomainMask, YES);
        NSString *dbFolder=[docDir objectAtIndex:0];
        NSFileManager *manager=[NSFileManager defaultManager];
        if (![manager fileExistsAtPath:dbFolder])
        {
            [manager createDirectoryAtPath:dbFolder withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *dbPath=[dbFolder stringByAppendingPathComponent:@"fappDB.sqlite"];
        if (![manager fileExistsAtPath:dbPath])
        {
            [manager copyItemAtPath:[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"fappDB.sqlite"] toPath:dbPath  error:nil];
        }
        NSLog(@"%@",dbPath);
        return dbPath;
        }

        +(BOOL)createTable
        {
        NSString *dbpath=[dbModelClass connectDb];
        sqlite3 *dbObj;
        if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
        {
            sqlite3_stmt *stmt=nil;
            const char *sql="create table deposit(deposit_amount VARCHAR,remarks VARCHAR)";
            sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
            if (sqlite3_step(stmt)==SQLITE_DONE)
            {
                NSLog(@"tabel created successfull");
            }
            else
            {
                NSLog(@"tabel already created");
            }
            sqlite3_finalize(stmt);
            sqlite3_close(dbObj);
        }   
                return YES;
        } 
        +(BOOL)createTable3;
        {
        NSString *dbpath=[dbModelClass connectDb];
        sqlite3 *dbObj;
        if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
        {
            sqlite3_stmt *stmt=nil;
            const char *sql="create table expense2(expense_title VARCHAR,description VARCHAR,amount VARCHAR,paidcash VARCHAR,date VARCHAR,remarks VARCHAR)";
            sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
            if (sqlite3_step(stmt)==SQLITE_DONE)
            {
                NSLog(@"tabel created successfull");
            }
            else
            {
                NSLog(@"tabel already created");
            }
            sqlite3_finalize(stmt);
            sqlite3_close(dbObj);
        }
        return YES;
        }

        +(int)saveData:(NSMutableArray *)data
        {
        sqlite3 *dbObj;
        sqlite3_stmt *stmt=nil;
        NSString *dbPath=[dbModelClass connectDb];
        const char *sql=[[NSString stringWithFormat:@"insert into deposit(deposit_amount,remarks) values(\"%@\",\"%@\")",[data objectAtIndex:0],[data objectAtIndex:1]]UTF8String];

        if (sqlite3_open([dbPath UTF8String], &dbObj)==SQLITE_OK)
        {
            sqlite3_bind_text(stmt, 1, [[data objectAtIndex:0]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 2, [[data objectAtIndex:1]UTF8String], -1, SQLITE_TRANSIENT);


            sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
            if (sqlite3_step(stmt)==SQLITE_DONE)
            {
              NSLog(@"data insertion stmnt executed properly");
               }
               else
                  NSLog(@"data insertion stmnt not executed");

                  sqlite3_finalize(stmt);
                   sqlite3_close(dbObj);

        }
        return sqlite3_last_insert_rowid(dbObj);
        } 

        +(int)saveData2:(NSMutableArray *)data
        {
        sqlite3 *dbObj;
        sqlite3_stmt *stmt=nil;
         NSString *dbPath=[dbModelClass connectDb];
        const char *sql=[[NSString stringWithFormat:@"insert into expense2(expense_title,description,amount,paidcash,date,remarks) values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",[data objectAtIndex:0],[data objectAtIndex:1],[data objectAtIndex:2],[data objectAtIndex:3],[data objectAtIndex:4],[data objectAtIndex:5]]UTF8String];

        if (sqlite3_open([dbPath UTF8String], &dbObj)==SQLITE_OK)
        {
            sqlite3_bind_text(stmt, 1, [[data objectAtIndex:0]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 2, [[data objectAtIndex:1]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 3, [[data objectAtIndex:2]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 4, [[data objectAtIndex:3]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 5, [[data objectAtIndex:4]UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stmt, 6, [[data objectAtIndex:5]UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_prepare_v2(dbObj, sql, -1, &stmt, nil);
            if (sqlite3_step(stmt)==SQLITE_DONE)
            {
                NSLog(@"data insertion stmnt executed properly");
            }
            else
                NSLog(@"data insertion stmnt not executed");

            sqlite3_finalize(stmt);
            sqlite3_close(dbObj);

        }
        return sqlite3_last_insert_rowid(dbObj);
        }

        +(NSMutableArray *)getData
        {
        sqlite3 *dbobj;
        NSString *dbpath  =[dbModelClass connectDb];
        NSMutableArray *readArray=[[NSMutableArray alloc]init];
        if(sqlite3_open([dbpath UTF8String], &dbobj)==SQLITE_OK)
        {
            sqlite3_stmt *statement=nil;

            //**** NSString *string=@"SELECT name FROM emptable";
            NSString *string=@"SELECT * FROM deposit";
            const char *query=[string UTF8String];
            if(sqlite3_prepare_v2(dbobj, query, -1, &statement, NULL)==SQLITE_OK)
            {
                while (sqlite3_step(statement)==SQLITE_ROW)
                {
                    NSMutableDictionary *readDic=[[NSMutableDictionary alloc] init];

                    [readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] forKey:@"deposit_amount"];
                    // NSString *aName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
                    // NSString *pwd=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
                    //   [readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:@"password"];
                    //  [readArray addObject:aName];
                    // [readArray1 addObject:pwd];
                    [readArray addObject:readDic];
                    // NSLog(@"%@",readDic);
                }
            }
            sqlite3_finalize(statement);
        }
        NSLog(@"%@",readArray);
        sqlite3_close(dbobj);
        return readArray;
        }
        - (void)viewDidUnload
        {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
        }

           - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        {
        // Return YES for supported orientations
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
        }

        @end
        This is my netviewcontroller.h
        #import <UIKit/UIKit.h>

        @interface NetViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

        {
        IBOutlet  UILabel *depositLabel,*expenseLabel,*netvalueLabel;
        IBOutlet  UITextField *netvalueText;
        IBOutlet UITableView *depositTable;

        }
        @property (strong, nonatomic) UINavigationController *navigationController;
        @property(strong,nonatomic)UILabel  *depositLabel,*expenseLabel,*netvalueLabel;
        @property(strong,nonatomic)UITextField *netvalueText;
        @property(strong,nonatomic)UITableView *depositTable;

        -(IBAction)netvalue:(id)sender;

        @end
        This is my netviewcontroller.m

        #import "NetViewController.h"
        #import "dbModelClass.h"
        @interface NetViewController ()

        @end

        @implementation NetViewController
        {
        NSArray *tableData;
        }
        @synthesize depositLabel,netvalueLabel,depositTable,netvalueText;
        //@synthesize str,depositData,depositArray;


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

        - (void)viewDidLoad
        {

        [super viewDidLoad];
        [dbModelClass connectDb];
        [dbModelClass getData];
       /* depositArray=[[NSMutableArray alloc]init];
        depositData=[[NSMutableArray alloc]init];
        depositArray=[dbModelClass getData:str];

        for( NSDictionary *dis in depositArray)
        {
            [depositData addObject:[dis objectForKey:@"depositTable"]];
        }*/

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

        }
        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
        {
        return [tableData count];
        }

          - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
        static NSString *simpleTableIdentifier = @"SimpleTableItem";

            UITableViewCell *cell = [tableView     dequeueReusableCellWithIdentifier:simpleTableIdentifier];

            if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
        }

        cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
        return cell;
        }
        @end
impratikz
  • 3
  • 2
user2420691
  • 15
  • 1
  • 3
  • 1
    Is there a question? What specifically isn't working? Are you getting a SQLITE_OK result? What is sqlite3_column_text returning? Have you examined the DB from the sqlite3 tool in the Mac command line window to see if the DB is set up properly and is getting updated? – Hot Licks Jun 05 '13 at 10:40
  • If you are hoping that somebody will go over every line of code you've posted, don't. Nobody is getting paid to serve you. You'd make it concise. – El Tomato Jun 05 '13 at 10:53
  • what is your issue..? please describe it. well your code is working fine or not are you getting value in Array or not..? have you face any Error..? if yes then which error you getting..? please ask question with issue not with only code. – Nitin Gohel Jun 05 '13 at 11:10
  • How to add the sqlite database data into an array And how to add this value into tableview? – user2420691 Jun 05 '13 at 11:41
  • Not a real question. If you don't know how to read the spec for NSMutableArray and figure out how to add an entry, you should not be programming! – Hot Licks Jun 05 '13 at 19:37

2 Answers2

3

First of all, Read about NSArray in this tutorial.

then read about NSDictionary in this tutorial.

then you can learn how to save data in sqlite and display in tableview.

I am posting my sample code try to follow like this will help you

-(void)checkAndCreateDB
{
    dataBasePath=[[NSString alloc] initWithString: [NSString stringWithFormat: @"%@/QRCodeDB.sqlite",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]]];
    BOOL success;
    NSFileManager *filemanager=[NSFileManager defaultManager];
    success=[filemanager fileExistsAtPath:dataBasePath];
    if(success){
        return;
    }
    NSString *databasePathFromApp=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"QRCodeDB.sqlite"];
    [filemanager copyItemAtPath:databasePathFromApp toPath:dataBasePath error:nil];
}
-(void)addNewItemWhereText:(NSString *)text imageData:(NSData *)data dateIs:(NSString *)date
{
    [self checkAndCreateDB];
    sqlite3_stmt *compiledStmt;
    sqlite3 *db;
    if(sqlite3_open([dataBasePath UTF8String], &db)==SQLITE_OK){
        NSString *insertSQL=@"insert into History(image,text,date) VALUES(?,?,?)";

        if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK)
        {
            sqlite3_bind_blob(compiledStmt, 1, [data bytes], [data length], SQLITE_TRANSIENT);
            sqlite3_bind_text(compiledStmt, 2, [text UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(compiledStmt, 3, [date UTF8String], -1, SQLITE_TRANSIENT);
            if(sqlite3_step(compiledStmt) != SQLITE_DONE ) {
                NSLog( @"Error: %s", sqlite3_errmsg(db) );
            } else {
                NSLog( @"Insert into row id = %lld", (sqlite3_last_insert_rowid(db)));
            }

            sqlite3_finalize(compiledStmt);
        }
    }
    sqlite3_close(db);
}
-(UIImage *)giveMeImageWhereDateIs:(NSString *)date
{
    [self checkAndCreateDB];
    UIImage *imageIs;
    sqlite3_stmt *compiledStmt;
    sqlite3 *db;
    if(sqlite3_open([dataBasePath UTF8String], &db)==SQLITE_OK){
        NSString *insertSQL = [NSString stringWithFormat:@"Select image from History Where date = '%@'",date];
        if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStmt) == SQLITE_ROW) {

                int length = sqlite3_column_bytes(compiledStmt, 0);
                NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length];
                imageIs=[UIImage imageWithData:imageData];
                NSLog(@"Length : %d", [imageData length]);

            }
        }
        sqlite3_finalize(compiledStmt);
    }
    sqlite3_close(db);
    return imageIs;
}
-(NSArray *)giveMeAllDataInTable
{
    NSMutableArray *tableDataArray=[[NSMutableArray alloc]init];
    [self checkAndCreateDB];
    sqlite3_stmt *compiledStmt;
    sqlite3 *db;
    if(sqlite3_open([dataBasePath UTF8String], &db)==SQLITE_OK){
        NSString *insertSQL = [NSString stringWithFormat:@"Select * from History"];
        if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStmt) == SQLITE_ROW)
            {
                NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
//                int length = sqlite3_column_bytes(compiledStmt, 0);
//                NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length];
                [dict setObject:[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStmt, 1)] forKey:@"text"];
                [dict setObject:[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStmt, 2)] forKey:@"date"];
                [tableDataArray addObject:dict];
            }
        }
        sqlite3_finalize(compiledStmt);
    }
    sqlite3_close(db);
    return tableDataArray;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
NSLog
  • 649
  • 1
  • 5
  • 12
0

First of all , I cant see where you have initialised dbModelClass object

Secondly , Your method getData will return the array containing data from your sqlite. Which you are not saving anywhere .

 - (void)viewDidLoad
    {

    [super viewDidLoad];

    [dbModelClass connectDb];      

EDIT : tableData is the NSArray you are using in Class NetViewController

Replace this line

 [dbModelClass getData];        

With this

tableData = [dbModelClass getData];       
 NSLog(@"Content for tableData - %@ ",tableData);

Suggestion : Use First letter caps for Class name

Dushyant Singh
  • 721
  • 4
  • 13
  • How to add the sqlite database data into an array And how to add this value into tableview? – user2420691 Jun 05 '13 at 11:50
  • I am very beginner to IOS Please help me.How to get data into an array and how to add this data into tableview? depositArray=[[NSMutableArray alloc]init]; depositData=[[NSMutableArray alloc]init]; depositArray=[dbModelClass getData:str]; for( NSDictionary *dis in depositArray) { [depositData addObject:[dis objectForKey:@"depositTable"]]; } – user2420691 Jun 05 '13 at 11:54
  • Yes I did above menctioned but it getting error "No known class method for selector'getData'" – user2420691 Jun 05 '13 at 14:01