Show Contact list on table view of iPhone - ios

I have a view controller where I have an add contact button and a table view. On clicking the add contact button a new view controller opens where there are a few textfields and labels and a button(Submit) which adds the textfield data to the database. I want that as I press the Submit button, the table view in the previous controller should contain the name and contact no. of the contact that was submitted. The addContact method is as follws:
-(IBAction)addContact{
sqlite3_stmt *statement;
const char *dbpath = [mDatabasePath UTF8String];
if (sqlite3_open(dbpath, &mDiary) == SQLITE_OK)
{
NSString *insertSQL1=[NSString stringWithFormat:#"INSERT INTO CONTACTS VALUES(\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")", mName.text, mContactno.text,mCemail.text,mClatitude.text,mClongitude.text];
const char *insert_stmt1 = [insertSQL1 UTF8String];
sqlite3_prepare_v2(mDiary, insert_stmt1,
-1, &statement, NULL);
NSString *tempName = [NSString stringWithFormat:#"%#",mName.text];
NSString *tempNo = [NSString stringWithFormat:#"%#",mContactno.text];
tempName = [tempName stringByAppendingString:tempNo];
[phoneContacts addObject:tempName];
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];
if (sqlite3_step(statement) == SQLITE_DONE)
{ mStatus.text=#"Contact added";
mName.text=#"";
mContactno.text=#"";
mCemail.text=#"";
mClatitude.text=#"";
mClongitude.text=#"";
}
else {
mStatus.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(mDiary);
}
}
The table view methods are:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.phoneContacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [self.phoneContacts objectAtIndex:indexPath.row];
return cell;
}
Nothing is getting shown in the table view. Why?
I've added a method populateContactTable:
-(IBAction)populateContactTable:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [mDatabasePath UTF8String];
if (sqlite3_open(dbpath,&mDiary)== SQLITE_OK) {
NSString *selectSQL = [NSString stringWithFormat:#"SELECT * FROM CONTACTS"];
const char *query_stmt = [selectSQL UTF8String];
if (sqlite3_prepare_v2(mDiary,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
tempContactName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
tempContactNo = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,1)];
tempContactName = [tempContactName stringByAppendingString:#" "];
tempContactName = [tempContactName stringByAppendingString:tempContactNo];
[phoneContacts addObject:tempContactName];
tableView.delegate = self;
tableView.dataSource = self;
[tableView reloadData];
// NSLog(#"%#",userName);
// return tempContactName;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(mDiary);
}
this method is called via a button in the root view controller. Still no data from the database is getting shown on the table.
Here's a snap of the storyboard:

Related

iOS - Searching a SQLite database is slow

Hi I have built a dictionary application my data base has 78.000 record , so when I trying to search through data base the searching process is not smooth and you feel some delay ! specially when try to type first letter when app lunched . here is my codes , I would be grateful if help me to find a solution :
Searching :
- (void)searchWord:(NSString *)txt{
sqlite3_exec(database, "REINDEX table;", NULL, NULL, NULL);
NSMutableArray *DB_Array = [[NSMutableArray alloc] init];
NSString *dbPath = [[NSString alloc] initWithString: [self getDBPath]];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
// #"SELECT * FROM DIC WHERE NAME != '%#%%' ORDER BY NAME LIMIT 30"
// SELECT * FROM DIC Where Name LIKE '%#%%' order by NAME LIMIT 30
NSString *sql =[NSString stringWithFormat:#"SELECT ID,NAME FROM DIC WHERE NAME LIKE '%#%%' ORDER BY NAME LIMIT 15",txt];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sql UTF8String] , -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSInteger oid = sqlite3_column_int(compiledStatement, 0);
const char* f1 = (const char*)sqlite3_column_text(compiledStatement, 1);
NSString *oName = f1 == NULL ? nil : [[NSString alloc] initWithUTF8String:f1];
// NSLog(#"%#",oName);
const char* f2 = (const char*)sqlite3_column_text(compiledStatement, 2);
NSString *oMean = f2 == NULL ? nil : [[NSString alloc] initWithUTF8String:f2];
const char* f3 = (const char*)sqlite3_column_text(compiledStatement, 3);
NSString *oPron = f3 == NULL ? nil : [[NSString alloc] initWithUTF8String:f3];
NSInteger bm = sqlite3_column_int(compiledStatement, 5);
readerClass = [[Reader alloc]initWithReadDB:oid Name:oName Mean:oMean Pron:oPron bookMark:bm];
[DB_Array addObject:readerClass];
}
}
else {
NSLog(#"Error retrieving data from database.");
}
sqlite3_close(database);
}
else {
NSLog(#"Error: Can't open database!");
NSLog(#" DB Name %#",viewController.dbName);
}
AppDelegate *appDelegateClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegateClass.wordList removeAllObjects];
[appDelegateClass.wordList=DB_Array mutableCopy];
[appDelegateClass setCurrentDBPath:[dbPath UTF8String]];
}
TableView :
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
appClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"%d",appClass.wordList.count);
return appClass.wordList.count;
}
- (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];
}
appClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
readerClass = (Reader *)[appClass.wordList objectAtIndex:indexPath.row];
cell.textLabel.text = readerClass.Name;
return cell;
}
SearchBar :
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if([searchText length] > 0) {
dbClass=[[DB alloc]init];
[dbClass searchWord:searchText];
}else
{
dbClass=[[DB alloc]init];
[dbClass searchWord:#" "];
}
[self.myTable reloadData];
}

Passing data from sqlitedatabase to a Detailview

I'm creating an iOS app which is a directory system, where on the first page I load data such as a list of some states in a tableview (from a sqlite database). When clicking on a state only the districts under that particular state have to be displayed in the detailview's tableview. My problem is that when clicking on each district the phonenumber of that district must be shown in the next view controller. Can somebody please help?
This is the firstview.
#implementation firstview
#synthesize ddetails=_ddetails;
#synthesize at,arraydata,show,table;
static firstview *_database;
+ (firstview*)database {
if (_database == nil) {
_database = [[firstview alloc] init];
}
return _database;}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [theauthors count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
menu *me = [self.theauthors objectAtIndex:indexPath.row];
cell.textLabel.text=me.state;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[_button setTitle:cellText forState:UIControlStateNormal];
menu *infos=[theauthors objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"detailViewController"] ;
_ddetails.uniqueId=infos.id;
// NSLog(#"%#",infos.state);
// NSLog(#"%d",infos.id);
[self.navigationController pushViewController:_ddetails animated:NO];
}
-(NSMutableArray *) authorList{
theauthors = [[NSMutableArray alloc]init] ;
show=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
NSString *query =[NSString stringWithFormat:#"SELECT id,category FROM category "];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &selectstmt, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt)==SQLITE_ROW) {
menu * men = [[menu alloc] init];
men.id= sqlite3_column_int(selectstmt,0);
men.state=[NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt,1)];
[theauthors addObject:men];
// NSLog(#"%#",men.category);
// NSLog(#"%d",men.id);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return theauthors;
}
}
- (detailsnews *)Detailsnews:(int)uniqueId{
NSLog(#"%d",uniqueId);
detailsnews *get=nil;
_the=[[NSMutableArray alloc]init];
_gets=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
NSString *sqls =[NSString stringWithFormat:#"SELECT * FROM menulist where category=%d",uniqueId];
// NSLog(#"%d",uniqueId);
sqlite3_stmt *selectstmt6;
if(sqlite3_prepare(db, [sqls UTF8String], -1, &selectstmt6, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt6)==SQLITE_ROW) {
// NSLog(#"%d",uniqueid);
int totalValue = 0;
int uniqueId = sqlite3_column_int(selectstmt6,0);
// NSLog(#"%d",uniqueid);
[_gets addObject:[NSNumber numberWithInt:uniqueId]];
for(NSNumber *number in _gets) // Use fast enumeration to iterate through the array
{
totalValue = [number intValue];
// NSLog(#"%d",totalValue);
}
char *nameChars = (char *) sqlite3_column_text(selectstmt6, 2);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
char *rec = (char *) sqlite3_column_text(selectstmt6, 1);
NSString *rece = [[NSString alloc] initWithUTF8String:rec];
// NSLog(#"%#",rece);
[_the addObject:rece];
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in _the)
{
[result appendString:[obj description]];
result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
}
//[_the addObject:[NSNumber numberWithInt:uniqueid]];
// int totalValue = 0;
// for(NSNumber *number in _the) // Use fast enumeration to iterate through the array
// {
// totalValue = [number intValue];
// NSLog(#"%d",totalValue);
// }
//
// NSMutableString * result = [[NSMutableString alloc] init];
// int totalValue = 0;
//for (NSObject * obj in _the)
// {
// [result appendString:[obj description]];
// result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
// }
//NSArray *arr=[result componentsSeparatedByString:#"\r"];
// NSMutableString * vgh = [[NSMutableString alloc] init];
// for (NSObject * obj in arr)
// {
//[vgh appendString:[obj description]];
// vgh = [arr componentsJoinedByString: #"\r"];
// }
get = [[detailsnews alloc] initWithUniqueId:totalValue district:result phonenumber:name ];
//NSLog(#"%#",_the);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return get;
}
}
detailview controller
- (void)viewDidLoad
{
[super viewDidLoad];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
if (details != nil) {
NSArray *arrComponents = [details.district componentsSeparatedByString:#"\r"];
arr = [[NSMutableArray alloc] init];
for(int i = 0; i < [arrComponents count] ;i++)
{
NSString *str = [arrComponents objectAtIndex:i];
[arr addObject:str];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[button2 setTitle:cellText forState:UIControlStateNormal];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
//NSLog(#"%d",details.uniqueId);
// NSLog(#"%#",details.rece);
// detailsnews *infos=[arr objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.uniqueId=details.uniqueId;
// NSLog(#"%d",details.uniqueId);
[self.navigationController pushViewController:_ddetails animated:NO];
}
You need to Pass the data including the phoneNumbers from first stateViewController to District and then from District to DetailsPage…I would suggest pass an NSdictionary which Includes the data from one view to another such as..In second ViewController declare a global Dictionary as mainDictionary..
and in didSelectRowAtIndexPath just pass the data as
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.mainDict=AllThe Details;
Do the same thing with PhoneNumbers also

How to filter NSDictonary in UISearchBar?

In my app i am using UITableView To display List of items And UISearchBar to Filter the List Of items. All the data, i am reading it from sqlite3.
Following is my code:
below code is used to retrieve the data from Local DB and save the data into NSMutableDictionary called dict and the the dict is added into NSMutableArray
arr_AllTableData.
-(void)dataFromLocalDB
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &PSATestDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Test"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(PSATestDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
companyName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 9)];
[arr_Name addObject:companyName];
address = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 10)];
[arr_Address addObject:address];
number = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
[arr_TelephoneNo addObject:number];
url = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 4)];
[arr_WebAddress addObject:url];
_dict = [[NSMutableDictionary alloc] init];
[_dict setValue:arr_Name forKey:#"Name"];
[_dict setValue:arr_Address forKey:#"Address"];
[_dict setValue:arr_TelephoneNo forKey:#"Number"];
[_dict setValue:arr_WebAddress forKey:#"WebAddress"];
[arr_AllTableData addObject:_dict];
}
sqlite3_finalize(statement);
sqlite3_close(PSATestDB);
}
}
}
Following code is used to display data in UITableView
#pragma mark - UITableView Data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered == YES)
{
return [filtered_Name count];
}
else
{
return [arr_AllTableData count];
}
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"listCell";
PSAListCell *List = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (isFiltered == YES)
{
List.lbl_name.text = [filtered_Name objectAtIndex:indexPath.row];
}
else
{
List.lbl_name.text = [[_dict objectForKey:#"Name"] objectAtIndex:indexPath.row];
List.lbl_address.text = [[_dict objectForKey:#"Address"] objectAtIndex:indexPath.row];
List.lbl_ContactNO.text = [[_dict objectForKey:#"Number"] objectAtIndex:indexPath.row];
List.lbl_WebAddress.text = [[_dict objectForKey:#"WebAddress"] objectAtIndex:indexPath.row];
}
return List;
}
This is my UISearch Bar implemantion code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0)
{
// set our boolean flag
isFiltered = NO;
}
else
{
//set our boolean flag
isFiltered = YES;
// Alloc And init our filter NSMutable array
filtered_Name = [[NSMutableArray alloc]init];
//fast enumeration
NSMutableArray *test = [[NSMutableArray alloc]init];
for (NSDictionary *dictionary in arr_AllTableData)
{
NSArray *array = [dictionary objectForKey:#"Name"];
[test addObjectsFromArray:array];
}
for (NSString * name in test)
{
NSRange nameRang = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (nameRang.location != NSNotFound)
{
[filtered_Name addObject:name];
}
}
}
[_ListTable reloadData];
}
I want to filter the NSDictionary which contains the data and want to display to the filter data on UITableView and if the data is not available in the dictionary then it need to call a web service?
Can anyone please help me out with this?
you can use NSPredicate to filter content from arr_AllTableData based upon your input string.
you can find filter array with predicate in below link.
http://alexeckermann.com/blog/legacy/filtering-nsarray-with-nspredicates

[__NSCFString _isResizable]: unrecognized selector sent to instance 0xa7a52e0

I have image URL strings in database. Then I retrieving the images and add to productimg_array. I need to show the productimg_array images to UITableView cell. I'm using imageView.image=[UIImage imageNamed:[productimg_array objectAtIndex:indexPath.row]];
But app crashing.
const char *sql = "SELECT id,cat_id,product_image,order_by,description FROM product";
NSLog(#"sql is %s",sql);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// We "step" through the results - once for each row.
while (sqlite3_step(statement) == SQLITE_ROW) {
product_image = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
// NSLog(#"product_image is %#",product_image);
[productimg_array addObject:product_image];
}
}
TableView:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"productimg_array is %lu",(unsigned long)[productimg_array count]);
return [productimg_array count];
}
- (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];
}
for(int i=0; i<[productimg_array count];i++){
[cell.imageView setImageWithURL:[NSURL URLWithString:[productimg_array objectAtIndex:i]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
cell.imageView.image = [productimg_array objectAtIndex:indexPath.row];
here cell.imageView.image expect an image in the position but the array has a set of strings that you are passing to set in the imageview
cell.imageView.image =[UIImage imageNamed:[productimg_array objectAtIndex:indexPath.row]];
Note :
product_image = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
can crash if the product_image is empty or null in db,so do this
char *nameChars = (char *) sqlite3_column_text(statement, 2);
if (nameChars) {
product_image = [[NSString alloc] initWithUTF8String:nameChars];
}
First you need to download that images from URL location and then you have to assign it to your image view.For this you can use lazy loading.

How to Join two tables data into UITableView using Sqlite iPhone and how to set NSDictionary object?

How to join my two tables data into another screen in this Am Struck with the NSDictionary,NSArray and NSString how to add object into NSDictionary?
Below is my DBClass.m
#import "DBClass.h"
#implementation DBClass
+(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:#"JoinsDB.sqlite"];
if (![manager fileExistsAtPath:dbPath])
{
[manager copyItemAtPath:[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"JoinsDB.sqlite"] toPath:dbPath error:nil];
}
NSLog(#"%#",dbPath);
return dbPath;
}
+(BOOL)createTable
{
NSString *dbpath=[DBClass connectdb];
sqlite3 *dbObj;
if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
{
sqlite3_stmt *stmt=nil;
const char *sql="create table Company(ID INTEGER,Name VARCHAR,Age INTEGER,Address VARCHAR,Salary INTEGER)";
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=[DBClass connectdb];
const char *sql=[[NSString stringWithFormat:#"insert into Company(ID,Name,Age,Address,Salary) values(\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")",[data objectAtIndex:0],[data objectAtIndex:1],[data objectAtIndex:2],[data objectAtIndex:3],[data objectAtIndex:4]]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_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);
}
+(BOOL)createTable2
{
NSString *dbpath=[DBClass connectdb];
sqlite3 *dbObj;
if (sqlite3_open([dbpath UTF8String], &dbObj)==SQLITE_OK)
{
sqlite3_stmt *stmt=nil;
const char *sql="create table Department(ID INTEGER,Dept VARCHAR,Emp_ID INTEGER)";
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)saveData2:(NSMutableArray *)data
{
sqlite3 *dbObj;
sqlite3_stmt *stmt=nil;
NSString *dbPath=[DBClass connectdb];
const char *sql=[[NSString stringWithFormat:#"insert into Department(ID,Dept,Emp_ID) values(\"%#\",\"%#\",\"%#\")",[data objectAtIndex:0],[data objectAtIndex:1],[data objectAtIndex:2]]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_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 =[DBClass 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 EMP_ID, Age, DEPT FROM COMPANY INNER JOIN DEPARTMENT ON COMPANY.ID = DEPARTMENT.EMP_ID";
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, 2)] forKey:#"Emp_ID"];
[readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:#"Name"];
[readDic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] forKey:#"Dept"];
[readArray addObject:readDic];
NSLog(#"%#",readDic);
}
}
sqlite3_finalize(statement);
}
NSLog(#"%#",readArray);
sqlite3_close(dbobj);
return readArray;
}
#end
How to show in UITableview,and in Viewdidload what should can I do
This my JoinViewController.m
#import "JoinViewController.h"
#import "DBClass.h"
#interface JoinViewController ()
#end
#implementation JoinViewController
#synthesize data,array;
#synthesize Table;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
data=[[NSMutableArray alloc]init];
array=[DBClass getData];
for( NSDictionary *obj in array)
{
NSLog(#"%#",obj);
[data addObject:[obj objectForKey:#"Emp_ID"]];
[data addObject:[obj objectForKey:#"Name"]];
[data addObject:[obj objectForKey:#"Dept"]];
}
NSLog(#"\n%d",[data count]);
[Table reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
//return 1;
return [data count];
}
- (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];
}
cell.textLabel.text = [[data objectAtIndex:indexPath.row]objectForKey:#"Emp_ID"];
cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:#"Name"];
cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:#"Dept"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
#end
In your getdata method, your sql is asking for EMP_ID, Age, DEPT, but you're storing the data as Emp_ID, Name, Dept. One says age, the other says name. Also, you're duplicating the column numbers, getting a value from column 2, which would be DEPT, and you're storing it in Emp_ID, and you're getting the value from column 1 twice, which would be age, and storing it in Name and Dept. Column 0 should be Emp_ID, 1 is Age (which you probably want to change to Name), 2 is DEPT.
You can also simplify your SQL statement a bit with:
SELECT EMP_ID, Age, DEPT FROM COMPANY, DEPARTMENT where COMPANY.ID = DEPARTMENT.EMP_ID;

Resources