Display array value to view - iphone

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.

Related

how to create table in sqlite3 with a list of column name in NSMutableArray

I need to create a sqlite3 table with column dynamically , actually the column names stored in NSMutableArry , i want to create a table from NSMutableArrya Values.
Try this :
- (void)viewDidLoad
{
NSString *idField = #"ID INTEGER PRIMARY KEY AUTOINCREMENT";
NSString *nameField = #"NAME TEXT";
NSString *ageField = #"AGE INTEGER";
// Make the field array using different attributes in different cases
NSArray *fieldArray = [NSArray arrayWithObjects:idField,nameField,ageField, nil];
[self createTable:fieldArray];
}
- (void)createTable:(NSArray *)fieldArray
{
// Put all the code for create table and just change the query as given below
NSString *queryString = [NSString stringWithFormat:#"CREATE TABLE IF NOT EXISTS CONTACTS (%#)",[fieldArray componentsJoinedByString:#","]];
const char *sql_stmt = [queryString UTF8String];
}
You can do it in such a way, just parse the data of you array the right way
-(BOOL)createNewTable
{
NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[array objectAtIndex:0];
filePath =[filePath stringByAppendingPathComponent:#"yourdatabase.db"];
NSFileManager *manager=[NSFileManager defaultManager];
BOOL success = NO;
if ([manager fileExistsAtPath:filePath])
{
success =YES;
}
if (!success)
{
NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"yourdatabase.db"];
success =[manager copyItemAtPath:path2 toPath:filePath error:nil];
}
createStmt = nil;
NSString *tableName=#"SecondTable";
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
if (createStmt == nil) {
NSString *query=[NSString stringWithFormat:#"create table %#(rollNo integer, name text)",tableName];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) {
return NO;
}
sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
return YES;
}
}
For creating table dynamically use the create query like:
NSString *query=[NSString stringWithFormat:#"create table '%#'('%#' integer, '%#' text)",yourTableName,[yourArray objectAtIndex:0],[yourArray objectAtIndex:1]];

How to print all data in given table?

i am iPhone application developer, and now we understood the concept of database.
i want to print all data from database. but i m not getting how can i print all data. here is i pest some code. please give me correct direction to print all data..
for example in sql we print all data as "select * from contact5;" we fire this string. can we done in iPhone coding?
-(IBAction)PrintData:(id)sender
{
NSLog(#"Button Pressed");
sqlite3_stmt *statement1;
NSString *querySQL=#"SELECT * FROM CONTACT5";
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement1, NULL);
while (sqlite3_step(statement1) == SQLITE_ROW)
{
NSLog(#"Enter in the denger zone");
NSString *idField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 0)];
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 2)];
NSString *NameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 1)];
NSString *phoneFiels = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 3)];
NSLog(#"ID is=%#",idField);
NSLog(#"Name is=%#",NameField);
NSLog(#"Address is=%#",addressField);
NSLog(#"Phone No. is=%#",phoneFiels);
[idField release];
[NameField release];
[phoneFiels release];
[addressField release];
}
sqlite3_finalize(statement1);
sqlite3_close(contactDB);
}
thanks in advance.
We are sharing Some come which is using NSMutableDictionary to store your data and you can easily use that code to print your data,where do you want
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "Select * from CalculateTime";
sqlite3_stmt *insertStmt;
if(sqlite3_prepare_v2(database, sql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0,#"Error: Failed to prepare statement with message '%s'.",sqlite3_errmsg(database));
arrayCountry = nil;
arrayCountry = [[NSMutableArray alloc]init];
arrayCity = nil;
arrayCity = [[NSMutableArray alloc]init];
arrayFlag = nil;
arrayFlag = [[NSMutableArray alloc]init];
arrayZone = nil;
arrayZone = [[NSMutableArray alloc]init];
NSString *str2;
while(sqlite3_step(insertStmt)==SQLITE_ROW)
{
char *row;
row = (char*)sqlite3_column_text(insertStmt, 0);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayCountry addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 1);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayCity addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 2);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayFlag addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 3);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayZone addObject:str2];
}
}
}
Access these dictionary data to print anywhere..

How to return sqlite3_stmt to called object

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 to list the resultset based on order using query

//===================================================================================
- ( NSMutableDictionary * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableDictionary *aTierTwoTemplateData = [[NSMutableDictionary alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData setObject:aId forKey:aValue];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return aTierTwoTemplateData;
}
I am able to get the resultset when i assign this to array , but it loses the order in which , i have stored in the dictionery.
Actually , i have stored the result set based on the position field .
When i assign the resultset into array , the order gets changed.
Please let me know how can i handle this situation.
This is not a duplicate, as i have a coulmn in the db as "position"
If you want to store data as key-value pair and maintain the order, then you can use combination of NSArray and NSDictionary.The same code will be:
//===================================================================================
- ( NSArray * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableArray *aTierTwoTemplateData = [[NSMutableArray alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData addObject:[NSDictionary dictionaryWithObject:aId forKey:aValue]];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return [aTierTwoTemplateData autorelease];
}
In this way you'll be having an array of dictionaries, where your values will be stored in the dictionary and the order of the data also will be preserved.

making map coordinates(lan,& long)storing in sqlite database

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.