I have an application in which I want to fetch content from a database using a particular ID column and later display all that content in textfields on a button press. The snippet below shows how I fetch the content in an array.
//this is a function which i am created which will be called in button click event
-(NSArray*)getStudents
{
NSMutableArray *studentArray=[[NSMutableArray alloc]init];
sqlite3_stmt *statement = nil;
NSString *query=#"select * from UserInformation where UserId=?";
const char *sql = [query cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_prepare_v2(dbConnection, sql, -1, &statement, NULL) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
Student *newStudent=[[Student alloc]init];
newStudent.age=sqlite3_column_int(statement, 0);
newStudent.name=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
[studentArray addObject:newStudent];
}
}
return studentArray;
}
I have a problem adding this array to my textfields so that when I click on the button my textfields are loaded with the values from the database for a particular userid. I have written the above function in one of my controllers and my textfields are defined in another controller. How do I fill the above array in my textfields?
USe below as reference code ..
//Get all your student object from database
NSArray* myArray = [self getStudents ];
//Use mutable string to append all the data in single string.
NSMutableString* stringName = [NSMutableString stringWithString:#""];
//Traverse through the Student array
for(id arrayObj in myArray)
{
Student* student = (Student*)arrayObj;
[stringName appendString:student.name];
[stringName appendString:#" ";
}
//Now you have stringName variable holding all the student name and this is space separated string
myTextField.text = stringName;
Related
hello,
I am stucked at the last part of it, Please help me on it.
In this there are three views, first one, for list of books( in UITableView), second is chapters(in UITableView) and last one is for content,which is in text format (in UITextView).
Upto second view it is working very fine.Problem is, when i select any chapters in second view, text view in third view displays nothing.But in output it displays the sequence of numbers.
code to fetch data from database and display into UITextView.
NSMutableString *mStr = [NSMutableString stringWithFormat:#"select content from content where name = \"%#\" and chapterno = %#",chapName,chapNo];
const char *sql =(char *)[mStr UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_prepare(dbContent, sql, -1, &sqlStmt, NULL)!=SQLITE_OK)
{
NSLog(#"prob with prepare statement: %s",sqlite3_errmsg(dbContent));
}
else
{
while (sqlite3_step(sqlStmt)==SQLITE_ROW) {
len = sqlite3_column_bytes(sqlStmt, 0);
NSData *cData = [[NSData alloc]initWithBytes:sqlite3_column_blob(sqlStmt, 0) length:len];
NSString *nstr = [NSString stringWithUTF8String:[cData bytes]];
myTextView.text = nstr;
}
In above chapName is coming from first view and chapNo is selected row in second view.
content table looks like:
id bookid name chapterno content
1 1 abc 1 BLOB(size:4217)
2 1 abc 2 BLOB(size:3193)
3 1 abc 3 BLOB(size:3501)
O/p comes in a long sequence of numbers like this..
<0d0a3120 496e2074 68652062 6567696e 6e696e67 20476f64 20637265 61746564 20746865 20686561 76656e20 616e6420 74686520 65617274 682e0d0a...>
Here, text content i need to display in text view. What i'm missing here?
I think the problem is NSData to NSString conversion. If your Sqlite strings are not null-terminated converting with following line should help.
NSString* nStr = [[NSString alloc] initWithData:cData
encoding:NSUTF8StringEncoding];
NSMutableArray *ar=[[NSMutableArray alloc] init];
NSString *strQuery=[NSString stringWithFormat:#"select content from content where name = \"%#\" and chapterno = %#",chapName,chapNo];
const char *sql =[mStr UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_open([self.dbPath UTF8String], &database)==SQLITE_OK)
{
if(sqlite3_prepare_v2(database, query, -1, &compiledStmt, NULL)==SQLITE_OK){
while (sqlite3_step(sqlStmt)==SQLITE_ROW) {
len = sqlite3_column_bytes(sqlStmt, 0);
NSData *cData = [[NSData alloc]initWithBytes:sqlite3_column_blob(sqlStmt, 0) length:len];
NSString *nstr = [NSString stringWithUTF8String:[cData bytes]];
myTextView.text = nstr;
[ar addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 1) length:sqlite3_column_bytes(compiledStmt, 1)],#"data1",
[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStmt, 2)],#"data2",nil]];
}
else {
NSLog(#"Invalid query");
}
NSArray *arToReturn=([ar count]>;0)?[NSArray arrayWithArray:ar]:nil;
ar=nil;
return arToReturn;
}
Please implement following code and let me inform any problem and query genrated.
I have found a simplest alternate way for it.
Since, I am taking book name(from first table view) and chapter number(from second table view) from the database and passing it to detail view page.
Lets say here, my books names are maths, physics, geography..and chapters are in numerals (1,2,3...).Only thing is needed to keep the file name as
[booknamechpatername.txt]
#book name- Maths
chapter1-->> maths1.txt
chapter2-->> maths2.txt
...
#book name - Physics
chapter1 -->> physics12.txt
...
geography21.txt
...so on..
and drag it to iphone resource or any folder you want.
Now, Store that file into string and display into UITextView.
-(void)loadFile{
NSError *error;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *docDir = [dirPath objectAtIndex:0];
if (!docDir) {
NSLog(#"Doc dir not found");
}
NSString *str = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:#"%#%#",chapName,chapNo] ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:str encoding:NSUTF8StringEncoding error:&error];
myTextView.text = content;
}
and call it in viewDidLoad
[self loadFile];
Otherwise, this link https://github.com/jblough/bible-ios would help, if you want to go through database only.
I'm trying to display food by type to a user. The different types of foods are different elements in a table (fruits, veggies, meats, etc). I have all the foods in one database using sqlite. How can I query this database using objective c so that I can display only the correct type of food the user selected in the next view's table?
We use FMDB in two apps. It works fine.
-(NSArray *)GetAllFoods
{
NSMutableArray *filesArray = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
NSString *DBPath = [ClsCommonFunctions GetDatabasePath];
if ([self OpenDBWithPath:DBPath])
{
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "your query";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(filesDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// Need to get data from database...
NSSstring *foodObj = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]
[filesArray addObject:foodObj];
FileObj = nil;
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
sqlite3_close(filesDB);
}
return filesArray;
I was able to get a list of title of the books (tableview) and when i select the book i would like to push to the new view of the details of the books. Do i do it in titleView class 'didSelectRow' or in DetailView class 'viewWillAppear' and if so what exactly do I have to put to get the statement, 3 or contentInfo?
Database Class
(NSArray *) itemsByAuthorID:(NSInteger)authorID {
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query;
code....
query = [NSString stringWithFormat:#"select * from books where books.author_id = '%i'", authorID];
}
code...
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW) {
int itemID = sqlite3_column_int(statement, 0);
int authorID = sqlite3_column_int(statement, 1);
char *nameChars = (char *) sqlite3_column_text(statement, 2);
char *itemContent = (char *) sqlite3_column_text(statement, 3);
NSString *contentTitle = [[NSString alloc] initWithUTF8String:nameChars];
NSString *contentInfo = [[NSString alloc] initWithUTF8String:itemContent];
Item *info = [[Item alloc] initWithItemID:itemID authorID:authorID contentTitle:(NSString *)contentTitle contentInfo:contentInfo];
[retval addObject:info];
}
sqlite3_finalize(statement);
}
return retval;
You can create a private class for Book and retrive data from database for all books in array of Book.
Then after when didSelectRow is called only pass object of Book as parameter and show details in Detail view.
I want to load data to uipickerview from database.
this is my code
if (sqlite3_prepare_v2(UsersDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
int i=0;
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"select");
self.coun=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSLog(#"Coun = %#",coun);
self.animals=[coun componentsSeparatedByString:#":"];
NSLog(#"String value=%#",self.animals);
}
sqlite3_finalize(statement);
} else
{
NSLog(#"not select");
}
and button actions code is
- (IBAction)selectAnItem:(UIControl *)sender {
//Display the ActionSheetPicker
[ActionSheetPicker displayActionPickerWithView:sender data:self.animals selectedIndex:self.selectedIndex target:self action:#selector(itemWasSelected::) title:#"Select Country"];
}
but it run load only last value. Not all values loaded in UIpickerview. How to load all values from database using this code. Anyone pls help me. Thanks in advance.
You have to do like this,
NSArray *splitedString = [coun componentsSeparatedByString: #":"];
NSString *animalName;
if ([splitedString count]>0)
{
animalName=[splitedString objectAtIndex:0];
[self.animals addObject:animalName]; //here animals should be NSMutableArray
}
In the while loop, you have to collect all the self.coun values in an array. When you come out of the loop, having all the values, populate the picker.
NSMutableArray *countries = [[NSMutableArray alloc] init];
while (sqlite3_step(statement) == SQLITE_ROW){
self.coun=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSLog(#"Coun = %#",coun);
[countries addObject:coun];
//self.animals=[coun componentsSeparatedByString:#":"];
//NSLog(#"String value=%#",self.animals);
}
// Now you can use countries to populate in picker.
You have to implement data source and delegates for the UIPickerView.
Seems, you are storing countries in DB, reading from DB you are assigning in self.animals. Thats kind of not matching things with variable names. And why are your parsing by ":"?
hye all,
i have built a SQLite database and wanna to add into iphone app. already i have add it resource->add->x.sqlite and also add libsqlite3.0.dylib.framework but i don't know what is the showing code. I wanna to show the data in the db when user pressed button.
Can anyone help me to give an example on how the db can be view when button is press??
Here's some basic code to query the database:
-(NSArray*)names
{
NSString* query = [[NSString alloc] initWithString:#"SELECT name FROM sometablename;"];
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(yourDatabaseHandle, [query UTF8String], -1, &statement, nil);
[query release];
if (retval != SQLITE_OK)
{
sqlite3_close(yourDatabaseHandle);
NSAssert1(0, #"Error querying table: %i", (retval ^ SQLITE_ERROR));
return nil;
}
NSMutableArray* values = [[[NSMutableArray alloc] init] autorelease];
while (sqlite3_step(statement) == SQLITE_ROW)
{
const char* value = (const char*)sqlite3_column_text(statement, 0);
NSString* s = [[NSString alloc] initWithUTF8String:value];
[values addObject:s];
[s release];
}
sqlite3_finalize(statement);
return values;
}
You might want to present this in a table view. There are plenty of questions & answers here on Stack Overflow already to explain how to do that, as well as plenty of Apple sample code.