I'm using the code below to populate an array from my ManagedObjectContext, but what I would like to do is to fetch only the unique ID numbers of each row matching my query (itemType = 1) and populate the fetchResults array with only these unique ID numbers. Is that possible?
Any help is appreciated.
lq
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"MyAppName"
inManagedObjectContext:[self managedObjectContext]]];
NSError *error = nil;
NSPredicate *predicate;
NSArray *fetchResults;
predicate = [NSPredicate predicateWithFormat:#"(itemType = %i)", 1];
[request setPredicate:predicate];
fetchResults = [managedObjectContext executeFetchRequest:request error:&error];
if (!fetchResults) {
// NSLog(#"no fetch results error %#", error);
}
self.mutableArrayName = [NSMutableArray arrayWithArray:fetchResults];
[request release];
To help anyone with similar needs, I'm answering my own question. I figured out a solution that works for pulling specific row and/or column data from my SQLite database in query form, rather than using Fetch with Predicate. (Note: code shows examples for extracting string and integer data types.)
First, add a Framework for libsqlite3.0.dylib
In the header add the following file:
#import <sqlite3.h>
#interface MyViewController : UIViewController {
NSMutableArray *dataArray; // This array will hold data you will extract
NSArray *summaryArray; // This holds an array of PKIDs that will be queried
}
#property (nonatomic, retain) NSMutableArray *dataArray;
#property (nonatomic, assign) NSArray *summaryArray;
- (void)getData:(NSInteger *)intPKID;
- (NSString *) getDBPath;
#end
In the implementation file add the following:
static sqlite3 *database = nil; // add this before the #implementation line
#synthesize dataArray;
#synthesize summaryArray;
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"MyDatabaseName.sqlite"];
}
- (void)getData:(NSInteger *)intPKID {
NSString *dbPath = [self getDBPath];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSString *strSQL;
NSString *strExtractedData;
NSUInteger count;
NSInteger intPK;
if (self.dataArray == nil) {
self.dataArray = [[[NSMutableArray alloc] init] autorelease];
} else {
[self.dataArray removeAllObjects];
}
count = [self.summaryArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Extract a specific row matching a PK_ID:
strSQL = [NSString stringWithFormat: #"select intPKID, strColumnName from MyDatabaseName where (PKID = %i)", [[self.summaryArray objectAtIndex:i]intValue]];
// Extract a range of rows matching some search criteria:
// strSQL = [NSString stringWithFormat: #"select intPKID, strColumnName from MyDatabaseName where (ITEMTYPE = '%i')", 1];
const char *sql = (const char *) [strSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
[self.dataArray addObject:[NSNumber numberWithInt:qlite3_column_int(selectstmt, 0)]];
[self.dataArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];
}
}
}
} else {
sqlite3_close(database); // Database not responding - close the database connection
}
}
predicate = [NSPredicate predicateWithFormat:#"itemType == 1"];
or
predicate = [NSPredicate predicateWithFormat:#"(itemType == %i)", 1];
should both work.
Related
Im storing some values in my server. Then i fetched that values using JSON and added to local database table. Then i need to display that values to view. But array values displaying in NSLog. It won't displaying in view. I don't need to display in TableView.
code:
-(void) addDataToArray{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSLog(#"docs dir is %#", documentsDirectory);
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"db1.sqlite"];
//NSLog(#"filepath %#",path);
mArray = [[NSMutableArray alloc]init];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
// const char *sql = "SELECT id,cat_name FROM categories order by order_by";
const char *sql = "SELECT * FROM categories";
NSLog(#"Sql is %s",sql);
sqlite3_stmt *statement;
int catID = 0;
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) {
NSString *catName = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
NSLog(#"catName is %#",catName);
[mArray addObject:catName];
// [self.view addConstraints:mArray];
NSLog(#"mArray is %#", mArray);
[catName release];
catID = sqlite3_column_int(statement, 0);
}
}
sqlite3_finalize(statement);
} else {
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
[self addDataToArray];
}
NSLog:
catName is person1
mArray is (
person1
)
catName is person2
mArray is (
person1
person2
)
TextView:
UITextView *txt=[[UITextView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
// txt.text=[mArray objectAtIndex:0];
[self.view addSubview:txt];
for (int i = 0; i<[mArray count]; i++ ) { NSLog(#"index %d",i); }
You need to merge array's objects to convert them in string, because you can't show an array in textView directly. If mArray contains NSString type object then you can do like this:
NSMutableString *string = [[NSMutableString alloc] init];
for (id obj in mArray){
[string appendString:obj];
}
textView.text = string;
If you want to show each person in next line you can add \n after each name.
I am working on an iPhone app. I have created a re usable class in which a sqlite getData method is written. I want to pass a sql statement from my controller and want to get an array back with all of the rows.
Can I get sqlite3_stmt object stored into array and return that array, so at calling point I can cast it and find out each columns value?
My current code is like that :
-(NSMutableArray*)getData:(NSString*) SqlQuery
{
// The Database is stoed in the application bundle
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"sqliteClasses.sqlite"];
if(sqlite3_open([path UTF8String], &contactDB) == SQLITE_OK)
{
const char *sql = (const char*)[SqlQuery UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(contactDB, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement) == SQLITE_ROW)//(stepResult == SQLITE_ROW)
{
// [arrayRecords addObject:compiledStatement];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(contactDB);
return arrayRecords;
}
The error line is : [arrayRecords addObject:compiledStatement];
How Can I achieve this ? any alternate for implementing this ?
Thanks.
- (NSArray *) getActionWithFilters:(NSDictionary *)dictionary ClassName:(NSString *)className Error:(NSError **)error{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM %# %#",className,[self getFitlerArrayByDictionary:dictionary]];
sqlite3_stmt *statement = [self getItemsWithQuery:query];
NSMutableArray *array = [[NSMutableArray alloc] init];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *itemDic = [[NSMutableDictionary alloc] init];
int columns = sqlite3_column_count(statement);
for (int i=0; i<columns; i++) {
char *name = (char *)sqlite3_column_name(statement, i);
NSString *key = [NSString stringWithUTF8String:name];
switch (sqlite3_column_type(statement, i)) {
case SQLITE_INTEGER:{
int num = sqlite3_column_int(statement, i);
[itemDic setValue:[NSNumber numberWithInt:num] forKey:key];
}
break;
case SQLITE_FLOAT:{
float num = sqlite3_column_double(statement, i);
[itemDic setValue:[NSNumber numberWithFloat:num] forKey:key];
}
break;
case SQLITE3_TEXT:{
char *text = (char *)sqlite3_column_text(statement, i);
[itemDic setValue:[NSString stringWithUTF8String:text] forKey:key];
}
break;
case SQLITE_BLOB:{
//Need to implement
[itemDic setValue:#"binary" forKey:key];
}
break;
case SQLITE_NULL:{
[itemDic setValue:[NSNull null] forKey:key];
}
default:
break;
}
}
[array addObject:itemDic];
[itemDic release];
}
return [array autorelease];
}
How can I retain all the row from login table? I can retain only one row, why not others? Am I using wrong query? Please check my code:
#import "loginAppDelegate.h"
#import "global.h"
#import <sqlite3.h>
#import "logincontroller.h"
#implementation loginAppDelegate
#synthesize window;
#synthesize loginView;
//databaseName=#"login.sqlite";
-(void) chekAndCreateDatabase
{
BOOL success;
//sqlite3 *databaseName=#"login.sqlite";
NSFileManager *fileManager=[NSFileManager defaultManager];
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
success=[fileManager fileExistsAtPath:databasePath];
if(success)return;
NSString *databasePathFromApp=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"login.sqlite"];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void) Data
{
Gpass=#"";
Guname=#"";
sqlite3_stmt *detailStmt=nil;
//sqlite3 *databaseName;
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
[self chekAndCreateDatabase];
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String],&database)==SQLITE_OK) {
if (detailStmt==nil) {
const char *sql= "select *from Loginchk where uname='%?'and password='%?'";
//NSString *sql = [[NSString alloc] initWithFormat:#"SELECT * FROM Loginchk WHERE uname ='%#' and password ='%#' ",Uname.text,Password.text];
if (sqlite3_prepare_v2(database,sql,-1,&detailStmt,NULL)==SQLITE_OK) {
sqlite3_bind_text(detailStmt,1,[Gunameq UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(detailStmt,2,[Gpassq UTF8String],-1,SQLITE_TRANSIENT);
if (SQLITE_DONE!= sqlite3_step(detailStmt)) {
Guname=[NSString stringWithUTF8String:(char*)sqlite3_column_text(detailStmt,0)];
Gpass =[NSString stringWithUTF8String:(char*)sqlite3_column_text(detailStmt,1)];
NSLog(#"'%#'",Guname);
NSLog(#"'%#'",Gpass);
}
}
sqlite3_finalize(detailStmt);
}
}
sqlite3_close(database);
}
//Declare Class as Following to store user details UserDetails.h
#interface UserDetails : NSObject
{
NSString *strUserName;
NSString *strPassword;
}
#property (nonatomic,assign) NSString * strUserName;
#property (nonatomic,retain) NSString * strPassword;
//Declare Class as Following to store user details UserDetails.m
#implementation UserDetails
#synthesize strUserName,strPassword;
-(void)dealloc
{
[super dealloc];
[strUserName release];
[strPassword release];
}
//Declare Class as Following to store user details Your ApplicationDelegate.m file
-(NSMutableArray)getAllUserDetails
{
sqlite3_stmt *selectStmt = nil;
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
[self chekAndCreateDatabase];
NSMutableArray *arrUsers = [[NSMutableArray alloc] init];
const char *sqlStatement = "your query";
if(sqlite3_prepare_v2(database, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(selectStmt) == SQLITE_ROW)
{
UserDetails *objUserDetail = [[UserDetails alloc] init];
objUserDetail.userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 1)];
objUserDetail.password = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 2)];
[arrUsers addObject:objUserDetail];
[objUserDetail release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(selectStmt);
selectStmt = nil;
}
call this function in button click event as
-(IBAction)btnLogin
{
BOOL isUserExists = NO;
NSMutableArray *arrAllUsers = [loginAppDelegate getAllUserDetails];
//Normal Checking Stuff
for(UserDetails *objUser in arrAllUsers)
{
if([txtUserTextBox.text isEqualToString:objUser.strUserName] && [txtPasswordTextBox.text isEqualToString:objUser.strPassword])
{
//True Login
isUserExists = YES;
break;
}
}
//Check your stuff if user exists or not what to do
if(isUserExists)
{
Heading to next screen;
}
else
{
Alertmessage
}
}
I am creating an application where I am using SQLite database to save data. But when I run my application I get the following errors:
#interface TDatabase : NSObject {
sqlite3 *database;
}
+(TDatabase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
#end
#import "TDatabase.h"
#import <sqlite3.h>
#implementation TDatabase
static TDatabase *SampleDataBase =nil;
+(TDatabase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[TDatabase alloc] init];
}
return SampleDataBase;
}
-(NSString *)GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return insertSql;
}
NSString *sql = #"select * from Location";
const location = [[TDatabase shareDataBase] getAllDataForQuery:sql forDatabase:#"journeydatabase.sqlite"];//1
NSString* insertSql = [NSString stringWithFormat:#"insert into Location values ('city','name','phone')"];//2
const insert =[[TDatabase shareDataBase] inseryQuery:insertSql forDatabase:#"journeydatabase.sqlite"];//3
in line no 1,2,3 I get the same error:
initializer element is not constant
What might be the problem?
#rani writing your own methods to deal with sqlite database is very painstaking. You should use fmdb wrapper class or use core data. I personally prefer fmdb. Initially I was doing the same way you were. I found about fmdb here. After using it I had to write very little code whenever I have to deal With sqlite db.
how to created an application that records a series of longitude and latitude values in a SQLite database and display them as a coloured track on a MapActivity.
I need help. How can store the map coordinates in sqlite database and display like journey details in table .For example I have done one journey from mumbai to Pune .Then how can store the data into database that can available for future reference .when user click on journey name it should give all details
If you are new to Sqlite Then look into this class for data base
Create two database file as the following
---->>>>
Database.h
Write the following code in this file
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface DataBase : NSObject {
sqlite3 *database;
}
+(DataBase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1;
-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1;
#end
---->>>>
Database.m
Write the following code in this file
#import "DataBase.h"
#implementation DataBase
static DataBase *SampleDataBase =nil;
+(DataBase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[DataBase alloc] init];
}
return SampleDataBase;
}
-(NSString *) GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[updateSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[deleteSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
#end
Now to get data use the following code
NSString *sql = #"select * from UserInfo"; <br>
userInfo = [[DataBase shareDataBase] getAllDataForQuery:sql forDatabase:#"Sample.db"];
It will return array of all the row in form of NSDictionary.
To add new record use the following code
NSString *sql = [NSString stringWithFormat:#"insert into userInfo values ('city','name','phone')"];
[[DataBase shareDataBase] inseryQuery:sql forDatabase:#"Sample.db"];
In the same way there is also method to update and delete record.
so This is the best example I have seen we just need to call one method to for fetch, insert , update or delete.
Thanks for seeing the question,
To get location import corelocation framework in your project.
follow this link
http://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007801 to get sample for getting location.
This is the format to set location in json
[{"Longitude":"45.2655","Latitude":"23.2655"},{"Longitude":"45.2655","Latitude":"23.2655"},{"Longitude":"45.2655","Latitude":"23.2655"}]
Thanks.
You need to create a table with fields ...... Source,Destination,SourceLat,SourceLong,DestinationLat,DestinationLong....... and in this you will pass
Source - Mumbai,(or other) - text - varchar type
Destinatino - Pune, (or other) -text - varchar type
SourceLat - coordinate.latitude; - number with decimal precison upto 10 points.
SourceLong - coordinate.longitude - number with decimal precison upto 10 points.
DestinationLat - coordinate.latitude; - number with decimal precison upto 10 points.
DestinationLong - coordinate.longitude - number with decimal precison upto 10 points.
Thanks,
First you need to create object of NSMutableArray *arrayOflocation; in .h file,
Then in you locationUpdate method write the following code
NSMutableDictionary *LocationDic = [[NSMutableDictionary alloc] init];
[LocationDic setObject:[NSString stringWithFormat:#"%f",c.latitude] forKey:#"Latitude"];
[LocationDic setObject:[NSString stringWithFormat:#"%f",c.longitude] forKey:#"Longitude"];
[arrayOflocation addObject:LocationDic];
now when you save the trip you need to create the string for the json format for that you need to use json API you can get it using google easily . write the following code when you want to save the string in file.
NSString *dataString = [arrayOflocation JSONRepresentation];
//// code to write dataString in txt file.
and at finally need to store the file name in sqlite along with other detail for the trip.