String printing incorrectly in table view after JSON parsing - ios

I one of my apps, i parse some data from local host and print it in a table view. To get the data, the user first logs in using an alert view. The user id entered is then used to fetch the data which i parse using JSON.
There is definitely a very simple solution to this question but I can't seem to be able to fix it. The problem is that when I print the data the string comes in this format:
( "string" )
But I want it so that it just says : string
in the table view. Here is my parsing method:
- (void)updateMyBooks
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Fetch data on a background thread:
NSString *authFormatString =
#"http://localhost:8888/Jineel_lib/bookBorrowed.php?uid=%#";
NSString *string = [[NSString alloc]initWithFormat:#"%#",UserID];
NSString *urlString = [NSString stringWithFormat:authFormatString, string];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"uel is %#", url);
NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
response1 = [contents JSONValue];
if (contents) {
// ... Parse JSON response and add objects to newBooksBorrowed ...
BookName = [[NSString alloc]init];
DateBorrowed = [[NSString alloc]init];
BookID = [[NSString alloc]init];
BookExtended = [[NSString alloc]init];
BookReturned = [[NSString alloc]init];
BookName = [response1 valueForKey:#"BookName"];
BookID = [response1 valueForKey:#"BookID"];
DateBorrowed = [response1 valueForKey:#"DateBorrowed"];
BookExtended = [response1 valueForKey:#"Extended"];
BookReturned = [response1 valueForKey:#"Returned"];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update data source array and reload table view.
[BooksBorrowed addObject:BookName];
NSLog(#"bookBorrowed array = %#",BooksBorrowed);
[self.tableView reloadData];
});
}
});
}
This is how I print it in the table view:
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
NSLog(#"string is %#",string);
cell.textLabel.text = string;
When I use log during the parsing process, it comes out as ( "string" ) so the problem is somewhere in the parsing, at least thats what I think.

If
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
returns something like "( string )" then the most probably reason is that
[BooksBorrowed objectAtIndex:indexPath.row]
is not a string, but an array containing a string. In that case,
NSString *string = [[BooksBorrowed objectAtIndex:indexPath.row] objectAtIndex:0];
should be the solution.

NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
string = [string stringByReplacingOccurrencesOfString:#"(" withString:#""];
string = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
string = [string stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"string is %#",string);
cell.textLabel.text = string;
EDIT:
Above code is used if it's showing text in that format in your label.
If you see that in NSlog then it's NSString inside NSArray.
You need to fetch that string first from array and then display, use code line suggested by #Martin R for that.
NSString *string = [[BooksBorrowed objectAtIndex:indexPath.row] objectAtIndex:0];

Related

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

JSon returning Integer values into array

I have successfully realized the interaction with json and returning successfully all the required entities. But i have one field that will be returned as an integer. I want to do the simplest thing and access an element of the array , which is an integer , and compare it with another integer. No matter what i do it doesn't work out : this is my code so far :
NSString *strURL2 = [NSString stringWithFormat:#"MyURL"];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL2]];
NSString *strResult2 = [[NSString alloc] initWithData:dataURL2 encoding:NSUTF8StringEncoding];
NSDictionary *json2 = [strResult2 JSONValue];
userExists = [json2 valueForKeyPath:#"userId"];
Where userExists is an array, and the values stored in it are NOT strings , they are Int.
Any help?!
NSString *strURL2 = [NSString stringWithFormat:#"MyURL"];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL2]];
NSString *strResult2 = [[NSString alloc] initWithData:dataURL2 encoding:NSUTF8StringEncoding];
NSDictionary *json2 = [strResult2 JSONValue];
Now if you want to add the integer to the array (has to be NSMutableArray of course) userExists, you do it like so:
[userExists addObject:[[json2 objectForKey:#"userId"] integerValue]]
If your intention was to compare the returned integer with an integer in the array at index i then you do it like so:
if([userExists objectAtIndex:i] == [[json2 objectForKey:#"userId"] integerValue]) {
....
}

iOS parsing img tag found in JSON

I am trying to parse the file location from the following so that image can be displayed. How do I do it?
[
{
"title":"testing barcode display",
"body":"lets see if it renders \r\n\r\n",
"author":"1",
"created":"1373490143",
"nid":"5",
"Barcode":"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />"
}
]
I have a table view which displays the title tag. I need to display the entire content in the detail view. I can do everything except the Barcode tag. Please advise.
If it should be done, parse the xml
NSString *xmlString = #"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />";
GDataXMLElement *xmlElement = [[GDataXMLElement alloc]initWithXMLString:xmlString error:nil];
NSArray *attributes = [xmlElement attributes];
[attributes enumerateObjectsUsingBlock:^(GDataXMLNode * node, NSUInteger idx, BOOL *stop) {
NSLog(#"%# : %#",node.name,node.stringValue);
}];
OR
NSString *class = [[xmlElement attributeForName:#"class"] stringValue];
NSString *typeOf = [[xmlElement attributeForName:#"typeof"] stringValue];
NSString *src = [[xmlElement attributeForName:#"src"] stringValue];
NSString *alt = [[xmlElement attributeForName:#"alt"] stringValue];
NSString *title = [[xmlElement attributeForName:#"title"] stringValue];
Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
You have to convert json string in nsdictionary, so try this
SBJSON *json = [[SBJSON new] autorelease];
NSError *error;
NSDictionary *dict = [json objectWithString:YOUR_JSON_STRING error:&error];
add user this dictionary to display details in tableView

When I press register button my app has crashed but data insert successfully in database

Here is my response code.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
NSLog(#"Success");
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"Response"];
for(NSDictionary *countname in wholeJsonArray)
{
NSString *countryName = [countname objectForKey:#"country_name"];
if(countryName)
[countryArray addObject:countryName];
NSString *stateName=[countname objectForKey:#"state_name"];
if(stateName)
[stateArray addObject:stateName];
}
above code is retrieve to country name and statename .
When i debug my code after press button apps should crashed in NSString *countryName = [countname objectForKey:#"country_name"]; line cursor point.
NSMutableArray *wholeJsonArray does not contain NSMutableDictionary ; It contains NSString instead. Please review your array contents.

A better approach to coding the a string value test for a NSDictionary object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How could I write this if else code checking in a better way?
My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a NSDictionary object and then depending upon the value prefix a UILabel with $, £, ¥ currency symbols.
Here's my code (I've just shown 2 examples below, I have more currencies and the code is very long):
if ([[item objectForKey:#"currency"] isEqualToString:#"EUR"]) {
NSString *priceConvertToStr = [NSString stringWithFormat:#"€%#", [[item objectForKey:#"price"]stringValue]];
NSString *priceStringFix = [priceConvertToStr
stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
priceLabelText.text = priceStringFix;
[imgView2 addSubview:priceLabelText];
}
if ([[item objectForKey:#"currency"] isEqualToString:#"GBP"]) {
NSString *priceConvertToStr = [NSString stringWithFormat:#"€%#", [[item objectForKey:#"price"]stringValue]];
NSString *priceStringFix = [priceConvertToStr
stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
priceLabelText.text = priceStringFix;
[imgView2 addSubview:priceLabelText];
}
if ([[item objectForKey:#"currency"] isEqualToString:#"USD"]) {
NSString *priceConvertToStr = [NSString stringWithFormat:#"$%#", [[item objectForKey:#"price"]stringValue]];
NSString *priceStringFix = [priceConvertToStr
stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
priceLabelText.text = priceStringFix;
[imgView2 addSubview:priceLabelText];
}
thanks so much for any help.
You can refactor your code to this (possible because essentially 80% of the code within the if statements are identical):
NSDictionary *currDict = #{
#"EUR": #"€",
#"GBP": #"₤",
#"USD": #"$"
};
NSString *currName = [item objectForKey:#"currency"];
NSString *currency = [currDict objectForKey:currName];
NSString *priceConvertToStr = [NSString stringWithFormat:#"%#%#",
currency,
[[item objectForKey:#"price"] stringValue]
];
NSString *priceStringFix = [priceConvertToStr stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
priceLabelText.text = priceStringFix;
[imgView2 addSubview:priceLabelText];

Resources