Im working on a iOS app, so i need to save a image that the user will choose from his album or will take it from the camera. Im doing this with a picker
Then i try to save the image into the table with this code:
- (IBAction)saveUOme:(id)sender
{
NSString * _name = name.text;
NSString * _lastname = lastname.text;
NSString * _email = email.text;
NSString * _workemail = workEmail.text;
NSString * _cellphone = cell.text;
NSString * _phone = homePhone.text;
NSString * _money = amount.text;
NSString * _stuff = stuff.text;
NSString * _cause = cause.text;
//NSData *_image = UIImagePNGRepresentation(image);
NSData *_image = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:#"yyyy-MM-dd"];
NSString * _date = [dateformatter stringFromDate:[datePicker date]];
if (!switchR.on)
{
_date=#"";
}
//NSString *_error;
NSLog(#" %# ,%# ,%# ,%# ,%# ,%#,%#,%#,%#,%# ", _name,_lastname,_email,_workemail,_cellphone,_phone,_money,_stuff,_cause,_date);
if(([_name length]!=0 && [_lastname length] !=0 && [_money length] !=0) || ([_name length]!=0 && [_lastname length] !=0 && [_stuff length] !=0 ) )
{
NSString *query = [NSString stringWithFormat:#"INSERT INTO addUOmeTable ('name','lastname','email','workemail','cellphone','phone','money','stuff','cause','date','image') VALUES ('%#','%#','%#','%#','%#','%#','%#','%#','%#','%#','%#');", _name, _lastname, _email, _workemail, _cellphone, _phone,_money,_stuff,_cause,_date,_image];
char *err;
if (sqlite3_exec(_db, [query UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(_db);
NSAssert(0,#"No se pudo agregar");
}else
{
NSLog(#"Se agregaron los datos");
}
}else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Some Data is Missing"
message:#"Name, Lastname or Amount/Stuff"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
/*
FirstViewController *obj =[[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
[self.view addSubview:obj.view];*/
//[self.navigationController pushViewController:obj animated:YES];
}
}
So far i think this works because in the database i get this as save object
<89504e47 0d0a1a0a 0000000d 49484452 00000400 00000300 08020000 0035d882 5a000000 1c69444f 54000000 02000000 00000001 80000000 28000001 80000001 80000c6c fd9ea091 34000040 00494441 5478019c 7df7775c 45b6357f ce7b3360 a5ce4959 b2255956 ce9d734e ea56ce96 73c0186c c0806d8c 73ced9c6 e4641be7 086f6698 21e300cc fbf9dbb7 4feb50be 2d9b79df 5a67d5da 75ead4a9 bab7c33d fb567a2e 38520e09 0f574222 4395e1c1 8ae84065 46aac37d 95c1de4a 7fa2dc93 2873c74b 9db1325b acbc275c da1d2eef 8c967644 4ada22a6 d6b0be29 ac6b8ea8 5b23eaf6 88aa3ba6 b624d4ce 84d693d2 85fb0df1 2153efa0 2135a84b 0de953a.....>
Then i try to select all from the database with this code
-(void) selectData
{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM addUOmeTable ORDER BY name ASC"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_db, [query UTF8String], -1, &statement, Nil)== SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW)
{
char *id1 = (char *) sqlite3_column_text(statement, 0);
NSString *id_uomeDoubt = [[NSString alloc] initWithUTF8String:id1];
char *name1 = (char *) sqlite3_column_text(statement, 1);
NSString *name = [[NSString alloc] initWithUTF8String:name1];
char *lastname1 = (char *) sqlite3_column_text(statement, 2);
NSString *lastname = [[NSString alloc] initWithUTF8String:lastname1];
char *email1 = (char *) sqlite3_column_text(statement, 3);
NSString *email = [[NSString alloc] initWithUTF8String:email1];
char *workemail1 = (char *) sqlite3_column_text(statement, 4);
NSString *workemail = [[NSString alloc] initWithUTF8String:workemail1];
char *cellphone1 = (char *) sqlite3_column_text(statement, 5);
NSString *cellphone = [[NSString alloc] initWithUTF8String:cellphone1];
char *phone1 = (char *) sqlite3_column_text(statement, 6);
NSString *phone = [[NSString alloc] initWithUTF8String:phone1];
char *money1 = (char *) sqlite3_column_text(statement, 7);
NSString *money = [[NSString alloc] initWithUTF8String:money1];
char *staff1 = (char *) sqlite3_column_text(statement, 8);
NSString *staff = [[NSString alloc] initWithUTF8String:staff1];
char *couse1 = (char *) sqlite3_column_text(statement, 9);
NSString *couse = [[NSString alloc] initWithUTF8String:couse1];
char *date1 = (char *) sqlite3_column_text(statement, 10);
NSString *date = [[NSString alloc] initWithUTF8String:date1];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 11) length:sqlite3_column_bytes(statement, 11)];
doubtArr = [NSArray arrayWithObjects:id_uomeDoubt,name,lastname,email,workemail,cellphone,phone,money,staff,couse,date,data, nil];
[uomeDoubts addObject:doubtArr];
}
}
[self.myTable reloadData];
}
And finally i try to display the image into a cell using this code
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
CustomeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell)
{
cell= [[CustomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
NSArray *debtor = [uomeDoubts objectAtIndex:indexPath.row];
NSString *nombre = [debtor objectAtIndex:1];
NSString *nombre2 = [debtor objectAtIndex:1];
NSString *apellido = [debtor objectAtIndex:2];
nombre = [nombre stringByAppendingString:#" "];
nombre = [nombre stringByAppendingString:[debtor objectAtIndex:2]];
cell.TitleLable.text = nombre;
NSString *tempo = [debtor objectAtIndex:7] ;
if ([tempo length] ==0)
{
NSString *st = #"Stuff - ";
st = [st stringByAppendingString:[debtor objectAtIndex:8]];
cell.SubtitleLable.text = st;
}
else
{
NSString *mny = #"Money - $";
mny = [mny stringByAppendingString:[debtor objectAtIndex:7]];
cell.SubtitleLable.text = mny;
}
NSLog(#"%# %#",nombre2,apellido);
NSData* data = [debtor objectAtIndex:11];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
And i dont get any error , the only thing is that the image is not display at all
PLEASE HELP!
Related
//find all data from database
- (void) findAllSupplement
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM SupplementInformationTable"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSMutableArray *allRows = [[NSMutableArray alloc] init] ;
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement,0);
NSString *field1Str1 = [[NSString alloc] initWithUTF8String: field1];
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field1Str2 = [[NSString alloc] initWithUTF8String: field2];
char *field3 = (char *) sqlite3_column_text(statement,2);
NSString *field1Str3 = [[NSString alloc] initWithUTF8String: field3];
char *field4 = (char *) sqlite3_column_text(statement,3);
NSString *field1Str4= [[NSString alloc] initWithUTF8String: field4];
char *field5 = (char *) sqlite3_column_text(statement,4);
NSString *field1Str5 = [[NSString alloc] initWithUTF8String: field5];
char *field6 = (char *) sqlite3_column_text(statement,5);
NSString *field1Str6 = [[NSString alloc] initWithUTF8String: field6];
char *field7 = (char *) sqlite3_column_text(statement,6);
NSString *field1Str7= [[NSString alloc] initWithUTF8String: field7];
char *field8 = (char *) sqlite3_column_text(statement,7);
NSString *field1Str8 = [[NSString alloc] initWithUTF8String: field8];
char *field9 = (char *) sqlite3_column_text(statement,8);
NSString *field1Str9 = [[NSString alloc] initWithUTF8String: field9];
NSMutableDictionary *dataDictionary=[[NSMutableDictionary alloc]init];
[dataDictionary setObject:field1Str1 forKey:#"supplementIdentity"];
[dataDictionary setObject:field1Str2 forKey:#"supplementName"];
[dataDictionary setObject:field1Str3 forKey:#"supplementDescription"];
[dataDictionary setObject:field1Str4 forKey:#"offerIdentity"];
[dataDictionary setObject:field1Str5 forKey:#"offerName"];
[dataDictionary setObject:field1Str6 forKey:#"offerDescription"];
[dataDictionary setObject:field1Str7 forKey:#"flavourIdentity"];
[dataDictionary setObject:field1Str8 forKey:#"imageLink"];
[dataDictionary setObject:field1Str9 forKey:#"quantityPurchase"];
// Add the string in the array.
[allRows addObject:dataDictionary];
NSLog(#"Match found") ;
//send all data to the cart container screen
CartContainer *objCartContainer=[[CartContainer alloc]init];
objCartContainer.arrayConatinLocalDataFromDB=allRows;
}
sqlite3_finalize(statement);
NSLog(#"%#",allRows);
}
sqlite3_close(_contactDB);
}
}
how i can call this function in app delegate ?this function is declared and define in view controller named productDetail.m .And i want to execute this function for my entire app. help will be appreciated.
Write the function in Appdelegate.m
And call from viewController.m
form this code:
AppDelegate *appDelegate;
appDelegate= (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate findAllSupplement];
Or you can declare the funtion globally. like:
In ViewController.h
+ (void) findAllSupplement;
And Define the funtion in ViewControler.m
+ (void) findAllSupplement
{
// your code here
}
And you can call the funtion from any class.
- (NSMutableArray*)getAllDataFromTableUSERINFO:(NSString *)fetchQuery {
NSMutableArray *resultArray1 =[[NSMutableArray alloc]init];
#autoreleasepool {
if (sqlite3_open([[self getDBPath]UTF8String],&database)==SQLITE_OK){
sqlite3_stmt *stmt;
const char *sqlfetch=[fetchQuery UTF8String];
if (sqlite3_prepare(database, sqlfetch, -1,&stmt, NULL)==SQLITE_OK) {
while (sqlite3_step(stmt)==SQLITE_ROW){
RM_USER_INFO *UserInfo = [[RM_USER_INFO alloc]init];
UserInfo.uid=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,0)];
UserInfo.username=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,1)];
UserInfo.password=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,2)];
UserInfo.fname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,3)];
UserInfo.mname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,4)];
[resultArray1 addObject:UserInfo];
}
}
sqlite3_finalize(stmt);
stmt=nil;
sqlite3_close(database);
sqlite3_release_memory(120);
}
}
return resultArray1;
}
Get always EXE_BAD_ACCESS after fews operations
Try this function:
static NSInteger DBBUSY;
+(NSMutableArray *)executeQuery:(NSString*)str{
sqlite3_stmt *statement= nil;
sqlite3 *database;
NSString *strPath = Your Database path here;
while(DBBUSY);
DBBUSY = 1;
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSInteger i = 0;
NSInteger iColumnCount = sqlite3_column_count(statement);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
while (i< iColumnCount) {
NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, i)];
NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, i)];
if(!str)
str = #"";
[dict setObject:str forKey:strFieldName];
i++;
}
[allDataArray addObject:dict];
}
}
DBBUSY = 0;
sqlite3_finalize(statement);
}
sqlite3_close(database);
return allDataArray;
}
This may help you :)
I've got a chat app that is based on a navigation controller.
Within the view that displays the conversation i load all the previous history from SQLite within the viewDidLoad method.
When a conversation grows it takes a few seconds to open up the view and therefore feels "laggy".
Below is my code that i use to load the history from the database.
Any ideas what could be improved to make the UI feel more responsive?
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM chatHistory WHERE channelID = '%#' ORDER BY time ASC", box.activeChannel];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2([box db], [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *channelID = [[NSString alloc] initWithUTF8String:field1];
char *field2 = (char *) sqlite3_column_text(statement, 1);
NSString *sender = [[NSString alloc] initWithUTF8String:field2];
char *field3 = (char *) sqlite3_column_text(statement, 2);
NSString *message = [[NSString alloc] initWithUTF8String:field3];
char *field4 = (char *) sqlite3_column_text(statement, 3);
NSString *recipient = [[NSString alloc] initWithUTF8String:field4];
char *field5 = (char *) sqlite3_column_text(statement, 4);
NSString *time = [[NSString alloc] initWithUTF8String:field5];
NSString *str = [[NSString alloc] initWithFormat:#"%#", message];
NSString *str1 = [[NSString alloc] initWithFormat:#"%#", channelID];
NSString *str2 = [[NSString alloc] initWithFormat:#"%#", sender];
NSString *str3 = [[NSString alloc] initWithFormat:#"%#", time];
NSString *trimmedStr2 = [str2 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSString *trimmedAgentName = [box.agentName stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSString *trimmedTime = [str3 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *myDate = [df dateFromString:trimmedTime];
if ([trimmedStr2 isEqualToString:trimmedAgentName]) {
[self.messages addObject:[[JSMessage alloc] initWithText:str sender:trimmedAgentName date:myDate]];
[self finishSend];
[self scrollToBottomAnimated:YES];
} else {
[self.messages addObject:[[JSMessage alloc] initWithText:str sender:kSubtitleVisitor date:myDate]];
[self finishSend];
[self scrollToBottomAnimated:YES];
}
}
}
Edit
I've also tried to put the code inside a dispatch_queue, that made the switch to the view go a lot faster but the messages are still lagging behind when being added.
There are some places you can optimise in your code:
No need to create str str1 str2 str3, just use the message channelID sender time.
NSDateFormatter creation is expansive, you should create a instance outside the while loop.
viewDidLoad is called in UI thread, the query will take a long time to execute and block UI, you might want to execute SQL query in background. See Apple's Concurrency Programming Guide for more.
I might be doing this all wrong as I am still new to Objective C.
I am trying to retrieve data from an sqlite3 database and store it in a NSObject array.
Here is the viewDidLoad method in my implementation file.
- (void)viewDidLoad
{
[super viewDidLoad];
clients = [[NSMutableArray alloc] init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM clients"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [sql 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];
char *field3 = (char *) sqlite3_column_text(statement, 2);
NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];
char *field4 = (char *) sqlite3_column_text(statement, 3);
NSString *field4Str = [[NSString alloc]initWithUTF8String:field4];
char *field5 = (char *) sqlite3_column_text(statement, 4);
NSString *field5Str = [[NSString alloc]initWithUTF8String:field5];
char *field6 = (char *) sqlite3_column_text(statement, 5);
NSString *field6Str = [[NSString alloc]initWithUTF8String:field6];
char *field7 = (char *) sqlite3_column_text(statement, 6);
NSString *field7Str = [[NSString alloc]initWithUTF8String:field7];
char *field8 = (char *) sqlite3_column_text(statement, 7);
NSString *field8Str = [[NSString alloc]initWithUTF8String:field8];
char *field9 = (char *) sqlite3_column_text(statement, 8);
NSString *field9Str = [[NSString alloc]initWithUTF8String:field9];
ClientObj *c1 = [[ClientObj alloc] initWithCompanyName:field1Str firstName:field2Str lastName:field3Str email:field4Str workPhone:field5Str mobilePhone:field6Str streetAddress:field7Str city:field8Str postalCode:field9Str];
}
}
self.clients = [NSArray arrayWithObjects:c1,c2,c3,c4, nil];
}
I am trying to increment *c1 each time the while statement loops through the database. eg. c1, c2 ,c3, c4
I am then trying to add each ClientObj created from the database loop above to the clients array but I am not sure how to do this.
Any help or advice is very much appreciated
Initialize the array once before the loop:
self.clients = [[NSMutableArray alloc] init];
and then just add each client object to the array inside the loop:
while (sqlite3_step(statement) == SQLITE_ROW) {
// ...
ClientObj *c = [[ClientObj alloc] initWithCompanyName:field1Str firstName:field2Str lastName:field3Str email:field4Str workPhone:field5Str mobilePhone:field6Str streetAddress:field7Str city:field8Str postalCode:field9Str];
[self.clients addObject:c];
}
I'm working on an app that displays various feeds using ASIHTTPRequest. The user can add new sources to the app that are stored in an SQLite database. Currently I give the feeds to the app in the viewDidLoad method of my FeedsViewController but i want to be able to retrieve the data that contains the link for the source and store it in an array to use it.
Currently the app looks like and below the current code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.title =#"Lajmet";
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//self.tabBarController.tabBar.tintColor = [UIColor blackColor];
self.allEntries = [NSMutableArray array];
self.queue = [[NSOperationQueue alloc] init];
self.feeds = [NSMutableArray arrayWithObjects:#"http://pcworld.al/feed",#"http://geek.com/feed", #"http://feeds.feedburner.com/Mobilecrunch",#"http://zeri.info/rss/rss-5.xml",
nil];
[self.tableView reloadData];
[self refresh];
}
My view that contains the function (AddSourcesViewController) to add and delete new sources looks like this and here the code:
- (void)viewDidLoad
{
[super viewDidLoad];
arrayOfSource = [[NSMutableArray alloc]init];
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
[self createOrOpenDB];
// Display sources in table view
sqlite3_stmt *statement;
if (sqlite3_open([dbPathString UTF8String], &sourceDB)==SQLITE_OK) {
[arrayOfSource removeAllObjects];
NSString *querySql = [NSString stringWithFormat:#"SELECT * FROM SOURCES"];
const char* query_sql = [querySql UTF8String];
if (sqlite3_prepare(sourceDB, query_sql, -1, &statement, NULL)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
NSString *name = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
NSString *category = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
SourceDB *source = [[SourceDB alloc]init];
[source setName:name];
[source setLink:link];
[source setCategory:category];
[arrayOfSource addObject:source];
}
}
}
[[self myTableView]reloadData];
}
- (void)createOrOpenDB
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:#"sources.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dbPathString]) {
const char *dbPath = [dbPathString UTF8String];
//creat db here
if (sqlite3_open(dbPath, &sourceDB)==SQLITE_OK) {
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS SOURCES (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, LINK TEXT, CATEGORY TEXT)";
sqlite3_exec(sourceDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(sourceDB);
}
}
}
- (IBAction)addSourceButton:(id)sender
{
char *error;
if (sqlite3_open([dbPathString UTF8String], &sourceDB)==SQLITE_OK) {
NSString *inserStmt = [NSString stringWithFormat:#"INSERT INTO SOURCES(NAME,LINK,CATEGORY) values ('%s', '%s','%s')",[self.nameField.text UTF8String], [self.linkField.text UTF8String],[self.categoryField.text UTF8String]];
const char *insert_stmt = [inserStmt UTF8String];
if (sqlite3_exec(sourceDB, insert_stmt, NULL, NULL, &error)==SQLITE_OK) {
NSLog(#"Source added");
SourceDB *source = [[SourceDB alloc]init];
[source setName:self.nameField.text];
[source setLink:self.linkField.text];
[source setCategory:self.categoryField.text];
[arrayOfSource addObject:source];
}
sqlite3_close(sourceDB);
}
}
- (IBAction)deleteSourceButton:(id)sender
{
[[self myTableView]setEditing:!self.myTableView.editing animated:YES];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
SourceDB *s = [arrayOfSource objectAtIndex:indexPath.row];
[self deleteData:[NSString stringWithFormat:#"Delete from sources where name is '%s'", [s.name UTF8String]]];
[arrayOfSource removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void)deleteData:(NSString *)deleteQuery
{
char *error;
if (sqlite3_exec(sourceDB, [deleteQuery UTF8String], NULL, NULL, &error)==SQLITE_OK) {
NSLog(#"Source deleted");
}
}
- (IBAction)showSourceButton:(id)sender
{
sqlite3_stmt *statement;
if (sqlite3_open([dbPathString UTF8String], &sourceDB)==SQLITE_OK) {
[arrayOfSource removeAllObjects];
NSString *querySql = [NSString stringWithFormat:#"SELECT * FROM SOURCES"];
const char* query_sql = [querySql UTF8String];
if (sqlite3_prepare(sourceDB, query_sql, -1, &statement, NULL)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
NSString *name = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
NSString *category = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
SourceDB *source = [[SourceDB alloc]init];
[source setName:name];
[source setLink:link];
[source setCategory:category];
[arrayOfSource addObject:source];
}
}
}
[[self myTableView]reloadData];
}
Now i created a method in my FeedsViewConrtoller:
-(void)ReadData
{
[self createOrOpenDB];
feedsArray = [[NSMutableArray alloc] init];
const char *dbPath = [dbPathString UTF8String];
if (sqlite3_open(dbPath, &sourceDB)==SQLITE_OK)
{
const char *sqlstmt = "SELECT LINK FROM SOURCES";
sqlite3_stmt *completedstmt;
if (sqlite3_prepare_v2(sourceDB, sqlstmt, -1, &completedstmt, NULL)==SQLITE_OK)
{
while(sqlite3_step(completedstmt)==SQLITE_ROW)
{
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(completedstmt, 2)];
SourceDB *source = [[SourceDB alloc]init];
[source setLink:link];
[feedsArray addObject:link];
}
}
}
}
And when i change
self.feeds = [NSMutableArray arrayWithObjects:#"http://pcworld.al/feed",#"http://geek.com/feed", #"http://feeds.feedburner.com/Mobilecrunch",#"http://zeri.info/rss/rss-5.xml",
nil];
to:
self.feeds = [NSMutableArray arrayWithArray:feedsArray];
i get the following error:
2013-08-14 15:03:55.328 ShqipCom[3128:c07] (null)
What am i doing wrong here?
Thanks a lot!
Granit
In ReadData, you're returning one column, but then retrieving the third column with:
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(completedstmt, 2)];
That should be:
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(completedstmt, 0)];
A couple of other thoughts:
Part of the reason it's hard for us to answer this is that you aren't reporting SQLite errors. I'd suggest logging when a SQLite test failed, e.g.:
if (sqlite3_prepare_v2(sourceDB, sqlstmt, -1, &completedstmt, NULL)==SQLITE_OK
{
while(sqlite3_step(completedstmt)==SQLITE_ROW)
{
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(completedstmt, 2)];
SourceDB *source = [[SourceDB alloc]init];
[source setLink:link];
[feedsArray addObject:link];
}
}
whereas you might want something like:
if (sqlite3_prepare_v2(sourceDB, sqlstmt, -1, &completedstmt, NULL)!=SQLITE_OK
{
NSLog(#"%s: prepare error: %s", __FUNCTION__, sqlite3_errmsg(sourceDB));
return;
}
int rc;
while ((rc = sqlite3_step(completedstmt)) == SQLITE_ROW)
{
NSString *link = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(completedstmt, 2)];
SourceDB *source = [[SourceDB alloc]init];
[source setLink:link];
[feedsArray addObject:link];
}
if (rc != SQLITE_DONE)
{
NSLog(#"%s: step error: %s", __FUNCTION__, sqlite3_errmsg(sourceDB));
return;
}
You really should be checking the result of every SQLite call, and reporting an error message if not successful. Otherwise you're flying blind.
On your INSERT statement, are you 100% sure that those three fields will never have an apostrophe in them? (Also, if the user is entering any of this data, you have to be concerned about SQL injection attacks.) Generally you'd use ? placeholders in your SQL, you'd prepare the SQL with sqlite3_prepare_v2, and then use sqlite3_bind_text to bind text values to those placeholders, and then you'd sqlite3_step and confirm a return value of SQLITE_DONE.
Note, checking each and every sqlite3_xxx function call return result and doing all of the necessary sqlite3_bind_xxx calls is a little cumbersome. In your next project, if you want to streamline your SQLite code, you might want to consider using FMDB.
Your can add any object in NSMutableArray by
[myArray name addObject:mYString]; // add whatever object here;
if you want to add Array to you NSMutableArray
[myArray addObjectsFromArray:anOtherArray];