I can't trap FMDB empty resultset - iphone

I am having trouble trapping an empty result set from FMDB.
The code is below. I am getting NSLog's from the database opening and closing and NSLog "1" but none of the ones in the If statement!
If I have data in the database its fine, but I want to trap and edit result if the database is empty.
[self openDatabase];
NSNumberFormatter *nfcurrency = [[NSNumberFormatter alloc]init];
[nfcurrency setNumberStyle:NSNumberFormatterCurrencyStyle];
[nfcurrency setLocale:[NSLocale currentLocale]];
FMResultSet *result = [[self getDatabase]executeQuery:#"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
//FMResultSet *result = [[self getDatabase]executeQuery:#"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
NSLog(#"1");
if (result == NULL) {
NSLog(#"Last BFNeeded Result = nil");
} else {
while ([result next]) {
NSLog(#"HERE");
NSString *lastBFNeeded = [nfcurrency stringFromNumber:[NSNumber numberWithDouble:[result doubleForColumn:#"BFNeeded"]]];
NSLog(#"lastBFNeeded=%#",lastBFNeeded);
}
}
NSLog(#"ClosingDB");
[self closeDatabase];
Continuing after getting first reply:
I can't get hasAnotherRow to work as expected.
I have this code:
FMResultSet *result = [[self getDatabase]executeQuery:#"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 0,1;"];
if (result == nil) {
NSLog(#"Last BFNeeded Result = nil");
}
else {
NSLog(#"has results1: %#", [result hasAnotherRow] ? #"YES" : #"NO");
while ([result next]) {
NSLog(#"has results2: %#", [result hasAnotherRow] ? #"YES" : #"NO");
}
}
With a database that returns a result, I get result1 NO, result2 YES so I assume the hasAnotherRow must go inside the while ([result next]) loop.
However with an empty database, I get result1 NO and it doesn't even get to result2!

the "result" will never be nil for a query that produces 0 rows.
also, you shouldn't compare object pointers to NULL -- compare to nil. See this question: NULL vs nil in Objective-C
try this:
FMResultSet *result = [[self getDatabase]executeQuery:#"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
NSLog ( #"has results: %#", [result hasAnotherRow] ? #"YES" : #"NO" );

NSInteger count;
query=[NSString stringWithFormat:#"select Count(*) from %# where name = 'brandon' ",dbName];
results = [database executeQuery:query ];
while([results next]) {
count = [results intForColumnIndex:0];
NSLog(#"count:%d",count);
}
will set count equal to zero if there is no entry

Related

String not getting split giving unrecognized selector error

Trying to split the string in to array, but it is giving error "[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x11741b20'". The string contains the value, that comes from first index of array then the string needs to be split and store in array.
This is array value.
mcommarr:(
":comment",
":comment",
":comment"
NSString *strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
NSArray *arr2 = [str componentsSeparatedByString:#","];
Here is the complete method in which i am using this.
-(void)loadData:(int)indexVal;
{
indexVal=serialIndexVal;
serialIndexVal++;
NSLog(#"arrLike:%d", [self.mArrLike count]);
NSLog(#"arrPid:%d", [self.mArrPid count]);
status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
[self.activityIndicator startAnimating];
#try
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *status = [NSString stringWithFormat:#"get"];
[self.mButtonsStatusDict setObject:status forKey:#"status"];
[self.mButtonsPidDict setObject:[self.mArrPid objectAtIndex:indexVal] forKey:#"pid"];
self.mButtonsCommentsDict = [MyEventApi showComments:self.mButtonsPidDict];
self.mButtonsDict = [MyEventApi likeDislike:self.mButtonsUidDict post:self.mButtonsPidDict postStatus:self.mButtonsStatusDict];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.activityIndicator stopAnimating];
NSLog(#"buttons data dict:%#", self.mButtonsDict);
if([self.mButtonsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mArrLike addObject: #"0"];
[self.mArrDislike addObject: #"0"];
}else{
[self.mArrLike addObject: [self.mButtonsDict valueForKey:#"like"]];
[self.mArrDislike addObject: [self.mButtonsDict valueForKey:#"dislike"]];
}
if([self.mButtonsCommentsDict count] == 0)
{
NSLog(#"server problem no response");
[self.mCommArrTot addObject: #"0"];
}
else{
self.dictComm = [self.mButtonsCommentsDict valueForKey:#"comments"];
[self.mCommArr addObject:[self.dictComm valueForKey:#"comment"]];
NSLog(#"count:%d",[self.mCommArr count]);
// NSString *strTot = [NSString stringWithFormat:#"%d",tot];
// [self.mCommArrTot addObject:strTot];
NSLog(#"dictcomm:%#", self.dictComm );
NSLog(#"mcommarr:%#", [self.mCommArr objectAtIndex:indexVal]);
strr = [[NSString alloc]init];
strr = [self.mCommArr objectAtIndex:indexVal];
//NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
// NSArray *arr1 = [self string:strr];
// NSArray *splitArray=[self.mCommArr[0] componentsSeparatedByString:#","];
//[strr componentsSeparatedByString:#","];
// NSLog(#"arrSep:%#", arr1);
//int count = [arr1 count];
//NSLog(#"arrcount:%d", count);
// NSString *strTot = [NSString stringWithFormat:#"%d",count];
// [self.mCommArrTot addObject:strTot];
//NSLog(#"mcommarrtot:%#", [self.mCommArrTot objectAtIndex:indexVal]);
}
// NSLog(#"arrLike:%#", [self.mArrLike objectAtIndex:indexVal]);
// NSLog(#"arrDisLike:%#", [self.mArrLike objectAtIndex:indexVal]);
[self.mPublicFriendTable reloadData];
});
});
}
#catch (NSException *exception) {
NSLog(#"main: Caught %#: %#", [exception name], [exception reason]);
}
#finally {
}
}
It get killed when try to split. Why so, i am not getting. If anyone has faced such situation please guide what is wrong her.
You can split the string into an NSArray like below...
NSString *yourString = #"comment,comment,comment";
NSArray *strArray = [yourString componentsSeparatedByString:#","];
NSLog(#"\n\n Array is ==>> %#",strArray);
"[__NSArrayI componentsSeparatedByString:]:
Your error says you tried to send the above method to NSArray, which doesn't has.
As you want to split the array at index 0. you should probably do as :
NSArray *splitArray=[yourArray[0] componentsSeparatedByString:#","];
Here yourArray is the array that you get from Server.
NSString *strr = [[NSString stringWithFormat:#"%#", [self.mCommArr objectAtIndex:indexVal]];
NSArray *arr2 = [strr componentsSeparatedByString:#","];
I think you are passing str right now, which can be an array (as your error points out).
Let me know the results.

How to Show a String instead of address in textView

i am trying to get a random string from database i have tried to convert array in a String but when i click button i only get address can anyone help me how to show that string in my button action?
- (IBAction)randBtn:(id)sender {
SendQuoteVC *svc= [[SendQuoteVC alloc]initWithNibName:#"SendQuoteVC" bundle:nil];
DBHandler *db =[[DBHandler alloc]init];
arr =[db randomQuote];
NSMutableString * show = [[NSMutableString alloc] init];
for (NSObject * obj in arr)
{
[show appendString:[obj description]];
}
NSLog(#"The concatenated string is %#", show);
NSString *rs =[NSString stringWithFormat:#" %#",show];
svc.quote=rs;
[self.navigationController pushViewController:svc animated:YES];
}
and my log message is
2012-12-26 17:02:46.062 SendQuote[2281:c07] QUERY: SELECT * FROM quotes ORDER BY RANDOM() LIMIT 1
2012-12-26 17:02:46.097 SendQuote[2281:c07] txtQuote is (
"<quoteDC: 0xa9a94c0>"
)
2012-12-26 17:02:46.100 SendQuote[2281:c07] rand is (
"<quoteDC: 0xa9a94c0>"
)
i have changed my user entity class to quoteDC class and my Db function is
-(NSMutableArray *)randomQuote{
NSMutableArray *dataArray =[[NSMutableArray alloc]init];
NSString * sqlStr=[NSString stringWithFormat:#"SELECT * FROM quotes ORDER BY RANDOM() LIMIT 1"];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement: sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
quoteDC *worddc = [[quoteDC alloc] init];
NSString *userid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement, 0)];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement, 1)];
worddc.quote_id=[userid integerValue];
worddc.quotes=name;
[dataArray addObject:worddc];
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
}
return dataArray;
}
the [db randomQuote] method returns an array of users not strings, you can typecast it to user object than get your desired property out of it!
It seems like your array is an array of objects of some user class rather than array of strings.
Hence the call to
[obj description]
is returning an object instead of a string.
You would need to override the description method in your user class, and return string.
This code makes the issue:
for (NSObject * obj in arr)
{
[show appendString:[obj description]];
}
Because your entity class don't have a property like description.
Instead of this write:
for (quoteDC * obj in arr)
{
[show appendString:[obj quotes]];
}
Try this i think it work for u...
- (IBAction)randBtn:(id)sender {
SendQuoteVC *svc= [[SendQuoteVC alloc]initWithNibName:#"SendQuoteVC" bundle:nil];
DBHandler *db =[[DBHandler alloc]init];
arr =[db randomQuote];
NSString *rs =(NSString *)arr;
svc.quote=rs;
[self.navigationController pushViewController:svc animated:YES];
}
Instead of for (NSObject * obj in arr) use the object that is stored in arr.
I guess it is some DBHandler object. So use
for (DBHandler * dbh in arr){
[show appendString:[dbh thePropertyYouWantToAppend]];
}

Grabbing multiple rows from sudzc

I'm trying to return multiple rows from a sudzc wsdl. I have loaded the result into a dictionary. The code below gives me the first result. How do I retrieve all of the results instead of just the first one? I'm looking for CSHR_POS_NAME where [ID.text intValue] == CSHR_NUM.
dict = [resp objectForKey:#"TC"];
if( ( dict == nil ) || ![dict isKindOfClass:[NSDictionary class]] ) {
NSLog( #"WARNING: %#", [dict description]);
return;
}
desc = [[dict objectForKey:#"CSHR_POS_NAME"]copy];
CashierNum = [[dict objectForKey:#"CSHR_NUM"]copy];
NSLog(#"Name: %# and Cashier Number: %#",desc, CashierNum);
I was able to accomplish in vb:
If dsCashiers.Table("TC").Rows.Count > 0 Then
...
[d setObject:v forKey:[child name]];
NSString* key = [child name];
id check = [d objectForKey:key];
if( check != nil ) {
NSInteger next = 1;
key = [NSString stringWithFormat:#"%#%d", [child name], next];
check = [d objectForKey:key];
while( check != nil ) {
next++;
key = [NSString stringWithFormat:#"%#%d", [child name], next];
check = [d objectForKey:key];
}
[d setObject:v forKey:key];
}
[d setObject:v forKey:[child name]];

AWS SimpleDB Select Expression iPhone

I need to construct a selectExpression for SimpleDB where I only want items with attributes = to X, sorted in descending order by attribute Y. All I have so far is this:
NSString *selectExpression = [NSString stringWithFormat:#"select itemName() from `%#`",domainString];
#try {
SimpleDBSelectRequest *selectRequest2 = [[[SimpleDBSelectRequest alloc] initWithSelectExpression:selectExpression] autorelease];
SimpleDBSelectResponse *selectResponse = [[Constants sdb] select:selectRequest2];
if (items == nil) {
items = [[NSMutableArray alloc] initWithCapacity:[selectResponse.items count]];
}
else {
[items removeAllObjects];
}
for (SimpleDBItem *item in selectResponse.items) {
[items addObject:item.name];
}
[items sortUsingSelector:#selector(compare:)];
}
#catch (AmazonServiceException *exception) {
NSLog(#"Exception = %#", exception);
}
I would prefer to only select items (above) with attributes X by Y rather than get all items and then sort. How do I add this? Does it go in the selectExpression string or somewhere else. Many thanks!
Try this out --
Select x,y from <domain_name> where itemName() is not null order by itemName() asc
NSString *selectExpression = [NSString stringWithFormat:#"select itemName() from `%#` where X = '%#' order by 'X' descending",domainName,attributeValue];

crash happens when NSMutableArray is returned?

I have coded like that(that function will be called again and again), but the returned object gives "BAD ACCESS", the NSLog prints correct string, but toReturn sometimes(i called
again and again) gives crashes..any help to alter this code,If i remove the "autorelease" method,it worsks fine
- (NSMutableArray *)getAll:(NSString *)type
{
NSLog(#"Type: %#", type);
NSMutableArray *toReturn = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
rs = [db executeQuery:Query1];
while ([rs next]) {
[toReturn addObject:[rs stringForColumn:#"Name"]];
NSLog(#"name: %#", [rs stringForColumn:#"Name"]);
}
[rs close];
return toReturn;
}
You need to make sure that your string is not deallocated in the meantime. Try changing
[toReturn addObject:[rs stringForColumn:#"Name"]];
to
[toReturn addObject:[[rs stringForColumn:#"Name"] copy]];