Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
kully
Posts: 23
Registered: ‎10-15-2009
My Device: Not Specified

Adding many random contacts - sample code

Hello.

 

Address book searching is slooow. To get a feel for how your app would work with lots of contacts try the following code (I put it beind a menu item). You'll need a few imports, but Eclipse will tell you which ones. To vary the number of contacts to add change the first for-loop.

 

Hope this saves someone a litte bit of time.

 

cheers,

 

 

 

        	   ContactList contacts = null;
        	   try {
        	      contacts = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
        	   } catch (PIMException e) {
        	      // An error occurred
        	      return;
        	   }
        	   
        	   String arrSzCities[] = {"Birmingham", "Walsall", "Wolverhampton", "Banbury", "Bromsgrove", "Lichfield", "Balsall Heath",
        			   "West Bromich", "Smethwick", "Scott Arms", "Perry Barr", "Small Heath", "Acocks Green", "Great Barr",
        			   "Harborne", "Selly Oak", "Newtown", "Hockley", "Nuneaton", "Stafford", "Stoke", "Sandwell", "Brierly Hill",
        			   "Longbridge", "Sutton Coldfield", "Tamworth", "Coventry", "Rugby", "Hall Green", "Olton", "Dorridge",
        			   "Lapworth", "Shirley", "Wythall", "Warwick", "Dudley", "Barnt Green", "Tile Hill", "Berkswell", "Canley",
        			   "Yardley", "Yardley Wood", "Bordesley Green", "Cosely", "Four Oaks", "Erdington", "Aston", "Duddington"};  
        	   
        	   String arrSzCountries[] = {"England", "Wales", "Scotland", "Northern Ireland", "Eire", "Spain", "France", "Italy",
        			   "Monaco", "Switzerland", "Austria", "Germany", "Lapland", "Estonia", "Hungary", "Slovakia", "Slovenia",
        			   "Czech Republic", "Latvia", "Holland", "Belgium", "Luxembourg", "Iceland", "Finland", "Denmark", "Norway"};
        	   
        	   String arrSzFamilyNames[] = {"SMITH", "JOHNSON", "WILLIAMS", "BROWN", "JONES", "MILLER", "DAVIS", "GARCIA", "RODRIGUEZ",
        			   "WILSON", "MARTINEZ", "ANDERSON", "TAYLOR", "THOMAS", "HERNANDEZ", "MOORE", "MARTIN", "JACKSON", "THOMPSON", 
        			   "WHITE", "LOPEZ", "LEE", "GONZALEZ", "HARRIS", "CLARK", "LEWIS", "ROBINSON", "WALKER", "PEREZ", "HALL", "YOUNG",
        			   "ALLEN", "SANCHEZ", "WRIGHT", "KING", "SCOTT", "GREEN", "BAKER", "ADAMS", "NELSON", "HILL", "RAMIREZ", "CAMPBELL",
        			   "MITCHELL", "ROBERTS", "CARTER", "PHILLIPS", "EVANS", "TURNER", "TORRES", "PARKER", "COLLINS", "EDWARDS", "STEWART",
        			   "FLORES", "MORRIS", "NGUYEN", "MURPHY", "RIVERA", "COOK", "ROGERS", "MORGAN", "PETERSON", "COOPER", "REED",
        			   "BAILEY", "BELL", "GOMEZ", "KELLY", "HOWARD", "WARD", "COX", "DIAZ", "RICHARDSON", "WOOD", "WATSON", "BROOKS",
        			   "BENNETT", "GRAY", "JAMES", "REYES", "CRUZ", "HUGHES", "PRICE", "MYERS", "LONG", "FOSTER", "SANDERS", "ROSS", 
        			   "MORALES", "POWELL", "SULLIVAN", "RUSSELL", "ORTIZ", "JENKINS", "GUTIERREZ", "PERRY", "BUTLER", "BARNES", "FISHER",
        			   "HENDERSON", "COLEMAN", "SIMMONS", "PATTERSON", "JORDAN", "REYNOLDS", "HAMILTON", "GRAHAM", "KIM", "GONZALES",
        			   "ALEXANDER", "RAMOS", "WALLACE", "GRIFFIN", "WEST",
        			   "COLE", "HAYES", "CHAVEZ", "GIBSON", "BRYANT", "ELLIS", "STEVENS", "MURRAY", "FORD", "MARSHALL", "OWENS", 
        			   "MCDONALD", "HARRISON", "RUIZ", "KENNEDY", "WELLS", "ALVAREZ", "WOODS", "MENDOZA", "CASTILLO", "OLSON", 
        			   "WEBB", "WASHINGTON", "TUCKER", "FREEMAN", "BURNS", "HENRY", "VASQUEZ", "SNYDER", "SIMPSON", "CRAWFORD", "JIMENEZ", 
        			   "PORTER", "MASON", "SHAW", "GORDON", "WAGNER", "HUNTER", "ROMERO", "HICKS", "DIXON", "HUNT", "PALMER", "ROBERTSON", 
        			   "BLACK", "HOLMES", "STONE", "MEYER", "BOYD", "MILLS", "WARREN", "FOX", "ROSE", "RICE", "MORENO", "SCHMIDT", "PATEL", 
        			   "FERGUSON", "NICHOLS", "HERRERA", "MEDINA", "RYAN", "FERNANDEZ", "WEAVER", "DANIELS", "STEPHENS", "GARDNER", "PAYNE", 
        			   "KELLEY", "DUNN", "PIERCE", "ARNOLD", "TRAN", "SPENCER", "PETERS", "HAWKINS", "GRANT", "HANSEN", "CASTRO", "HOFFMAN", 
        			   "HART", "ELLIOTT", "CUNNINGHAM", "KNIGHT"};

        	   String arrSzFirstNames[] = {"MARY", "PATRICIA", "LINDA", "BARBARA", "ELIZABETH", "JENNIFER", "MARIA", "SUSAN", "MARGARET",
        			   "DOROTHY", "LISA", "NANCY", "KAREN", "BETTY", "HELEN", "SANDRA", "DONNA", "CAROL", "RUTH", "SHARON", "MICHELLE",
        			   "LAURA", "SARAH", "KIMBERLY", "DEBORAH", "JESSICA", "SHIRLEY", "CYNTHIA", "ANGELA", "MELISSA", "BRENDA", "AMY",
        			   "ANNA", "REBECCA", "VIRGINIA", "KATHLEEN", "PAMELA", "MARTHA", "DEBRA", "AMANDA", "STEPHANIE", "CAROLYN", "CHRISTINE",
        			   "MARIE", "JANET", "CATHERINE", "FRANCES", "ANN", "JOYCE", "DIANE", "ALICE", "JULIE", "HEATHER", "TERESA", "DORIS",
        			   "GLORIA", "EVELYN", "JEAN", "CHERYL", "MILDRED", "GERALD", "KEITH", "SAMUEL", 
        			   "JAMES", "JOHN", "ROBERT", "MICHAEL", "WILLIAM", "DAVID", "RICHARD", "CHARLES", "JOSEPH", "THOMAS", "CHRISTOPHER", 
        			   "DANIEL", "PAUL", "MARK", "DONALD", "GEORGE", "KENNETH", "STEVEN", "EDWARD", "BRIAN", "RONALD", "ANTHONY", 
        			   "KEVIN", "JASON", "MATTHEW", "GARY", "TIMOTHY", "JOSE", "LARRY", "JEFFREY", "FRANK", "SCOTT", "ERIC", "STEPHEN", 
        			   "ANDREW", "RAYMOND", "GREGORY", "JOSHUA", "JERRY", "DENNIS", "WALTER", "PATRICK", "PETER", "HAROLD", "DOUGLAS", 
        			   "HENRY", "CARL", "ARTHUR", "RYAN", "ROGER", "JOE", "JUAN", "JACK", "ALBERT", "JONATHAN", "JUSTIN", "TERRY"};	   

        	   String arrSzEmailProviders[] = {"google", "yahoo", "wanadoo", "freemail", "aol", "yellowmellow", "redmail", "bt", "tiscali",
					   "naims", "bulldog", "demon", "virgin", "sky", "orange", "vodaphone", "o2", "three", "britishgas", "npower",
					   "britishtelecom", "royalmail", "parcelforce", "dhl", "usps", "ford", "rover", "fiat", "seat", "volvo", "bmw",
					   "landrover", "jaguar", "warburtons", "kingsmill", "hovis", "walkers", "cadburys", "ironbru", "redbull", "jura"};
        	   
        	   String arrSzAlphas[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
        			   "U", "V", "W", "X", "Y", "Z"};
        	   
        	   String arrSzStreetSuffixes[] = {"Road", "Street", "Crescent", "Close", "Way", "Mews", "Common", "Alley", "Common", "Grove",
        			   "Place", "Mill", "Manor", "Lane", "March", "Hill", "Park", "Passage", "Path", "Row", "Square", "Terrace", "View"};
        	   
        	   String arrSzStreetNames[] = {"High", "Station", "Main", "Park", "Church", "London", "Victoria", "Albert", "Green", "Manor",
        			   "Church", "Park", "Queens", "New", "Grange Road", "Kings Road", "North", "West", "South", "East", "Windsor", 
        			   "Highfield", "Mill", "Alexander", "York", "St. John's", "Broad", "Springfield", "George", "Manchester", "Richmond",
        			   "School", "Stanley", "Chester", "Aghaloo", "Picadilly", "**bleep**", "Wooburn", "Crazies", "Valentia", "Luton", "Croydon",
        			   "Rookery", "Coronation", "Dawlish", "Tiverton", "Dartmouth", "Hubert", "Bristol", "Arley", "Grange", "Dale",
        			   "Serpentine", "Bournebrook", "University", "Holly", "Kitchener", "Millner", "Westminster", "Cherrington", "Gristhorpe",
        			   "Kensington", "Cartland", "Horatio", "Ethelbert", "Hornblower", "Hanky Panky", "Bewdley", "Acorn", "Berry", "Moor", 
        			   "Brent", "Mungo Jerry", "Highbury", "Howell", "Tenbury", "Peacock", "Hartswell"};
        	   
        	   Random generator = new Random(1628434416);
        	   for (int i = 0; i < 2000; i++)
        	   {
            	   Contact contact = contacts.createContact();
            	   String[] addr = new String[contacts.stringArraySize(Contact.ADDR)];
            	   String[] szName = new String[contacts.stringArraySize(Contact.NAME)];

            	   // Family Name
            	   if (contacts.isSupportedArrayElement(Contact.NAME, Contact.NAME_FAMILY))
            		   szName[Contact.NAME_FAMILY] = arrSzFamilyNames[generator.nextInt(arrSzFamilyNames.length)];
            	   // First Name
            	   if (contacts.isSupportedArrayElement(Contact.NAME, Contact.NAME_GIVEN))
            		   szName[Contact.NAME_GIVEN] = arrSzFirstNames[generator.nextInt(arrSzFirstNames.length)];
            	   // Add name to contact
            	   contact.addStringArray(Contact.NAME, PIMItem.ATTR_NONE, szName);            	   

            	   // Postcode (UK format)
            	   if (contacts.isSupportedArrayElement(Contact.ADDR, Contact.ADDR_POSTALCODE))
            	        addr[Contact.ADDR_POSTALCODE] = 
            	        arrSzAlphas[generator.nextInt(arrSzAlphas.length)] + arrSzAlphas[generator.nextInt(arrSzAlphas.length)] 
            	        + Integer.toString(generator.nextInt(99)) + Integer.toString(generator.nextInt(9)) + " "
            	        + arrSzAlphas[generator.nextInt(arrSzAlphas.length)] + arrSzAlphas[generator.nextInt(arrSzAlphas.length)];  

            	   // Street and number
            	   if (contacts.isSupportedArrayElement(Contact.ADDR, Contact.ADDR_STREET))
            	        addr[Contact.ADDR_STREET] = Integer.toString(generator.nextInt(999)) + " "
            	        + arrSzStreetNames[generator.nextInt(arrSzStreetNames.length)]
            	        + " " + arrSzStreetSuffixes[generator.nextInt(arrSzStreetSuffixes.length)];
      	      
        		   // Locality
            	   if (contacts.isSupportedArrayElement(Contact.ADDR, Contact.ADDR_LOCALITY))
            		   addr[Contact.ADDR_LOCALITY] = arrSzCities[generator.nextInt(arrSzCities.length)];
            	   // Country
            	   if (contacts.isSupportedArrayElement(Contact.ADDR, Contact.ADDR_COUNTRY))
            		   addr[Contact.ADDR_COUNTRY] = arrSzCountries[generator.nextInt(arrSzCountries.length)];
            	   if (contacts.isSupportedField(Contact.ADDR))
             	      contact.addStringArray(Contact.ADDR, Contact.ATTR_HOME, addr);
            	   
            	   // Email address
            	   if (contacts.isSupportedField(Contact.EMAIL)) {
             	      contact.addString(Contact.EMAIL, Contact.ATTR_HOME | Contact.ATTR_PREFERRED, szName[Contact.NAME_GIVEN] + "." + szName[Contact.NAME_FAMILY] + "@" + arrSzEmailProviders[generator.nextInt(arrSzEmailProviders.length)] + ".com");
            	   }

				   // Telephone numbers (work and home)
            	   String szTelHome = "";
            	   String szTelWork = "";
            	   for (int j = 0; j < 7; j++) {
            		   String szDigit = Integer.toString(generator.nextInt(9));
            		   szTelHome = szTelHome + szDigit;
            		   szTelWork = szDigit + szTelWork; 
            	   }
            	   if (contacts.isSupportedField(Contact.TEL)) {
             	      contact.addString(Contact.TEL, Contact.ATTR_HOME, szTelHome);
             	   }
            	   if (contacts.isSupportedField(Contact.TEL)) {
              	      contact.addString(Contact.TEL, Contact.ATTR_WORK, szTelHome);
              	   }
            	   
            	   try {
            		   contact.commit();
            	   } catch (PIMException e) {
           	        // An error occured
            		   
            	   }
        	   }
        	          	   
        	   try {
        	        contacts.close();
        	   } catch (PIMException e) {
        	   }
           }

 

 

Developer
peter_strange
Posts: 19,610
Registered: ‎07-14-2008
My Device: Not Specified

Re: Adding many random contacts - sample code

Brilliant.  Thanks.  kudos to you!!!

Developer
simon_hain
Posts: 16,282
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: Adding many random contacts - sample code

extremly nice to share this code! don't need it just yet, but i am sure i will.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Developer
myraddin
Posts: 412
Registered: ‎09-12-2008
My Device: 9000 9810

Re: Adding many random contacts - sample code

Very useful piece of code !

 

Thanks !



"Listen carefully, I shall say this only once"
Developer
kully
Posts: 23
Registered: ‎10-15-2009
My Device: Not Specified

Re: Adding many random contacts - sample code

Let's hope the code monkeys at RIM take pity on is poor code monkeys and give us better access to contact information. :smileyhappy:

 

 

New Developer
ankur_kulkarni
Posts: 27
Registered: ‎08-04-2009
My Device: Not Specified

Re: Adding many random contacts - sample code

Hi Can anyone tel me how to add Birthdate to the contact?

Developer
jitendrasharma
Posts: 208
Registered: ‎08-04-2009
My Device: Not Specified

Re: Adding many random contacts - sample code

 

   public class HttpGetConnector implements Runnable //extends Thread//
    {
        public int code = 0;
        public String reply = null;
        public String errorMsg = null;
        String url = null;
        public HttpConnection c = null;
        InputStream is = null;
        int responseLength = -1;
        int responseCounter = -1;
        int currentCount = 0;
        private boolean running;
        private boolean waiting;
        private boolean active;
        private boolean cancel;
        
        //String auth = "GoogleLogin Auth="+authorization;
        String Authorization = null;
        String ContentType = null;
        String ContentLength = null;
        
        public HttpGetConnector(String url) 
        {    
        	
            this.url =  url;
            //

            running = false;
            waiting = false;
            cancel = false;
            
        }
        
        
        public void run()
        {
            reply = getViaHttpConnection();
        }
        
        public String getViaHttpConnection() 
    	{
    		String retval = "";

    		try 
    		{
    			setWaiting();
    			c = (HttpConnection)Connector.open(createURL(url));
    			setRunning();

    			code = c.getResponseCode();
    			System.out.println("Response Code - "+code);
    			if(code == HttpConnection.HTTP_OK) //if conection is established 
    			{
    				
    				/*if(ContentType!=null)
						c.setRequestProperty("Content-Type",ContentType);
					if(ContentLength!=null)
						c.setRequestProperty("Content-Length",ContentLength);*/
    				// Getting the response code will open the connection,
    				// send the request, and read the HTTP response headers.
    				// The headers are stored until requested.
    				
    				is = c.openInputStream();

    				// Get the ContentType
    				String type = c.getType();

    				// Get the length and process the data
    				String msg = c.getResponseMessage();
    				System.out.println(msg);
    				responseLength = (int)c.getLength();
    				responseCounter = responseLength / 256;


    				byte[] data = new byte[256];
    				int len = 0;
    				StringBuffer raw = new StringBuffer();

    				while ( -1 != (len = is.read(data)) ) 
    				{
    					raw.append(new String(data, 0, len));
    					currentCount++;
    					active = true;
    					if(cancel)
    					{
    						break;
    					}
    				}

    				String text = raw.toString();
    				//System.out.println(text);

    				if(cancel)
    				{
    					retval = null;
    				}
    				else
    				{
    					retval = text;
    				}
    			}
    			else if(code==HttpConnection.HTTP_UNAUTHORIZED)
    			{
    				//Connection is 401 UnAuthorized.
    				//A login and password is required.

    				//Obtain the login information from somewhere. 
    				//You could prompt the user for this information or 
    				//retrieve this from elsewhere if it is saved within 
    				//your application.
    				//Login information is hard coded here for brevity, but
    				//we ask the user if they want to log in.

    					String login = "jksharma@sampatti.com:p@ssw0rd777";

    					//Close the connection.
    					c.close();

    					//Encode the login information in Base64 format.
    					byte[] encoded = Base64OutputStream.encode(login.getBytes(), 0, login.length(), false, false);

    					c = (HttpConnection)Connector.open(createURL(url));
    					setRunning();

    					//Add the authorized header.
    					c.setRequestProperty("Authorization", "Basic " + new String(encoded));
    					
    					/*if(ContentType!=null)
    						c.setRequestProperty("Content-Type",ContentType);
    					if(ContentLength!=null)
    						c.setRequestProperty("Content-Length",ContentLength);*/
    					// Getting the response code will open the connection,
    					// send the request, and read the HTTP response headers.
    					// The headers are stored until requested.
    					
    					is = c.openInputStream();

    					// Get the ContentType
    					String type = c.getType();

    					// Get the length and process the data
    					String msg = c.getResponseMessage();
    					System.out.println(msg);
    					responseLength = (int)c.getLength();
    					responseCounter = responseLength / 256;


    					byte[] data = new byte[256];
    					int len = 0;
    					StringBuffer raw = new StringBuffer();

    					while ( -1 != (len = is.read(data)) ) 
    					{
    						raw.append(new String(data, 0, len));
    						currentCount++;
    						active = true;
    						if(cancel)
    						{
    							break;
    						}
    					}

    					String text = raw.toString();
    					if(cancel)
    					{
    						retval = null;
    					}
    					else
    					{
    						retval = text;
    					}
    				
    			}
    			else
    			{
    				retval=null;
    			}
    		}
    		catch (Exception e) 
    		{
    			//Logger.write(e,"Error - ");
    			if(code!=-1)
    				code = HttpConnection.HTTP_NOT_FOUND;

    			errorMsg = e.toString();
    			retval = null;
    		}
    		/* closing connection & streams if open*/
    		finally 
    		{
    			try
    			{
    				if (is != null)
    					is.close();
    				if (c != null)
    					c.close();
    			}
    			catch(Exception err)
    			{
    			}
    		}
    		return retval;
    	}
        
       
//========================================================================================================

    private String createURL(String connectUrl) 
    {
        String extension = "";
        if (DeviceInfo.isSimulator()) 
        {
            extension = ";deviceside=false";
        }
        else  if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
        {
                extension = ";deviceside=false";
         }             
        else {
          String uid = null;
          ServiceBook sb = ServiceBook.getSB();
          ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
          for (int i = 0; i < records.length; i++) {
            if (records[i].isValid() && !records[i].isDisabled()) {
            if (records[i].getUid() != null &&
                records[i].getUid().length() != 0) {
                if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
                    (records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
                    (records[i].getUid().toLowerCase().indexOf("mms") == -1)   ) {
                    uid = records[i].getUid();
                    break;
                }
            }
        }
    }
    if (uid != null) {
         // WAP2 Connection...........
         extension = ";ConnectionUID="+uid;
    }
     /*else  if ( ( RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN ) != 0 )
        {
           
            if(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_CARRIER, RadioInfo.WAF_WLAN, true))
               {
                     System.out.println("Wi-fi connected");
                     extension = ";deviceside=true;interface=wifi";
            }
        }
        */ 
    else {
        //TCP/IP connection..........
         extension = ";deviceside=true";
       }
      }
        return (connectUrl + extension); 
    }
    
    private String getDefaultConnection()
    {
        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.findRecordsByCid( "IPPP" );    
        
        if( records == null )
        {
            return ";deviceside=true";
        }

        int numRecords = records.length;
        for( int i = 0; i < numRecords; i++ )
        {
            ServiceRecord myRecord = records[i];
            
            if( myRecord.isValid() && !myRecord.isDisabled() )
            {
               int encryptionMode = myRecord.getEncryptionMode();
                if( encryptionMode == ServiceRecord.ENCRYPT_RIM )
                {
                     return ";deviceside=false";
                }
                else
                {
                      return ";deviceside=false;
ConnectionType=md-pub"; } } } return ";deviceside=true"; } //=================================End public void setContentLength(String length) { ContentLength = length; } public void setContentType(String type) { ContentType = type; } public String getResponse() { return reply; } public int getResponseCode() { return code; } public int getResponseLength() { return responseLength; } public int getResponseCounter() { return responseCounter; } public int getCurrentCount() { return currentCount; } public boolean isRunning() { return running; } private void setRunning() { running = true; waiting = false; } public boolean isWaiting() { return waiting; } private void setWaiting() { waiting = true; running = false; active = false; } public boolean isActive() { return active; } private void setActive() { active = true; } public void cancelThread() { cancel = true; } }

 

 

New Developer
Melanie_S
Posts: 5
Registered: ‎07-29-2011
My Device: Bold

Re: Adding many random contacts - sample code

that is awesome! thanks