I have bar code reader project in iOS...Now when my reader reads value starting with '0',it is giving me error.
eg. value '098876567' - Error
'I have tried to trim.It is working.But I face another problem.
If it found value '000877667676'
Again value starts with '0' so it is giving me error.
I am using sqlite3.
I know it is very basic question but still having problem.Help me.
My code is :
NSString *str = ID.text; //here ID field indicates read data from bar code reader
int test = [str intValue];
NSLog(#"get clicked");
[self databaseOpen];
NSString *getData = [NSString stringWithFormat:#"SELECT FName,LName FROM Emp WHERE Emp_ID = %d",test];
NSLog(#"getdata %#",getData);
NSArray *array = [adddatabase executeQuery:getData];
NSLog(#"array %#" , array);
getData = [[array objectAtIndex:0]valueForKey:#"FName"];
NSLog(#"update query:%#",getData);
fname.text = [NSString stringWithFormat:#"%#",getData];
NSString *lastname = [[NSString alloc]init];
lastname = [[array objectAtIndex:0] valueForKey:#"LName"] ;
NSLog(#"LName: %#",lastname);
lname.text=[NSString stringWithFormat:#"%#",lastname];
[adddatabase close];
[adddatabase release];
Can you share some code? Also, explain what sqlite3 (a database) has to do whit the barcode reader. Is the error from the barcode reader or from sqlite3?
I can imagine the error occuring when you read a barcode with leading zeroes, and try to store that in an integer field in your sqlite database. When storing a barcode you might want to use a String (TEXT) instead.
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 am inserting HTML content (which has special characters like bullets, etc) into the SQLite database.
When I try to get the content on a view, it does not show the special characters correctly. It shows me junk text.
How can I ensure that whatever text I insert in database, it is displayed correctly on the view.
Thanks!
My Insertion code:
// This query method implementation is in different file
- (NSArray *)executeQuery:(NSString *)sql arguments:(NSArray *)args {
sqlite3_stmt *sqlStmt;
if (![self prepareSql:sql inStatament:(&sqlStmt)])
return nil;
int i = 0;
int queryParamCount = sqlite3_bind_parameter_count(sqlStmt);
while (i++ < queryParamCount)
[self bindObject:[args objectAtIndex:(i - 1)] toColumn:i inStatament:sqlStmt];
NSMutableArray *arrayList = [[NSMutableArray alloc] init]; // By Devang
int columnCount = sqlite3_column_count(sqlStmt);
while ([self hasData:sqlStmt]) {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (i = 0; i < columnCount; ++i) {
id columnName = [self columnName:sqlStmt columnIndex:i];
id columnData = [self columnData:sqlStmt columnIndex:i];
[dictionary setObject:columnData forKey:columnName];
}
[arrayList addObject:dictionary];
//[arrayList addObject:[dictionary autorelease]];
}
sqlite3_finalize(sqlStmt);
return arrayList;
}
// now call this method by make object for this file
NSString *inserQuery =[NSString stringWithFormat:#"insert into feedtest (title,summary,image,id) values ('%#','%#','%#',%d)",cell.textLabel.text,source,returnURL,indexPath.row];
NSLog(#"query - %#",inserQuery);
[database executeQuery:inserQuery];
// Retrive the data
NSString *sd=[NSString stringWithFormat:#"Select title,summary from feedtest"];
NSMutableArray *p=[[NSMutableArray alloc]init];
p=[[database executeQuery:sd ] mutableCopy];
[database close];
NSString *titleHTML = [[p objectAtIndex:i]valueForKey:#"title"];
NSString *postHTML =[[p objectAtIndex:i]valueForKey:#"summary"];
NSLog(#"%#",titleHTML);
NSLog(#"%#",postHTML);
You can check your local database using FireFox plugin SQLite. But, sometimes on retrieving we faced strange problem like what is present in the storage not coming properly and sometime, there is crash. So my suggestion is what you should check encoding scheme(normally, it's not matter more) and while getting data use this:
[NSString stringWithFormat:#"%s",(const char*)sqlite3_column_text(statement, 4)] ;
instead of:
[NSString stringWithUTF8String:(const char*)sqlite3_column_text(statement, 4)];
Hope, this is what you're looking for. Any concern get back to me. :)
When I launch an app, I need to retrieve all contacts from Address Book & store it in array to display it in table view. I wrote this code in viewDidAppear method. While contacts are retrieving from Address Book , I am showing activity indicator. I have around 1100 contacts in my address book. For this it took 14 seconds to retrieve data & store it in array. Its not acceptable time. So I need to optimize this & reduce time to max 2 to 3 seconds.
I need all contacts because when my app launches , I need to search for contacts so I need all the data available in my array.
How can I reduce this timing ? If you need more information just let me know.
Any kind of help is highly appreciated. Thanks.
UPDATE 1 : My code
- (NSMutableArray*)getAddressBookData {
self.tempArray = [[NSMutableArray alloc]init];
addressBook = ABAddressBookCreate();
APP_DELGATE.people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
peopleCount = [APP_DELGATE.people count];
for (int i=0; i<peopleCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
NSLog(#"record id is %#",recordId);
// Get fname, lname, company
NSString *fnm = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty) ;
NSString *lnm = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty) ;
NSString *comp = (NSString*)ABRecordCopyValue(record,kABPersonOrganizationProperty);
// Get Ph no
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(record, kABPersonPhoneProperty);
NSArray* phoneNumbers = [self getPhoneNoWithoutSymbols:(NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty)];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
NSLog(#"strPhoneNos => %#",strPhoneNos);
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
NSLog(#"strEmails => %#",strEmails);
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
NSLog(#"strURLs => %#",strURLs);
// Get Address
ABMultiValueRef address=ABRecordCopyValue(record, kABPersonAddressProperty);
CFDictionaryRef dic=nil;
NSMutableArray *addressArray = [[NSMutableArray alloc]init];
for (int index=0; index<ABMultiValueGetCount(address); index++) {
dic=ABMultiValueCopyValueAtIndex(address, index);
NSString* labelName=(NSString*)ABMultiValueCopyLabelAtIndex(address, index);
if (labelName) {
NSString *street =(NSString*) CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString *city= (NSString*)CFDictionaryGetValue(dic, kABPersonAddressCityKey) ;
NSString *state= CFDictionaryGetValue(dic, kABPersonAddressStateKey);
NSString *country=CFDictionaryGetValue(dic, kABPersonAddressCountryKey);
NSString *zipcode=CFDictionaryGetValue(dic, kABPersonAddressZIPKey);
NSString *addressDetails=#"";
if (street) {
addressDetails=[NSString stringWithFormat:#"%# ",street];
}
if (city) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,city];
}
if (state) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,state];
}
if (country) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,country];
}
if (zipcode) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,zipcode];
}
[addressArray addObject:addressDetails];
}
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
NSLog(#"strAddress => %#",strAddress);
// Get Notes
NSString *noteString=(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty);
// Get Birthdate
NSDate *birthDate=(NSDate*)ABRecordCopyValue(record, kABPersonBirthdayProperty) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM dd yyyy"];
NSString *birthdateString = [formatter stringFromDate:birthDate];
[formatter release];
// Get user image
UIImage *image = nil;
if( ABPersonHasImageData( record ) ) {
NSData *imageData = (NSData*)ABPersonCopyImageData(record);
image = [UIImage imageWithData:imageData];
[imageData release];
}
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
[user release];
}
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
return tempArray;
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
self.phNoArray = [[NSMutableArray alloc]init];
for (NSString *str in array) {
[self.phNoArray addObject:[self getPhNo:str]];
}
return self.phNoArray;
}
-(NSString*)getPhNo:(NSString*)str {
NSString *str0 = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *str1 = [str0 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *str3 = [str2 stringByReplacingOccurrencesOfString:#"-" withString:#""];
return str3;
}
-(NSString*)getStringRepresentaionFromArray:(NSArray*)array {
return [array componentsJoinedByString:DELIMITER_SYMBOL];
}
Firstly, try some general approaches to reduce time by using more optimized code and less repetition of code and also through less use of loops or may be only iterate loops only till the data is obtained. Also you can check whether your code is properly distributed as far as the Time Profiling is concerned.
Secondly, we feel that time required is more because user is shown an Activity Indicator till 14 seconds. If you don't show it and don't block the User Interface till data is getting copied into your array, then user may feel that it is more smooth So here is how you can do that:
You can use NSThread to allow the application to launch while you retrieve all your data from the AddressBook and Store it in your array.
You can use
[NSThread detachNewThreadSelector:#selector(fetchAddressContacts:) withObject:nil];
For more information you can refer to detachNewThreadSelector: from NSThread
So basically in AppDelegate you need to code as following in AppDelegate.m
-(void)applicationDidFinishLaunching:(UIApplication *)application {
[NSThread detachNewThreadSelector:#selector(fetchAddressContacts) withObject:nil];
}
-(void)fetchAddressContacts {
//Do your stuff to copy your contacts from address book to array
// Once you finish this task you can trigger an NSNotification which could be caught on some other viewController or implement a delegate to transfer data to a viewController and proper actions can be executed once the data is loaded.
}
Let me know if you need more help.
Hope this helps you.
Perform your contacts retrieval method diagnostics and identify what calls are causing the bottleneck here.
Share your code and describe the bottlenecks
Any operation taking serious amount of time should be performed in a thread. In this case, I'd gather the data on first startup only and store them internally. You can refresh the primary data anytime later on demand (refresh button?) otherwise work with the internally stored "clone" of the contacts rather than calling any time-consuming operation on every app's start.
BTW: Be careful about the address book contacts these days :-)
When your app first install fetch all the contacts and save in coredate/plist file when next time app opens then show the contacts from the storage which is very fast as compare to fetching contacts from iPhone database. Now the problem how to update contacts which newly added, so for every contact there is property called "kABPersonModificationDateProperty" and "kABPersonCreationDateProperty" ,use this to find only updated contacts and add in the storage. Hope this helps.
I am working with Sqlite Database.
In my database
I have some filed Like, Invoice,Name,Date
My Invoiceno datatype is INTEGER,
In Select query Got output like this.
Query:(
{
InvoiceNo = 1;
Name : ABC
Date = "2012-04-16 00:00:00";
}
)
But when try to Get that Invoice no to string it's given Diff. Value.
Code for getting invoice from array to String:
NSString *str = [NSString stringWithFormat:#"%i",[[Query objectAtIndex:indexPath.row] valueForKey:#"InvoiceNo"]];
NSLog(#"str:%#",str);
Here, My invoice no is 1, & It's give me a value "2387056"
Please, Help me..How can i solve this problem?
NSString *str = [NSString stringWithFormat:#"%i",[[Query objectAtIndex:indexPath.row] valueForKey:#"InvoiceNo"]];
NSLog(#"str:%#",str);
you have to replace above lines with below lines
NSString *str = [NSString stringWithFormat:#"%i",[[[Query objectAtIndex:indexPath.row] valueForKey:#"InvoiceNo"] intValue]];
NSLog(#"str:%#",str);
Convert NSString to int
NSString *values = #"1";
int yourValue = [values intValue];
NSLog(#"Int Value : %d",yourValue);
i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me
You can join the elements of an array together with the NSString componentsJoinedByString class method:
NSString myString = [myNSArray componentsJoinedByString:#"x"];
where x is the characters you'd like to appear between each array element.
Edited to add
So in your newly-added code if these are the label values:
lbl = #"zero"
lbl1 = #"one"
lbl2 = #"two"
and you want to join them together with a space character then if you did this:
NSString *temp = [labelArray componentsJoinedByString:#" "];
NSLog(#"temp = %#", temp);
then this is what would be logged:
zero one two
Edited to further add
If you are instead trying to join the label values together to make xml elements then you might do something like this:
NSString *joinedElements = [labelArray componentsJoinedByString:#"</label><label>"];
NSString *temp = [NSString stringWithFormat:#"<label>%#</label>", joinedElements];
NSLog(#"temp = %#", temp);
then this is what would be logged:
<label>zero</label><label>one</label><label>two</label>
may be this is usefull to you.
NSString *str;
str = [arrayName objectAtIndex:i(Index NO)];
OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.
Best of Luck.
Most objects have a -description method which returns a string representation of the object:
- (NSString *)description;
For example:
NSArray *array = [NSArray arrayWithObjects:#"The", #"quick", #"brown", #"fox", nil];
NSLog(#"%#", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string
It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?
In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:
NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
[string appendString:[array objectAtIndex:0]];
[string appendFormat:#"blah some filler text %#", [array objectAtIndex:1]];
[string appendString:[array objectAtIndex:2]];
}