Showing posts with label Code Samples. Show all posts
Showing posts with label Code Samples. Show all posts

Thursday, July 9, 2009

Spruce Up Your Table Views

Setting the background color of your table view is very easy.  All you need to do is set the backgroundColor property to the color you want to see.  For example, I have created a table view here in the app delegate and simply set the background property from here:
UITableViewController *tvc = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
tvc.view.backgroundColor = [UIColor redColor];
    
[window addSubview:tvc.view];
    
[window makeKeyAndVisible];
If you are using sub-classing, you may also rather set this property in the initWithStyle.
You can use also an image as your background to really spice things up.
Here is that code:
UIView *backgroundView = [[UIView alloc] initWithFrame: window.frame];
backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TableViewBackground.png"]];
[window addSubview:backgroundView];
[backgroundView release];
    
yourTableViewController = [[ATableViewController alloc] initWithStyle:UITableViewStyleGrouped];
yourTableViewController.view.backgroundColor = [UIColor clearColor];
[window addSubview:yourTableViewController.view];
    
[window makeKeyAndVisible];
 
This one takes a little more code - essentially you are putting an image into a view, inserting that into the app window and then setting the background to a transparent color. 
Simply setting the background color of the table view to the image would produce artifacts.  
That is it!  I hope that this tip will add some more pizazz to your apps!
As you can see, the this array is sorted. There you have it!

Thursday, May 14, 2009

Sorting An Array in Objective-C

Arrays are structures used to hold a list of objects. Sometimes
though you may want to sort the order that the elements appear.

Doing this is actually pretty simple once you know how,
essentially you will be using the NSArray sortedArrayUsingSelector
method.

For example, if you create an array like so

NSMutableArray *anArray = [[NSMutableArray alloc] init];
[anArray addObject:@"B"];
[anArray addObject:@"A"];
[anArray addObject:@"C"];
and then write out the contents of the array to the log using a
foreach loop the results will look like this:

[Session started at 2009-03-25 16:57:55 -0400.]
2009-03-25 16:57:58.647 SortigArray[3403:20b] B
2009-03-25 16:57:58.648 SortigArray[3403:20b] A
2009-03-25 16:57:58.649 SortigArray[3403:20b] C

Obviously, the contents of the array stay in the same order in
which they were inserted.

What you could do is create another array, sorted, using the
sortedArrayUsingSelector method of NSArray. Here is how:
NSArray *sortedArray = [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
The odd (for some anyway) piece of this code is the
@selector(caseInsensitiveCompare:) component of the code. This is
a method passed to the function that instructions NSArray on how
to sort the array.

At any rate, if you run through the array as before and print out
the results to the log you will get this:

[Session started at 2009-03-25 17:07:18 -0400.]
2009-03-25 17:07:21.832 SortigArray[3537:20b] A
2009-03-25 17:07:21.833 SortigArray[3537:20b] B
2009-03-25 17:07:21.834 SortigArray[3537:20b] C

As you can see, the this array is sorted. There you have it!

Monday, April 27, 2009

General Coding Tips

Avoid the Object.getClass() Method

Avoid using the Object.getClass() method, because it is not efficient and it produces garbage (the Class object) that is never collected. Also avoid using the example.class literal. Behind the scenes, this generates Class.forName(“Example”).

Writing Efficient Loops

You should always factor loop invariant code out of a loop, as in the following example:

    for(int i = 0; i < >
...

}

This code results in vector.size() getting called each time through the loop, which is inefficient. If your container is likely to have more than one element, it is much faster to assign the size to a local variable. In addition, this example using pre-increment (++i) results in smaller code than post-increment (i++). The optimized code appears below:

     int size = vector.size();
for(int i = 0; i < style=""> ...
}

Alternatively, if the order in which you iterate over items is not important, you can iterate backward. Iterating backward avoids the extra local on the stack, and the comparison is also faster, as the following example illustrates:

for(int i = vector.size() - 1; i >= 0; --i) {

...

}



Optimizing Subexpressions

If you ever use the same expression twice, do not rely on the compiler to optimize it for you. Use a local variable, as in the following example:

one(i + 1); two(i + 1); // Avoid
int tmp = i + 1; 
one(tmp); 
two(tmp); // Prefer

Avoid java.util.Enumeration
Avoid using java.util.Enumeration unless you are using it to hide data (in other words, returning an Enumeration of data rather than the data itself). The following example shows a typical use of an Enumeration:

for (Enumeration e = v.elements(); e.hasMoreElements();) {
   o = e.nextElement();
   ...
}

Asking a vector or hash table for an Enumeration object creates unnecessary garbage and is slow. Instead, you can iterate over the elements yourself, as in this example:

for(int i = v.size() - 1; i >=0; --i) {
   o = v.elementAt(i);
   ...
}

If the vector might be modified by another thread, you must synchronize the iteration:

synchronized(v) {
   for(int i = v.size() - 1; i >=0; --i) {
      o = v.elementAt(i);
      ...
   }
}

In Java 2 Platform, Standard Edition (J2SE), you would use an Iterator for this, but Iterators are not available in Java 2 Platform, Micro Edition (J2ME).

Returning null
If you are writing a public method that returns an object, it should never return null unless the following occurs:

  • a null is expected during normal program operation.
  • the javadoc @return parameter states that null is a possible return value.

If a null is not normally expected, then the method should throw an appropriate exception, which forces the caller to deal with the problem explicitly. The caller is not expected to check for a null return value, unless the documentation specifies otherwise.

Passing null into Methods
Do not pass null parameters into an API method unless the API Reference documentation explicitly states that the method supports them.

Passing null into a Constructor
To avoid ambiguity when passing a null into a constructor, you should use this form:

new someObject ((Object)null);

A class can have two or more constructors, such as SomeObject(String) and SomeObject(Object), where passing in a null does not identify which constructor to use. As a result, the compiler reports an error. Not all supported constructors necessarily appear in the API Reference documentation, because some constructors are for internal use only. By casting the null to the appropriate object, you indicate precisely which constructor the compiler should use. This practice also ensures forward compatibility if later releases of the API add new constructors.

Optimizing Division Operations
Division operations are slow on the BlackBerry Wireless Handheld because its processor does not have a hardware divide instruction. When you write code that divides a positive number by two, you should use “shift right by one” instead. The following example illustrates this:

midpoint = width / 2; //avoid this
int = width >> 1; //prefer this

This does not work for negative values. Only use “shift right” (>>) when you know you are dealing with a positive value. It does not work for negative values.

Managing Garbage Collection
Avoid calling System.gc() to perform garbage collection. On a full handheld, this could take two seconds. Let the virtual machine (VM) collect garbage automatically.


Casting Using instanceof
It is more efficient to use instanceof instead of classCastException to evaluate whether a cast succeeds. Here is an example of using a try/catch block to catch the classCastException:

try {
   (String)x.whatever();
} catch(ClassCastException e) {
   // something else
}

Alternatively, you can use instanceof operator:

if(x instanceof String) {
   (String)x.whatever();
} else {
   // something else
}

Using instanceof is faster. The only time you should use the try/catch block is when the failure of the cast is an exceptional circumstance. The BlackBerry Java Development Environment (JDE) compiler and the VM are optimized to perform only one class check in the first block of code. This is true of any code in which the cast is run immediately following a branch determined by an instanceof check. Always perform the cast immediately after the branch so that the optimization can be performed.

Using Longs for Unique Identifiers
You should use longs rather than strings for unique constants, such as globally unique identifiers (GUIDs), hash table keys, and state/context identifiers. So that unique identifiers remain unique across all third-party application developers, you should use randomly generated keys based on a hash of some string. In the input string, you should include enough information to make it unique.

Wednesday, December 24, 2008

Pushing Web Content to BlackBerry Wireless Devices

            
            Deploying and enabling a web-based application on a BlackBerry wireless device allows for reduced development time by not creating a BlackBerry application. A Browser Push differs from a BlackBerry client push application as there is no requirement to develop a client to reside on the device. There are four types of Browser Push that can be sent to the BlackBerry wireless device.
  1. Browser Channel Push
  2. Browser Channel Delete Push
  3. Browser Content Cache Push
  4. Browser Message Push

Browser Channel Push


A Browser Channel Push sends a web page and two icons to the BlackBerry wireless device. The web page is stored in the cache of the BlackBerry Browser, and an icon is shown on the home screen of the device. An unread icon can be specified so that when a new Browser Channel Push arrives to the device, it will display the unread icon. After the user has opened and visited the page, the read icon is shown. This provides the user with a visual indication as to when a page has been updated. It's useful for a news service so that users are aware of when new data has arrived. The icons can even change with every push allowing an application to continually push different icons. This would be useful for a weather application updating the current weather conditions.

Browser Channel Delete Push


A Browser Channel Delete works in a similar, but opposite fashion of the Browser Channel Push. It will remove an icon on the BlackBerry Home screen that has been sent via a Browser Channel Push. Icons initiating from a Browser Channel Push can also be removed from the device itself.

Browser Content Cache Push


Browser Content Cache Push is the most discreet type of Browser Push. A Browser Content Push will push a web page to the BlackBerry wireless device and store it in the BlackBerry Browser's cache. The user is not informed in any way when this push takes place, or when the page has been updated.

Browser Message Push


Instead of creating an icon on the home screen of the BlackBerry wireless device, a Browser Message Push will arrive in the Inbox on the device. When the user opens the message, the default browser on the device is launched then opens the page. Unlike the Browser Channel Push or Browser Content Push, the web page is stored as a browser message instead of in the BlackBerry Browser's cache. This means that the page will be available until the message is deleted. It will not be removed from the BlackBerry Browser cache when other events (browsing, cache clear) take place. The message created from a Browser Message Push is not sent to, and will not appear in, a user's Inbox on their desktop. It is sent directly to the device.

How to push


Push applications can be created using any development language that is able to initiate a network connection and perform an HTTP post. A post to the BlackBerry MDS Server handles the delivery of the push to a BlackBerry wireless device. The post is made up of the standard html request headers, a few unique Browser Push headers and the web page being pushed (it is not required to send the web page when performing a Browser Channel Delete Push). The following additional http request headers are required for a Browser Push to take place.

 

Required

X-RIM-Push-Title
X-RIM-Push-Type

Optional

X-RIM-Push-Channel-ID
X-RIM-Push-UnRead-Icon-URL
X-RIM-Push-Read-Icon-URL
 
"The X-Rim-Push-Title" header holds the title that will appear on the home screen of the device for a Browser Channel Push, or in the subject of the message of a Browser Message Push. The "X-RIM-Push-Type" header holds the value that represents the type of push being sent. Possible values are:
  • Browser-Channel
  • Browser-Message
  • Browser-Content
  • Browser-Channel-Delete
The "X- RIM-Push-Channel-ID" header contains the URL of the page to be pushed to the device. This is not required when performing a Browser Message or Browser Content push. The "X-RIM-Push-UnRead-Icon-URL" and "X-RIM-Push-Read-Icon-URL" are optional headers that specify the URL of the icons to be used for a Browser Channel Push. If these are not specified then the default Browser Channel Push icons are used. These two headers are not required for Browser Message, Browser Content or Browser Channel Delete Push and may be omitted.
The page that is to be pushed is submitted once the headers are sent. It is recommended that this page resides on a web server, although it is not required. If it is not located on a web server, a user would be unable to refresh the page. If the page has been removed from the BlackBerry Browser cache (if a Browser Channel or Browser Content Push was used) they would be unable to view it. It is not required to send the actual page when performing a Browser Channel Delete.

Sample Java Push Application

           A sample Java based push application is included and documented with the BlackBerry JDE. The BlackBerry JDE is available in the JDE installation path: “$JDE_HOME$\samples\com\rim\samples\server\httppushdemo”

Sample Php Push Application

A sample php push application can be downloaded from this URL http://na.blackberry.com/eng/devjournals/resources/journals/jan_2005/phpPush.zip