How to write and retrieve the sqlite data into the file - iphone

Friend it just general question .
How can write and retrieve the data on to the file .And how can make this file in .csv format.
For example i am retrieve data like that
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
Than how can write this data on to the file in .csv format.
And than How can i retrieve this data

To write csv
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
NSData *csvData = [coords dataUsingEncoding:NSUTF8StringEncoding];
NSArray *UsrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocsDir = [UsrDocPath objectAtIndex:0];
NSString *csvPath = [DocsDir stringByAppendingPathComponent:#"coords.csv"];
//This is upto your logic that do you want to remove existant csv file or not
BOOL success = [FileManager fileExistsAtPath:csvPath];
if(success){
[FileManager removeItemAtPath:csvPath error:&error];
}
[csvData writeToFile:csvPath atomically:YES];
To read from file
NSData *csvData = [NSData dataWithContentsOfFile:csvPath];
NSString *strCSV = [[NSString alloc]initWithData:csvData encoding:NSUTF8StringEncoding];
Hope it helps

There is a csv parser written by dave delong. you can use that.

First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
}
As for writing to a CSV file, well there's code for that too:
#import "CHCSV.h"
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
//write stuff
[csvWriter closeFile];
[csvWriter release];
And to combine them, you'd do:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
if (![db open]) {
//couldn't open the database
[db release];
return nil;
}
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
for (NSString *columnName in orderedKeys) {
id value = [resultRow objectForKey:columnName];
[csvWriter writeField:value];
}
[csvWriter writeLine];
}
[csvWriter closeFile];
[csvWriter release];
[db close];
[db release];
That will write the contents of the tableName table out to a CSV file.
Then you can use CSV Parser to parse the CSV and get data.

Related

Save text in plist file with specific date

I am trying to store some stings into a plist file, the saving process works fine, but these notes should be saved based on a specific date, for example I enter a note on 2 Feb then I need enter another note on 5 Feb, and when I move during these dates my notes should show on these dates. I would be grateful if you help me.
Here is my code:
//Save Setting ///////////////////
- (NSString *) saveFilePath
{
NSArray *pathArray =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDate *date = [NSDate date];
return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:#"note.plist"];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSArray *values = [[NSArray alloc] initWithObjects:saveTextToday.text ,nil];
[values writeToFile:[self saveFilePath] atomically:YES];
[values release];
}
- (void)viewDidLoad
{
////Save Setting /////////////////////////////////////////////////
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
saveTextToday.text = [values objectAtIndex:0];
[values release];
}
// notification
UIApplication *myApp = [UIApplication sharedApplication];
// add yourself to the dispatch table
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:myApp];
}
It appears you're saving an array to a file, but using a ".plist" file extension. While the file created will be a plist file, there is no date information in the content.
Instead of an array, you could use an NSDictionary. Use the current date as the key, and the array you're using now as the object. Like this:
NSMutableDictionary *myDictionary = [NSMutableDictionary alloc] initWithContentsOfFile:myPath];
NSString *todayKey = [self showPersianFullDate]; // or [self showPersianFullDate:[NSDate date]]
[myDictionary setObject:saveTextToday.text forKey:todayKey];
[myDictionary writeToFile:[self saveFilePath] atomically:YES];
I think what you want to do is use the NSFileManager to find out when the file was saved, like this:
NSString *path = #"the path you've saved you plist to";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDate *creationDate = nil;
if ([fileManager fileExistsAtPath:path])
{
NSError *error = nil;
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:&error];
creationDate = [attributes objectForKey:NSFileCreationDate];
}
creationDate now contains the date when the file was first saved. To get the date when it was last saved, use NSFileModificationDate instead.

Arabic string in NSMutableArray or NSMutableDictionary

I have a problem when I add an arabic string to NSMutableArray or NSMutableDictionary.
Example:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"%#",data);
Output:
2012-01-18 21:55:05.646 aa[367:207] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
my problem exactly i save this data to sqlite [data objectForKey:#"name"] its saved \U0641\U0631\U0633\U0627\U0646 and when fetch data to to put it in UILabel or anything like it the text be \U0641\U0631\U0633\U0627\U0646
Any Help? Thank you :)
- (void)SaveMessage {
NSMutableDictionary *TableProperties = [[NSMutableDictionary alloc]init];
[TableProperties setObject:#"INSERT" forKey:#"Operation"];
[TableProperties setObject:#"savedmessages" forKey:#"tableName"];
NSString *string = [[NSString alloc]initWithFormat:#" %#",MessageBox.text];
[TableProperties setValue:string forKey:#"message"];
NSString *msgResult;
NSArray *result = [[DatabaseFunctions database] DataBaseOperation:TableProperties];
if ([[result objectAtIndex:0] isEqualToString:#"Done"])
msgResult = #"تم حفظ الرسالة بنجاح";
else
msgResult = #"لم تت العملية بنجاح حاول لاحقا";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"حفظ الرسالة"
message:msgResult
delegate:self
cancelButtonTitle:#"موافق"
otherButtonTitles:nil, nil ];
[alert show];
}
- (NSArray *)DataBaseOperation:(NSMutableDictionary *)TableProperties{
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *Operation = [TableProperties objectForKey:#"Operation"];
if ([Operation isEqualToString:#"SELECT" ]) {
NSString *tableColumns = [TableProperties objectForKey:#"tableColumns"];
NSString *tableName = [TableProperties objectForKey:#"tableName"];
NSString *tableWhere = [TableProperties objectForKey:#"tableWhere"];
NSString *tableOrder = [TableProperties objectForKey:#"tableOrder"];
NSString *tableLimit = [TableProperties objectForKey:#"tableLimit"];
NSString *Query;
if ([tableLimit isEqualToString:#"NO"]) {
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}else{
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %# LIMIT %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}
NSArray *FieldArray = [[TableProperties objectForKey:#"tableColumns"] componentsSeparatedByString:#","];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *Row = [[NSMutableDictionary alloc]init];
NSString *uniqueId = [[NSString alloc] initWithFormat:#"%i",sqlite3_column_int(statement, 0)];
[Row setObject:uniqueId forKey:#"uniqueId"];
for (int i = 1; i<[FieldArray count]; i++) {
NSString *column = [[NSString alloc] initWithUTF8String:(char *) sqlite3_column_text(statement, i)];
[Row setObject:column forKey:[FieldArray objectAtIndex:i]];
}
Objects *rowOfTable = [[Objects alloc] initSelectDataFromTables:Row];
Row = nil;
[retval addObject:rowOfTable];
}
sqlite3_finalize(statement);
}
}
else if([Operation isEqualToString:#"INSERT" ]) {
NSString *tableName = [TableProperties objectForKey:#"tableName"];
[TableProperties removeObjectForKey:#"Operation"];
[TableProperties removeObjectForKey:#"tableName"];
NSArray *Columns = [TableProperties allKeys];
NSArray *Values = [TableProperties allValues];
NSString *Query = [[NSString alloc] initWithFormat:#"INSERT INTO %# %# VALUES %#",tableName,Columns,Values];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK)
if (SQLITE_DONE!=sqlite3_step(statement)){
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}else{
NSLog(#"Data inserted Successfully");
[retval addObject:#"Done"];
}
else{
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}
sqlite3_finalize(statement);
}
return retval;
}
When you log an object using %#, NSLog sends the description message to the object and prints the resulting string.
An NSDictionary responds to the description message by encoding its keys and values in a "safe" format, escaping non-ASCII characters using \U#### codes.
If you pass the Arabic string to NSLog directly, it will just print the string without the escape codes:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"data = %#",data);
NSLog(#"string = %#", [data objectForKey:#"name"]);
Output:
2012-01-18 14:17:42.498 Animal[62723:f803] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
2012-01-18 14:17:42.500 Animal[62723:f803] فرسان
If you don't like the way NSDictionary responds to description, you will have to write your own method to format a dictionary as a string and use it to log your dictionary.
Update
I have looked at the source code you posted that talks to sqlite. The problem is that you are turning the values array ([TableProperties allValues]) into a string using the %# format specifier. This sends the description method to the NSArray, which returns a string. Just like NSDictionary, NSArray formats the description string in a "safe" format, escaping non-ASCII characters using \U#### codes.
You need to write your own method that takes an array and turns it into a string and does not escape special characters. (It needs to escape quotes though.)

how to write plist array of dictionary objects..dynamically and populating the tableview

m working with plist and i am new to it..
I want to save two type of values,these two are labels,i.e
label1
label2
so for that i tried to write the code but was able to save only for one
label i.e label1..in a plist and then populate it into the table so i got one value on
cell.textlabel.text = label1.text
but i need this also..
cell.detailedlabel.text = label2.text
so below is my code.. to save label1.text
-(IBAction) myBrand:(id) sender
{
NSLog(#"mylist Clicked");
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [docsDir stringByAppendingPathComponent:#"Data.plist"];
[array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]];
[array addObject:searchLabel.text];
[array writeToFile:plistPath atomically: TRUE];
}
now if i want o save one more label..in the array and populate it on cells detailedlabel..how shall i proceed..please help me out..
Hi friends..I want o have something like this....
NSMutableArray *array = [[NSMutableArray alloc] init];
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our Data/plist file
NSString *plistPath = [docsDir stringByAppendingPathComponent:#"Data.plist"];
//This copies objects of plist to array if there is one
[array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]];
//[array addObject:entity];
[array insertObject:entity atIndex:0];
[array insertObject:category atIndex:0];
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: entity, category, nil] forKeys:[NSArray arrayWithObjects: #"Entity", #"Category", nil]];
Regards
Ranjit
go through the portion of the code below which will solve your problem of storing both label values in plist...
NSMutableArray *data = [[NSMutableArray alloc] init];
NSMutableDictionary* newDict = [[NSMutableDictionary alloc] init];
[newDict setValue:label1.text forKey:labell]; //forKey identify the name of the array element in dictionary for plist
[newDict setValue:label2.text forKey:label2];
[data addObject:newDrink];
[newDict release];

Creating NSMutableArray from xml file

I have an xml file with the following information.
<?xml version="1.0"?>
-<Party>
-<Player>
<Name>Butch</Name>
<Level>1</Level>
<Class>Fighter</Class>
</Player>
-<Player>
<Name>Shadow</Name>
<Level>2</Level>
<Class>Rogue</Class>
</Player>
-<Player>
<Name>Crak</Name>
<Level>3</Level>
<Class>Wizard</Class>
</Player>
</Party>
I try to add this to an NSMutableArray by doing the following.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Party" ofType:#"xml"];
NSData *xmlData = [[NSMutableArray alloc] initWithContentsOfFile:filePAth];
When I run this, my array object has no data in it.
If I replace the line with;
NSdata *xmlData = [NSdata dataWithContentsOfFole:filePath];
it will load my data but it is not in the format I require.
I'm very new to Objective-c and iPhone development and any help will be greatly appreciated.
If anymore info is needed I'll be happy to provide it.
edit - I'm using GDataXML to parse my xml
edit - My Parser class is as follows
#implementation PartyParser
+(NSString *)dataFilePath:(BOOL)forSave{
return [[NSBundle mainBundle] pathForResource:#"Party" ofType:#"xml"];
}
+(Party *)loadParty{
NSString *filePath = [self dataFilePath:FALSE];
//NSData *xmlData = [NSData dataWithContentsOfFile:filePath];
NSData *xmlData = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if(doc ==nil){return nil;}
NSLog(#"%#", doc.rootElement);
Party *party = [[[Party alloc] init] autorelease];
NSArray *partyMembers = [doc.rootElement elementsForName:#"Player"];
for (GDataXMLElement *partyMember in partyMembers)
{
NSString *name;
int level;
RPGClass rpgClass;
//Name
NSArray *names = [partyMember elementsForName:#"name"];
if(names.count > 0)
{
GDataXMLElement *firstName = (GDataXMLElement *) [names objectAtIndex:0];
name = firstName.stringValue;
}else continue;
//Level
NSArray *levels = [partyMember elementsForName:#"level"];
if(levels.count > 0)
{
GDataXMLElement *firstLevel = (GDataXMLElement *) [levels objectAtIndex:0];
level = firstLevel.stringValue.intValue;
}else continue;
//Class
NSArray *classes = [partyMember elementsForName:#"class"];
if(classes.count > 0)
{
GDataXMLElement *firstClass = (GDataXMLElement *) [classes objectAtIndex:0];
if([firstClass.stringValue caseInsensitiveCompare:#"fighter"] == NSOrderedSame)
{
rpgClass = RPGClassFighter;
}
else if([firstClass.stringValue caseInsensitiveCompare:#"rogue"] == NSOrderedSame)
{
rpgClass = RPGClassRogue;
}
else if([firstClass.stringValue caseInsensitiveCompare:#"wizard"] == NSOrderedSame)
{
rpgClass = RPGClassWizard;
}
else
{
continue;
}
}else continue;
Player *player = [[[Player alloc] initWithName:name level:level rpgClass:rpgClass] autorelease];
[party.players addObject:player];
}
//NSLog(#"%#", doc.rootElement);
//
[doc release];
[xmlData release];
return party;
}
#end
The XML file can not be any type of XML. It needs to be in the "property list" format.
Take a look at some Apple docs or some of the .plist files that will be in your project. That will show you how to create such a file.
Alternatively, create one using the "PList Editor" application that comes with the developer tools. It has a good UI for creating these files.
Lastly, your line "NSData* xmlData = ..." is very wrong - you're assigning a mutable array object to an NSData* variable. The types are not interchangeable by a long shot.
If you want to do full-blown XML parsing, there are various options that deserve a topic of their own. The XML used for plists is limited to Cocoa collections and simple data types.
Take a look to this XML Parser. It is called "TBXML", I have used that for a while and I'm quite happy with the result.
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
Just place your XML file (e.g. "myFileName.xml") anywhere in your project.
Read the xml file contents to NSData using:
NSString *myBundleString = [[NSBundle mainBundle] pathForResource:#"myFileName" ofType:#"xml"];
NSData *myData = [NSData dataWithContentsOfFile:myBundleString];
And parse your data using NSXMLParser:
NSXMLParser *myParser = [[NSXMLParser alloc] initWithData:myData];
[myParser setDelegate:self];
[myParser parse];
Happy parsing using the delegate methods!

How to export SQLite file into CSV file in iPhone SDK

In my app, I want to export a SQLite database file to CSV file..
Could you suggest me how to do this?
Thanks.
First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
}
As for writing to a CSV file, well there's code for that too:
#import "CHCSV.h"
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
//write stuff
[csvWriter closeFile];
[csvWriter release];
And to combine them, you'd do:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
if (![db open]) {
//couldn't open the database
[db release];
return nil;
}
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
for (NSString *columnName in orderedKeys) {
id value = [resultRow objectForKey:columnName];
[csvWriter writeField:value];
}
[csvWriter writeLine];
}
[csvWriter closeFile];
[csvWriter release];
[db close];
[db release];
That will write the contents of the tableName table out to a CSV file.
Simply do a SELECT on each table and print out the value of each column as required to a text file.