SQLite and OBJ-C DB clear when launch application - iphone

I've a SQLite db on this position
/Users/software/Library/Application Support/iPhone Simulator/5.0/Applications/723EEE91-CB9D-4A27-8492-D61E127E72B7/myAPP.app/localDB.sqlite
No problems on write, delete or read data.
For example if I write on DB and close application, I find data in my DB, but if I restart the app my DB will clear. Can someone tell me why?
This is an example of a DB instance
SQLiteUtilities *db = [[SQLiteUtilities alloc]init:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"localDB.sqlite"]];
[db loadValuesFromQuery:#"SELECT * FROM categories;"];
for (int i = 0; i < [db getSize]; i++) {
NSLog(#"-- %#", [db objectAtIndex:i]);
}
[db release];
-(void)loadValuesFromQuery:(NSString *)query {
GenericRecord *record = [[[GenericRecord alloc]init] autorelease];
if (sqlite3_open([pathDB UTF8String], &database) == SQLITE_OK) {
// query che ricava i valori
const char *sql = (const char *) [query UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
// ricaviamo i valori letti dalla query
record.uniqueID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
record.superID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
record.subSuperID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
record.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
record.description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
record.price = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
record.note = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
record.pictureURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 8)];
record.catName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 9)];
record.subCatName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 10)];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 11) length:sqlite3_column_bytes(selectstmt, 11)];
if(data) record.imageBig = [UIImage imageWithData:data];
[self.list addObject:record];
}
}
}
sqlite3_close(database);
}

Also curious why I'm seeing so much raw sqlite3 work these days - any reason you're not using Core Data? Just a suggestion - it may not fit your needs (i.e., schema already exists and you're downloading it directly, etc).

Related

how to select unique values from sqlite table in iphone

I have data in my sqlite table like the following
here is the my table description and fields
coffeeID;
category;
sub_Category;
content_Type;
content_Title;
content_Description;
content_Id;
publisher;
content_Source;
update_date_time;
and here is the code where i am now getting all values but i want unique values.
const char *sql = "select * from category";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.category=sqlite3_column_int(selectstmt,1);
coffeeObj.sub_Category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.content_Type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.content_Title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,4)];
coffeeObj.publisher = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
coffeeObj.content_Description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
coffeeObj.content_Id = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
coffeeObj.content_Source = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 8)];
int count=[appDelegate.coffeeArray count];
NSLog(#"count is beofore getting values %d",count);
[appDelegate.coffeeArray addObject:coffeeObj];
int countone=[appDelegate.coffeeArray count];
NSLog(#"count is after getting values %d",countone);
[coffeeObj release];
}
}
}
I want that if it has two same sub categories then it may show only one like mean only unique records not the categories with same name repeated.
You can use Group by in SQL Query
"Select * From category GROUP BY category"
You can group by any column

How to get int data from iphone sqlite data base

I am getting data from iphone sqlite like this. I have 6 records in the table.
My table has fields responses_Id, participant_Id, answer_option, answer_text, update_date_time only all are varchar fields except responses_Id and participant_Id)
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.participant_Id=(This is integerin table)
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
When I NSlog data it does not show any things.
Look into the SQLite Documentation. All result values from queries are defined there.
You can use sqlite3_column_int for Integers similar to sqlite3_column_text for Text
NSNumber *primaryKey = [NSNumber numberWithInt:(int)sqlite3_column_int(selectstmt, 0)];
while(sqlite3_step(selectAllStmt) == SQLITE_ROW)
{
NSLog(#"record found");
char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if (temp!=nil) {
intId=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
// [pool release];
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey;
NSInteger intparticipant_Id;
char *temp = (char *)sqlite3_column_text(selectstmt, 0);
if (temp!=nil) {
primaryKey=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
temp = (char *)sqlite3_column_text(selectstmt, 1);
if (temp!=nil) {
intparticipant_Id=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
coffeeObj.participant_Id=intparticipant_Id;
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
Note:- char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if(temp != NULL)
str = [NSString stringWithUTF8String:temp];
else
str = #"";
temp =NULL;
If you want to take integer then you can do type casting "str = [NSString stringWithUTF8String:temp];" here......

allocated too much memory

I try to do an app but I get a lot of crash an memory allocation, then I try to reduce all the code and clean it, now I get this e
Why I get:
Potential leak of an object allocated on line 101 and stored into 'livello'
- (id) leggiLivelloDaTabella:(NSString *)tabella {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:#"DataBase.sqlite"];
sqlite3 *database;
Livello *livello = nil;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// query che ricava i valori
const char *sql = [[NSString stringWithFormat:#"select * from Livelli WHERE Tabella = '%#'",tabella] UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
// ricaviamo i valori letti dalla query
NSString *nomeTabella = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
NSString *risposteGiuste = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
NSString *stato = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
NSString *risposteMinime = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
NSString *tentativiSbagliati = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
NSString *tentativiTotali = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString *popUp = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
NSString *idLivello = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
livello = [[Livello alloc] initLivelloWithTabella:nomeTabella
rispGiuste:risposteGiuste
statoLivello:stato
rispMinime:risposteMinime
tentativiSbagliati:tentativiSbagliati
tentativiTot:tentativiTotali
disaplyPopUp:popUp
idLevel:idLivello];
}
}
sqlite3_finalize(selectstmt);
sqlite3_close(database);
selectstmt = nil;
}
else
sqlite3_close(database);
return livello;
}
If you are not using ARC (automatic reference counting), you should be marking livello as autorelease. Try using this as your return statement:
return [livello autorelease];
Here is some more info on ARC:
http://maniacdev.com/ios-5-sdk-tutorial-and-guide/arc-automatic-reference-counting/
http://longweekendmobile.com/2011/09/07/objc-automatic-reference-counting-in-xcode-explained/

Problem With Sqlite Data Retrieving

I have an SQLite database, and when I am trying to get the data from the database, I get the last inserted element repeatedly. How can I get all the elements with no repetition.
The code I've written:
- (NSMutableArray *) gettingData {
sqlDict = [[NSMutableDictionary alloc] init];
membersInfoArray =[[NSMutableArray alloc]init ];
[self checkAndCreateDatabase];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from ProductList";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *prdbcode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
[sqlDict setObject:prdbcode forKey:#"Barcode"];
[prdbcode release];
NSString *prdname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
[sqlDict setObject:prdname forKey:#"ProductName"];
[prdname release];
NSString *prdDesc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
[sqlDict setObject:prdDesc forKey:#"ProductDescription"];
[prdDesc release];
NSString *prdstatus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
[sqlDict setObject:prdstatus forKey:#"ProductStatus"];
[prdstatus release];
[membersInfoArray addObject:sqlDict];
[sqlDict release];
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return membersInfoArray;
}
I am retrieving the data as follows:
NSMutableArray *sqlArray = [sqlViewController gettingData];
Thank you.
Just Declare your array globally instead of declare locally in your method. Your problem will resolved.

How to dynamically sorting an NSMutableArray in Objective-C?

I am retrieving rows from SQLite table, then dynamically creating an object, and then adding the object to an NSMutableArray. My problem is that I am unable to figure out a way to dynamically sort the objects in the array based on the distance attribute (which is a double), as I am adding each object to the NSMutableArray in a for-loop, from smallest to largest.
My relevant code looks like this:
sqlite3 *database;
//Init the restaurant array
restaurants = [[NSMutableArray alloc] init];
CLLocation *firstLocation = [[[CLLocation alloc] initWithLatitude:userLatitude longitude:userLongitude] autorelease];
//Open the database from the users filesystem
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
//setup the SQL statement and compile it for faster access
const char *sqlStatement = "select * from restaurant";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
//read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCity = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aProvinceState = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aPostalZipCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aCountry = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aPhoneNumber = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aHours = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
double aLat = sqlite3_column_double(compiledStatement, 9);
double aLon = sqlite3_column_double(compiledStatement, 10);
CLLocation *secondLocation = [[[CLLocation alloc] initWithLatitude:aLat longitude:aLon] autorelease];
CLLocationDistance restDistance = [secondLocation distanceFromLocation:firstLocation];
CLLocationDistance distanceKm = restDistance / 1000.0;
NSString *aDist = [[NSString alloc] initWithFormat: #"%f", distanceKm];
Restaurant *restaurant = [[Restaurant alloc] initWithName:aName address:aAddress city:aCity provinceState:aProvinceState postalZipCode:aPostalZipCode country:aCountry phoneNumber:aPhoneNumber hours:aHours latitude:aLat longitude:aLon distance:aDist];
//add the restaurant object to the restaurant array
[restaurants addObject:restaurant];
[restaurant release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
Once this function has finished its course, the restaurants array should be a sorted array containing restaurant objects that are in order of nearest (smallest distance double value) to furthest (largest distance double value).
Use NSMutableArray's sortUsingSelector to call a comparison function on your Restaurant object.
#implementation Restaurant
- (double) distance { return _distance; }
- (NSComparisonResult) compareDistance:(Restaurant *) iRHS {
double lhs, rhs;
lhs = [self distance];
rhs = [iRHS distance];
if ( lhs < rhs ) return NSOrderedAscending;
if ( lhs > rhs ) return NSOrderedDescending;
return NSOrderedSame;
}
#end
...
[restaurants sortUsingSelector: #selector(compareDistance:)];