アプリでSQLiteを使用して、SQLiteで作成したテーブルのデータを挿入して表示したいのですが、SQLiteは初めてなので、グーグルでリンクhttp://www.techotopia.com/index.php/に出くわしました。このようなデータを挿入して表示するのに役立つAn_Example_SQLite_based_iPhone_Application(URLをサンプルURLに変更しました)
#import "MasterViewController.h"
#import "DetailViewController.h"
@interface MasterViewController ()
{
NSMutableArray *_objects;
}
@end
@implementation MasterViewController
@synthesize detailViewController = _detailViewController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
}
return self;
}
- (void)viewDidLoad
{
NSString *docsDir;
NSArray *dirPaths;
alertFlg=1;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"Failed to create table") ;
}
sqlite3_close(contactDB);
}
else
{
NSLog(@"Failed to open/create database") ;
}
}
[super viewDidLoad];
namearry = [[NSMutableArray alloc] init];
costarry = [[NSMutableArray alloc] init];
discrarry = [[NSMutableArray alloc] init];
[self parseXMLFileAtURL:@"http://api.androidhive.info/pizza/?format=xml"];
[self saveData];
[self displayData];
}
- (void)saveData
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
int i;
for ( i=0; i<[namearry count]; i++) {
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (name) VALUES ( \"%@\")", [namearry objectAtIndex:i]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Contact added");
} else {
NSLog(@"Failed to add contact") ;
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
-(void)displayData
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM contacts "];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *nameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
[namearry addObject:nameField];
NSLog(@"Match found");
}
sqlite3_finalize(statement);
}
}
sqlite3_close(contactDB);
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [namearry 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 setSelectionStyle:UITableViewCellSelectionStyleNone];
}
cell.textLabel.text = [namearry objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return NO;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/* if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
}
NSDate *object = [_objects objectAtIndex:indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];*/
}
/*------------------------------------Parser's Code-----------------------------------------*/
-(void) parseXMLFileAtURL:(NSString *)URL
{
// NSURL *url1=@"http://api.androidhive.info/pizza/?format=xml";
feedParser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:URL]];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[feedParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[feedParser setShouldProcessNamespaces:NO];
[feedParser setShouldReportNamespacePrefixes:NO];
[feedParser setShouldResolveExternalEntities:NO];
[feedParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
if (alertFlg==1)
{
alertFlg=0;
NSString * errorString = [NSString stringWithFormat:@"Network Error", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Please check the internet connection" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
// [errorAlert release];
}
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
currentElement =[elementName copy];
if ([elementName isEqualToString:@"name"])
{
//namearry=[[NSMutableArray alloc] init];
nameStrng =[[NSMutableString alloc] init];
}
else if ([elementName isEqualToString:@"cost"])
{
//costarry=[[NSMutableArray alloc] init];
costStrng =[[NSMutableString alloc] init];
}
else if ([elementName isEqualToString:@"description"])
{
//discrarry=[[NSMutableArray alloc] init];
descpStrng =[[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"name"])
{
nameStr=nameStrng;
// NSLog(@"namestr:=%@",nameStrng);
[namearry addObject:nameStrng];
}
else if ([elementName isEqualToString:@"cost"])
{
costStr=costStrng;
[costarry addObject:costStrng];
}
else if ([elementName isEqualToString:@"description"])
{
descrpStr=descpStrng;
[discrarry addObject:descpStrng];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:@"name"])
{
// NSLog(@"appending string for name attribute:=%@",string);
[nameStrng appendString:string];
}
else if ([currentElement isEqualToString:@"cost"])
{
[costStrng appendString:string];
}
else if ([currentElement isEqualToString:@"description"])
{
[descpStrng appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
}
/*----------------------End Of The Parser's Code AND Start Of the TableView'S Code---------------------------*/
@end
ここで必要なのはviewDidLoadメソッドで、テーブルが存在しない場合はテーブルを作成します。「create」テーブルコマンドを使用したので、テーブルの作成を選択した場合のように、属性を変更して動的にテーブルの作成コマンドを作成します。名前のみで、名前と番号のみでテーブルを作成することを選択した場合、またはこの2つ以上の属性でテーブルを作成することを選択した場合、コマンドはそれに応じて変更する必要があります。