Monday, January 17, 2011

Using image for a TextEditField in Blackberry

Hello all,
 
When i started coding for basic edit field in blackberry i found 
that it is transparent but the look was not exactly that i wanted. 
I wanted a look of TextEditField that appears in websites 
so i tried the below mentioned code. 
May be it can help to any blackberry developer.
 
Here is the code:
 
LabelField label = new LabelField("name");

textbox=new EditField("","",500, 
 EditField.NO_NEWLINE|Field.FOCUSABLE) 
 {
  protected void paint(Graphics g)
   {
     g.setColor(Color.MAROON);
     super.paint(g);
   }
  protected boolean keyChar(char key, int status, int time) 
   {
     return super.keyChar(key, status, time);
   }
 };


 manager = new VerticalFieldManager(HORIZONTAL_SCROLL )
  {
    protected void paint(Graphics g) 
     {
      int x = this.getHorizontalScroll();
      if(textbox.getText().equals(""))
      {
        g.drawBitmap( x, 0, textbox_img.getWidth(), 
           textbox_img.getHeight(),textbox_img, 0, 0 );
      }
     super.paint(g);
   }
}
manager.add(textbox);
 
add(label);
add(manager); 
 
now add this manager in your main screen and see how it looks.
Its even supports horizontal scroll.
  
Look at this:
 
 
  
  
  
 
 
 

Wednesday, January 12, 2011

Adding Menu Items in existing Blackberry Apps

Hello every one,

Sometimes it happens that you want to add your own menu item to the existing blackberry applications.When user clicks menu key in an existing application then a menu item added by you is visible say "Open with myApp" or "import with myApp".

This can be achieved using the ApplicationMenuItemRepository class.
net.rim.blackberry.api.menuitem package, enables you to add menu items to BlackBerry applications.

Features:
1) It enables you to add or remove application menu items.
2) It provides constants that define the contexts in which a menu items can appear.

For example:
The ApplicationMenuItemRepository.MENUITEM_CALENDAR constant specifies that the menu item appears when the calander is open.

In this sample we will invoke calander application by clicking on a button and we can see a new menu item added on the calendar app.

Here you go:

package com.Test;

import java.util.Date;
import javax.microedition.pim.Event;
import net.rim.blackberry.api.invoke.CalendarArguments;
import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.menuitem.ApplicationMenuItem;
import net.rim.blackberry.api.menuitem.ApplicationMenuItemRepository;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

public class ApplicationMenuDemo extends MainScreen
{
    LabelField lbl;
    ApplicationMenuDemo()
    {
        super();
       
        MyMenuItem myMenuitem = new MyMenuItem(0);
        ApplicationMenuItemRepository.getInstance().addMenuItem(
        ApplicationMenuItemRepository.MENUITEM_CALENDAR, myMenuitem);
       
        setTitle("ApplicationMenuItemRepository Demo");
       
        lbl = new LabelField("imported start date will be displayed here");
       
        ButtonField btn = new ButtonField("import from Calendar");
        btn.setChangeListener(listener);
       
        add(new LabelField("",LabelField.NON_FOCUSABLE));
        add(lbl);
        add(new LabelField("",LabelField.NON_FOCUSABLE));
        add(btn);
    }
   
    FieldChangeListener listener = new FieldChangeListener()
    {
        public void fieldChanged(Field field, int context)
        {
          Invoke.invokeApplication(Invoke.APP_TYPE_CALENDAR, new
                 CalendarArguments(CalendarArguments.ARG_VIEW_DEFAULT));
        }
    };
   
     class MyMenuItem extends ApplicationMenuItem
        {
            String text;
            MyMenuItem(int order)
            {
                super(order);
            }

            public Object run(Object context)
            {
                if (context instanceof Event)
                {
                    Event event = (Event) context;
                   
                    Date date = new Date((event.getDate(Event.START, 0)));
                                       
                    lbl.setText(date.toString());
                }
                return context;
            }

            public String toString()
            {
                return "Import Calander Date";
            }
        }
}
See how it looks:

 

 




link for api details:

http://www.blackberry.com/developers/docs/4.0.2api/index.html
Enjoy coding :)

Tuesday, January 11, 2011

Ads Service in Blackberry

Hello

Working with Ads Service in Blackberry is really great and new experience for those who haven't worked on iAds in iPhone.
I have gathered some information that i would like to share with all and may be some where somebody can be helped by it.

Advertisements rule the world...Keeping this in mind Blackberry platform provides you the capability to display ads in your Blackberry Device Application. Many of you must have seen such feature in iPhone Apps where ads are called as iAds.

To sign up for the Advertising Service, visit adservice.blackberry.com/register/




Using the Advertising Service SDK:

1) For each application that you integrate ads into, you need a unique instance of the Advertising Service SDK.

2) If you have multiple applications in which you want to display ads, you must register each application with Research In Motion separately.

3) Each application that you register, RIM sends you a new SDK which is identified by a unique package ID.

4) To use the Advertising Service API in an application, you have to add the .jar file for the Advertising Service API to the build path of a BlackBerry application project,after this develop and package the application, and distribute the application .cod file with the .cod file that contains the Advertising Service API.

System requirements

• BlackBerry® Java® Plug-in for Eclipse® 1.1 or later with the BlackBerry Java SDK 4.5 - 5.0.
"The Advertising Service does not yet fully support BlackBerry® Device Software 6.0."

• BlackBerry® Java® Development Environment 4.5 or later

• BlackBerry® Email and MDS Services Simulator Package 4.1.2 or later


How to move ahead:

1) RIM send you two zipped files that you need to unzip

BlackBerrySDK_app<package_ID>._Desktop

BlackBerrySDK_app<package_ID>._OTA

2) When you unzip them you can find many folders that contains the alx, cod, jad, jar files for different versions.

Files contained:
net_rim_bbapi_adv_<package_ID>.alx

net_rim_bbapi_adv_<package_ID>.cod

net_rim_bbapi_adv_<package_ID>.jad

net_rim_bbapi_adv_<package_ID>.jar


3) To add the .jar file of the Advertising Service API to your BlackBerry application Project :

Create a BlackBerry application project:

1. In Eclipse, in the Package/Project Explorer view, right-click the project that you want to add the .jar file to.
2. Click Build Path > Configure Build Path.
3. Click the Libraries tab.
4. Click Add External JARS if the .jar file is not in the current workspace (Prefer to add the jar file of particular version in your src folder).
5. Double-click net_rim_bbapi_adv_<package_ID>.jar to add the .jar file to the project.
7. Click OK.

Note: This itself doesn’t completes the task, you must also load the .cod file for the Advertising Service API on a BlackBerry device or in the BlackBerry Smartphone Simulator before an application can run.It would be a better option if you place the cod file in the simulators directory.

Ads Display Size
The Advertising Service supports the following sizes of ads, in pixels:
• 320 x 53 (required size for rich media ads)
• 216 x 36
• 168 x 28
• 120 x 20

Namespace:

import net.rim.blackberry.api.advertising.<package_ID>.Banner;

Here you go

package com.Test;

import net.rim.blackberry.api.advertising.appXXXXX.Banner;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
class Ads extends UiApplication
{
    public static void main(String[] args)
     { 
       Ads theApp = new Ads();
       theApp.enterEventDispatcher();
     }
    public Ads()
     {
        pushScreen(new AdDemoScreen());
     }

 class AdDemoScreen extends MainScreen
   {
      public AdDemoScreen()
       {
          Banner bannerAd = new Banner(placementId, null);
          bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
         add(bannerAd);
       }
   }
 }

How to send Meta data with Ads:

import net.rim.blackberry.api.advertising.<package_ID>.Banner;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import java.util.Hashtable;

  public class Ads extends UiApplication
   {
      public static void main(String[] args)
       {
         Ads theApp = new AdDemo();
         theApp.enterEventDispatcher();
       }
    public Ads()
    {
       pushScreen(new AdsScreen());
     }
  }
 class AdsScreen extends MainScreen
  {
     public AdsScreen()
     {
        Hashtable metadata = new Hashtable();
        metadata.put("age", "61");
        metadata.put("gender", "female");

        Banner bannerAd = new Banner(placement_Id, metadata);
        bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
        add(bannerAd);
     }
 }

package_ID : (appXXXXX) You can see this number on the files that RIM send you.(net_rim_bbapi_adv_appXXXXX.jar).

placement_Id : When RIM sends you the files they also send some credentials containing placement_id

Package a BlackBerry application project
1. In Package Explorer view, right-click a BlackBerry project.
2. Click BlackBerry > Package Project(s).
The Console view displays the progress of packaging.


Run an application that displays ads on a device
1. Connect a BlackBerry device to a computer with a USB cable.
2. Oopen Command prompt.
3. At the command prompt, type cd <location_of_application_deliverable_files> and press Enter.
4. At the command prompt, type javaloader -u load <my_jad_file.jad> and press Enter to load the .jad file for the application on the BlackBerry device.
6. On the Home screen of the device, navigate to and click the application icon.

Customizing the appearance and behavior of the display area for an ad

1) setMMASize() : Sets the size of the Banner object.

1) If your application runs on a BlackBerry Device Software version earlier
than 5.0 so use setMMASize().

2) If your application runs on BlackBerry Device Software 5.0, and you do not set the size in the application code, the Banner object resizes itself automatically to match the size of the ad that the mediation layer returns.

If you set a size that is different from the one that you specify when you register your application, the server-side value overrides the size that you set in the application, potentially causing ads to display incorrectly.


bannerAd.setMMASize(Banner.MMA_SIZE_EXTRA_LARGE);
Other Options for size:

Banner.MMA_SIZE_EXTRA_SMALL

Banner.MMA_SIZE_EXTRA_MEDIUM

Banner.MMA_SIZE_EXTRA_LARGE

Banner.MMA_SIZE_EXTRA_AUTO


2) Transition effect - The application by default displays a black transition effect between 2 ads.You can call this as fade in and fade out.

bannerAd.enableBannerTransition(false) – To turn off the transition effect
bannerAd. setBannerTransitionColor(Color.RED) - To specify a transition color that is supported by the Color class in the BlackBerry® Java® SDK.


3) Focus behavior- The application by default displays a blue border around the ad By default, when a user selects an ad.

bannerAd setBorderColor(Color.BLACK) - To specify a focus color that is supported by the Color class in the BlackBerry® Java® SDK.

bannerAd.setFocusOverrideFlag(true) – To prevent the Advertising Service API from handling focus behavior.


4) Placeholder image - Tthe application by default displays a transparent placeholder image with a border when ad service is waiting for an ad. You can customize the placeholder image, you can create a Bitmap object and pass it to the constructor for a Banner object as a parameter.

If you create your own placeholder image, verify that it has the same dimensions as the ads that
your application receives.

Bitmap customPlaceholder = Bitmap.getBitmapResource("Ad_placeholder.png");

Banner bannerAd = new Banner(placementId, null, 100000, customPlaceholder);

Enjoy Coding!!!!!!!!!!!

:)

How to create a Custom Button Field in Blackberry

Hello all,
This is my first blog.I will be happy if it can help blackberry developers in any way.

Custom Buttons :  Blackberry supports buttons that a very simple yet use full which is by default dark grey in color and when it gets focus then it appears in blue color.

Most of the time we want to create apps or projects with a wide variety of graphics in it that can appeal the user.

For this purpose we can create our own custom buttons and apply focusable and non focusable images on it.Moreover we can also add text to it.

Here u go:

package com.MyProject;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;

public class CustomButtonField extends Field
{
    Bitmap Unfocus_img, Focus_img, current_pic;
    int width;
    String text;
    Font font;   
    CustomButtonField(int width, String text, Bitmap onFocus, Bitmap onUnfocus, long style)
    {
        super(style);
        Unfocus_img = onUnfocus;
        Focus_img = onFocus;
        current_pic = onFocus;
        this.text = text;
        this.width = width;
    }
    protected void layout(int width, int height)
    {
        setExtent(current_pic.getWidth(), current_pic.getHeight());       
    }
    protected void paint(Graphics graphics)
    {
        try
        {
                FontFamily fntFamily = FontFamily.forName("BBAlpha Sans");
                font = fntFamily.getFont(Font.BOLD,14);             
        }
        catch(Exception e)
        {
            font = Font.getDefault();
         
        }
        graphics.setFont(font);
        graphics.setColor(Color.WHITE);
        graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic, 0, 0);
        graphics.drawText(text, width, 7);
    }
    protected void onFocus(int direction)
    {
        super.onFocus(direction);
        current_pic = Unfocus_img;
        this.invalidate();
    }
  protected void drawFocus(Graphics graphics, boolean on)
  {
       
    }
    protected void onUnfocus()
    {
        super.onUnfocus();
        current_pic = Focus_img;
        invalidate();
    }
    public boolean isFocusable() {
        return true;
    }
    protected boolean navigationClick(int status, int time) {
        fieldChangeNotify(0);
        return true;
    }
}


And this is how u can use it:
Bitmap focus = Bitmap.getBitmapResource("printButton_focus.png");
Bitmap unfocus = Bitmap.getBitmapResource("printButton_unfocus.png");
           
Bitmap focus1 = Bitmap.getBitmapResource("button-highlight.png");Bitmap unfocus1 = Bitmap.getBitmapResource("button.png");
           
 ButtonField obj = new ButtonField("Button");
 CustomButtonField button1 = new CustomButtonField(0,"",unfocus,focus,Field.FOCUSABLE);
 CustomButtonField button2 = new CustomButtonField(25,"Next",unfocus1,focus1,Field.FOCUSABLE);
           
 add(obj);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button1);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button2);


Result of three added buttons depending upon the argument
Unfocus  

Focus    

Unfocus 
   
Focus    

Unfocus

Focus   


Thank you to all those who helped me!!!!

How to programatically animate a gif in blackberry

Hello,

I have searched a lot and found many posts that helped me.I mixed them all to make it of my use.
So first of all thanks to those who helped me in achieving this task.
When i firstly tried to add a gif file i added it as a bitmap field to my screen but it appeared as an static image without any motion of frames.
The post mentioned below may be can help people who want to animate their GIF's

Here you go:



Animate gif image in blackberry

package com.Test;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;     

      public class AnimatedGIFField extends BitmapField
      {
          private GIFEncodedImage encoded_image;     //The image to draw.
          private int current_frame;          //The current frame
          private AnimatorThread animator_thread;      

          public AnimatedGIFField(GIFEncodedImage image)
          {
              this(image, 0);
          }
          public AnimatedGIFField(GIFEncodedImage image, long style)
          {      
             super(image.getBitmap(), style);
              encoded_image = image;         

              //Start the thread for animation.
              animator_thread = new AnimatorThread(this);
              animator_thread.start();
          }
          protected void paint(Graphics g)
          {
              super.paint(g);      

              //Don't redraw the background if this is the first frame of the GIF
              if (current_frame != 0)
              {
                  //Draw the animation frame.

                  g.drawImage(encoded_image.getFrameLeft(current_frame),
                  encoded_image.getFrameTop(current_frame),
                  encoded_image.getFrameWidth(current_frame),
                  encoded_image.getFrameHeight(current_frame),
                  encoded_image, current_frame, 0, 0);
              }
          }      

          //Stop the animation thread when the screen the field is on is
          //pop off of the display stack.

          protected void onUndisplay()
          {
              animator_thread.stop();
              super.onUndisplay();
          }

          //A thread to handle the animation.

          private class AnimatorThread extends Thread
          {
              private AnimatedGIFField _theField;
              private boolean continue_movement = true;
              private int total_frames;     //The total number of frames in the image.
              private int count;       //The number of times the animation has looped (completed).
              private int total_loops;      //The number of times the animation should loop (set in the image).      

              public AnimatorThread(AnimatedGIFField theField)
              {
                  _theField = theField;
                  total_frames = encoded_image.getFrameCount();
                  total_loops = encoded_image.getIterations();
              }
              public synchronized void stop()
              {
                  continue_movement= false;
              }
              public void run()
              {
                  while(continue_movement)
                  {
                      UiApplication.getUiApplication().invokeAndWait(new Runnable()
                      {
                          public void run()
                          {
                              _theField.invalidate(); // for repainting
                          }
                      });      

                      try
                      {
                          //put current frame in sleep mode before another frame is redrawn
                          sleep(encoded_image.getFrameDelay(current_frame) * 10);
                      }
                      catch (InterruptedException iex){}        

                      //Increment the frame.
                      ++current_frame;      

                      if (current_frame == total_frames)
                      {
                          //Reset back to frame 0 if we have reached the end.
                          current_frame = 0;
                          ++count;      

                          //Check if the animation should continue.

                          if (count == total_loops)
                          {
                              continue_movement= false;
                          }
                      }
                  }
              }
          }
}


How to call above class

GIFEncodedImage image;
EncodedImage encodedImage;
AnimatedGIFField animatedGIF;
 
encodedImage = EncodedImage.getEncodedImageResource("Share.gif");
byte data[] = new byte[4000];
data = encodedImage.getData();
image =(GIFEncodedImage) EncodedImage.createEncodedImage(data,0,data.length);
animatedGIF = new AnimatedGIFField(image);         
add(animatedGIF);          


Highly thankful to those posts that helped me in building this