Get contact number from contact list in BlackBerry - blackberry

When the user clicks a button in my app, I want to open the contact list for the user to select a contact. I then want to get the phone number for the selected contact.

you can use BlackBerryContactList.choose().
BlackBerryContactList list = (BlackBerryContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
PIMItem contact = list.choose();
if(contact != null){
String mobileNumber="";
for(int i=0; i < contact.countValues(Contact.TEL); i++)
{
if(contact.getAttributes(Contact.TEL, i) == Contact.ATTR_MOBILE)
mobileNumber = contact.getString(Contact.TEL, i);
}
}

Related

Moving from AI to Multiplayer Game

I currently have a single player board game with one human player and three AI players. I would like to change that to four human players. How can I achieve that from the code below? Can I simply use and OR statement for the 1st line "currentplayer ==3" and have that read "currentplayer == 3 | 1"
if (currentPlayer == 3 && ([currentTokens count])){
for (int count = 0; count < [currentTokens count]; count++) {
Token *token = (Token*)[currentTokens objectAtIndex:count];
[token setUserInteractionEnabled:YES];
}
}
else if ([currentTokens count])//For NonHuman Players
{
// NSLog(#"Break3.3");
int arrLength = [currentTokens count];
// NSLog(#"Break3.4 and %i",arrLength);
////////////////// AI for NON HUMAN AT OCCURENCE OF SIX OF DICE////////////
Token *nonHumanToken;
int tokenAtHomeCount = 0;
if (firstDiceValue == 6) {
for (int count = 0; count < [currentTokens count]; count++) {
Token *selectedToken = (Token*)[currentTokens objectAtIndex:count];
if (selectedToken.isAtHome) {
tokenAtHomeCount++;
nonHumanToken = (Token*)[currentTokens objectAtIndex:count];
break;
}
}
if (!tokenAtHomeCount) {
nonHumanToken = (Token*)[currentTokens objectAtIndex:(arc4random()%arrLength)];
}
}
else{
nonHumanToken = (Token*)[currentTokens objectAtIndex:(arc4random()%arrLength)];
}
////////////////////////////////
[self performSelector:#selector(courseOfActionWithDelay:) withObject:nonHumanToken afterDelay:1.5];
// [self moveToken:nonHumanToken Till:firstDiceValue];
if ([currentTokens count]) {
[self DisplayMessageForMovingTokens:currentPlayer];
}
}
Ideally if you are replacing your AI with human players, you would completely ditch the AI code. I would look into duplicating the human code for each player.
Say you have:
if(player==1) {
player 1's turn stuff here
}
you would expand off of that and move on to:
if(player==2) {
player 2's turn stuff here
}
If this is to be a turn based game, instead of tracking players, track turns. Turn one would be player one, turn two is player two, and then just reset once you get to the max number of players for the round.

Access email in EKParticipant/EKAttendee

I want to get the email address of the attendee of an event in the EKEventKit.
I have the following code:
if ( event.attendees.count > 0)
{
NSArray *people = event.attendees;
for(EKParticipant *person in people)
{
if ( person.participantType == EKParticipantTypePerson && person.URL.resourceSpecifier.length > 0)
{
NSString *dataString = [NSString stringWithFormat:#"event_id=%ld&name=%#&is_me=%d&email=%#&role=%#",event_id,person.name, person.isCurrentUser,person.URL.resourceSpecifier, #"attendee"];
//<DO SOMETHING USEFUL WITH dataString>;
}
}
}
When I run the code person populates with the following data:
EKAttendee <0x17809acc0> {UUID = 4F657EA4-452A-412B-A9AA-FEC5551DC096; name = A. Real Person; email = realperson#therightdomain.com; status = 0; role = 0; type = 1}
How to I access the email field?
I tried (as above) to use URL.resourceSpecifier, but that frequently is some strange string that is definitely NOT an email address.
The "Description" of the EKParticipant object is a property list of sorts. I tried several different methods of parsing that list into something containing key:value pairs unsuccessfully. So I wrote the following:
// This is re-useable code that converts any class description field into a dictionary that can be parsed for info
NSMutableDictionary *descriptionData = [NSMutableDictionary dictionary];
for (NSString *pairString in [person.description componentsSeparatedByString:#";"])
{
NSArray *pair = [pairString componentsSeparatedByString:#"="];
if ( [pair count] != 2)
continue;
[descriptionData setObject:[[pair objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:[[pair objectAtIndex:0]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
With this I simply get the email address with
[descriptionData valueForKey:#"email"]
I tried to answer this same question in "how to get ekevent EKparticipant email?" thread:
What you need to do is use EKPrincipal:ABRecordWithAddressBook and then extract email from there. Like this:
NSString *email = nil;
ABAddressBookRef book = ABAddressBookCreateWithOptions(nil, nil);
ABRecordRef record = [self.appleParticipant ABRecordWithAddressBook:book];
if (record) {
ABMultiValueRef value = ABRecordCopyValue(record, kABPersonEmailProperty);
if (value
&& ABMultiValueGetCount(value) > 0) {
email = (__bridge id)ABMultiValueCopyValueAtIndex(value, 0);
}
}
Note that calling ABAddressBookCreateWithOptions is expensive so you might want to do that only once per session.
If you can't access the record, then fall back on URL.resourceSpecifier.
In Swift 4:
private static func getParticipantDescriptionData(_ participant: EKParticipant) -> [String:String] {
var descriptionData = [String: String]()
for pairString in participant.description.components(separatedBy: ";") {
let pair = pairString.components(separatedBy: "=")
if pair.count != 2 {
continue
}
descriptionData[pair[0].trimmingCharacters(in: .whitespacesAndNewlines)] =
pair[1].trimmingCharacters(in: .whitespacesAndNewlines)
}
return descriptionData
}

IOS have a report builder generate in PDF

I have data to generate report that have header footer and content.
In the content have many group when the data in each group over the page area it add new page and write header of group and continued content data
Where can I have lib. or something to do this Task ??
Thanks For Advance.
Add for request code
NSArray *headObject = [uniqueStates allObjects];////Store head of each group
NSArray *detail; //Store all of data to present in table
int allData = [detail count]; // Tel amount of all data to show
/*
int headGroupline = 1; //Tel amount of head group line
int footGroupline = 1; //Tel amount of foot group line
*/
int detailIndex = 0; ///Tel what line we are now
int detailHeadIndex = 0; ///Tel what group we are now
int subdetail = 0; // Tel what line on group now
int aviableLineInpage = 24; // Line avilable in page for data to show
int allPage = 0; //Sum of all page
for (; detailIndex < allData; ) {
allPage++;
for (int i=0; i < aviableLineInpage;) {
if (allData - detailIndex == 0) {
///ShowgrandTotal
........
detailIndex++;
i+=25;
}else{
if (i == 0) {
//Show Head Group
......
}else{
if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(buy_date == %#)", headObject[detailHeadIndex]]] count]+1) {
detailHeadIndex++;
//Show Head Group
..........
}else{
if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(buy_date == %#)", headObject[detailHeadIndex]]] count]) {
//Show sum of each group
..........
i++;
detailIndex++;
subdetail++;
detailHeadIndex++;
}else{
//Show data of detail
........................
detailIndex++;
subdetail++;
}
}
}
i++;
}
}//for all line in page
}//for allData
It format is:
date 27/01/2014
data1
data2
data3
sum date 27/01/2014
date 28/01/2014
data1
data2
<============if page brake add new page and
date 28/01/2014
data3
sum date 28/01/2014
grand total........
But it goes
date 27/01/2014
data1
data2
data3
sum date 27/01/2014
data1
data2
<============if page brake add new page and
date 28/01/2014
data3
grand total........
Thanks very much
Use CGPDFDocumentRef and the associated functions to create the PDF document and each page it contains. When you create a page (UIGraphicsBeginPDFPageWithInfo) you can get the associated drawing context (UIGraphicsGetCurrentContext). Once you have that you can draw in a number of ways:
You could create a view with your header and footer, add content and render it into the view (using its layer)
You could draw images and text direct into the context (using CoreText (CTFrameDraw))
You need to create the logic to set how much content can fit on any one page and when you need to create a new page.
Also, depending on how you choose to draw content into the context you may need to scale and transform (CGContextScaleCTM + CGContextTranslateCTM) the context so that your content isn't upside down.
See this Apple guide.
int allData = [detail count]; // Tel amount of all data to show
/*
int headGroupline = 1; //Tel amount of head group line
int footGroupline = 1; //Tel amount of foot group line
*/
int detailIndex = 0; ///Tel what line we are now
int detailHeadIndex = 0; ///Tel what group we are now
int subdetail = 0; // Tel what line on group now
int aviableLineInpage = 24; // Line avilable in page for data to show
int allPage = 0; //Sum of all page
for (; detailIndex < allData; ) {
allPage++;
for (int i=0; i < aviableLineInpage;) {
if (allData - detailIndex == 0) {
detailIndex++;
i+=25;
}else{
if (i == 0) {
if (subdetail == -1) {
subdetail = 0;
}
}else{
if (subdetail == -1) {
subdetail = 0;
}else{
if (subdetail == [[detail filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(buy_date == %#)", headObject[detailHeadIndex]]] count]) {
i++;
subdetail = -1;
detailHeadIndex++;
if (detailHeadIndex == [headObject count] ) {
detailIndex++;
}
}else{
detailIndex++;
subdetail++;
}
}
}
i++;
}
}//for all line in page
}//for allData

Get an array of 3 ordered values whilst favouring a specified value

Sorry for the somewhat generic title, if anyone has a better suggestion please let me know.
Basically I am writing a custom leaderboard view whereby I want to show 3 scores only. If possible it will show the current user's score in the middle but, if the user is at the top or the bottom of the list, it should still show 3 scores but itll show another users above or below the list.
e.g.
Me (If I am top, then show 2 below)
User 1
User 2
or
User 1
Me (usual case where I am in the middle of two scores)
User 2
or
User 1
User 2
Me (If I am bottom show two scores above me)
I have a function written that does the first part of this but doesnt take into account edge cases which is what I am struggling with. Can anyone please advise?
-(void)getNearbyScores:(int)score{
GCLeaderboardScore *closestScoreAbove = nil; //Custom container for GC properties
GCLeaderboardScore *closestScoreBelow = nil; //Contains playerID, score, alias etc
if ([playerScores count] == 0){ //playerScores is an NSMutableDictionary
return;
}
for (NSString* key in playerScores) {
GCLeaderboardScore *playerScore = (GCLeaderboardScore *)[playerScores objectForKey:key];
if ((closestScoreAbove == nil || closestScoreAbove->score > playerScore->score) && playerScore->score > score){
closestScoreAbove = playerScore;
}
else if ((closestScoreBelow == nil || closestScoreAbove->score < playerScore->score) && playerScore->score < score){
closestScoreBelow = playerScore;
}
}
me->score = score;
me->rank = 1;
if (closestScoreAbove != nil) {
me->rank = closestScoreAbove->rank + 1;
nearbyScores = [NSMutableArray arrayWithObjects: closestScoreAbove, me, closestScoreBelow, nil];
}
else {
nearbyScores = [NSMutableArray arrayWithObjects: me, closestScoreBelow, nil];
}
}
Assuming there is a me GCLeaderboardScore object, the method below should return an array with the desired GCLeaderboardScore objects (untested):
-(NSArray *)getNearbyScores {
if(playerScores.count==0) return nil;
// Create an array sorted by score
NSArray *sortedByScore=[playerScores sortedArrayUsingComparator: ^(id object1, id object2) {
GCLeaderboardScore *score1=object1;
GCLeaderboardScore *score2=object2;
if(score1->score < score2->score) return NSOrderedAscending;
if(score1->score > score2->score) return NSOrderedDescending;
return NSOrderedSame;
}];
// Find index of me
NSUInteger idx=[sortedByScore indexOfObject:me];
// If me not found, return nil
if(idx==NSNotFound) return nil;
// Ideally we want to show the player before and behind
idx=MAX(0,(NSInteger)idx-1);
// maxIdx will be idx+2 or index of last object if lower
NSUInteger maxIdx=MIN(sortedByScore.count-1,idx+2);
// In case we are last, show two previous results (if array large enough)
if (maxIdx > 3)
idx=MAX(0,maxIdx-3);
// And return the objects, may be 1..3 objects
return [sortedByScore subarrayWithRange:NSMakeRange(idx,maxIdx-idx+1)];
}
I assume you have an array of scores. (Actual implementation can be adapted to your code)
Initialize:
firstScoreAbove = VERY_LARGE_SCORE; secondScoreAbove = VERY_LARGE_SCORE + 1;
firstScoreBelow = -1; secondScoreBelow = -2;
Scan the array elements.
if ( newScore > myScore ) {
if ( newScore < firstScoreAbove ) {
secondScoreAbove = firstScoreAbove;
firstScoreAbove = newScore;
} else if ( newScore < secondScoreAbove ) {
secondScoreAbove = newScore;
}
} else {
// similarly for below.
}
After scanning,
If firstScoreAbove has not changed, then myScore is top and output the two below scores.
If firstScoreBelow has not changed, then myScore is lowest and output the two above scores.
Else Output firstScoreAbove, myScore, firstScoreBelow.

Using PIM, how to detect what is the attribute which is retrieved using Contact.TEL and index?

I'm looping over all attributes of the Contact.TEL field to retrieve names and data, so that I can display something like this:
HOME: +2034953213
WORK: +2033923959
MOBILE: +20179083008
I've retrived the values (+2034953213, +2033923959, +20179083008) successfully using PIM api, but I didn't know how to detect what are the attributes corresponding to the values which I retrieved: (HOME, WORK or MOBILE ...etc) ?
How Can I detect that +2034953213 is either the 'HOME' or 'WORK' or 'MOBILE' ?
Same question for the other retrieved values ?
Here's my code:
ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
Enumeration contactListItems = contactList.items();
while (contactListItems.hasMoreElements()) {
Contact contact = (Contact)contactListItems.nextElement();
int telephonesCount = contact.countValues(Contact.TEL);
for(int i=0; i< telephonesCount; ++i) {
String number = contact.getString(Contact.TEL, i);
// I want here to know what is the current attribute that i retrieved its value ?
// I mean its value not its index (either HOME, WORK or MOBILE ...etc)
}
}
Here's the answer for those who are interested:
ContactList contactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
Enumeration contactListItems = contactList.items();
while (contactListItems.hasMoreElements()) {
Contact contact = (Contact)contactListItems.nextElement();
int telephonesCount = contact.countValues(Contact.TEL);
for(int i=0; i< telephonesCount; ++i) {
String number = contact.getString(Contact.TEL, i);
int attribute = contact.getAttributes(BlackBerryContact.TEL, i);
if (attribute == Contact.ATTR_MOBILE)
// It's a mobile phone number, do whatever you want here ...
else if (attribute == Contact.ATTR_HOME)
// It's a home phone number, do whatever you want here ...
else if (attribute == Contact.ATTR_WORK)
// It's a work phone number, do whatever you want here ...
// check other types the same way ...
}
}

Resources