Search This Blog

Tuesday, 19 June 2012

Issue when retrieving image from Server or network in Blackberry App

Hello Friends,
                       This thing made me frustrated for many days and then i found something very stupid thing hehehehe......had you ever face such a probllem that you know tht the image you want to use is on server but your app is unable to fetch tht image , this happens many a times ,like you are fetching multiple images but you found that some of them returned null......the problem is that  server admin named tht image with a space for ex : "red rose.jpg",here a space is there in image name , and whenever we want to fetch image we should switch this space with "%20" , you can easily do when you have only one image,but what will you do when the images are dynamic , you dont know the exact number of images and you dont know how many of them contains space in their names??? Here it is a function which will automatically replace the space with "%20".so you just need to use a for loop , and pass every single url of image to this function and it will replace the space with "%20" if found.....problem solved...

CODE:

public static String escapeHTML(String s){
    StringBuffer sb = new StringBuffer();
    int n = s.length();
       for (int i = 0; i < n; i++) {
          char c = s.charAt(i);
          switch (c) {
             case ' ': sb.append("%20"); break;
             default:  sb.append(c); break;
        }
    }
    return sb.toString();
}


How to use this function :

Suppose you have a url in string variable _image;

_image = "http:\\111.111.111.111\images\red rose.jpg";

Do this .....

String _str=escapeHTML(_image);

Friday, 15 June 2012

Another UI with header and Tab for Blackberry

Hello friends,
                     Here is the approach which you sometime needs when making some entertainment app or when you need to show data ina listfield and wants to make that looking awesome....

This contains the header, then comes the data space , you can add anything to this manager like list or any thing you want buttons etc... and bottom is the tab with icons to navigate the user on other screens....

you just need to copy paste this whole code its a complete screen code...

for resize function please look my previous post ....

CODE:


package mypackage;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.image.Image;
import net.rim.device.api.ui.image.ImageFactory;
import net.rim.device.api.ui.toolbar.ToolbarButtonField;
import net.rim.device.api.ui.toolbar.ToolbarManager;
import net.rim.device.api.util.StringProvider;


public final class MyScreen extends MainScreen
{
   int _width,_height;
    public MyScreen()
    {       
        _width = Display.getWidth();
        _height = Display.getHeight();

        Background _black = BackgroundFactory.createLinearGradientBackground(Color.BLACK,Color.BLACK
                ,Color.BLACK,Color.BLACK);
       
    VerticalFieldManager _master = new VerticalFieldManager(){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    _master.setBackground(_black);
   
    HorizontalFieldManager _header = new HorizontalFieldManager(){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/6;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
   
    Background _headerBack = BackgroundFactory.createBitmapBackground(MyApp.resize("HeaderAutumn1.jpg", _width, _height/5));
    _header.setBackground(_headerBack);
   
    VerticalFieldManager _dataController = new VerticalFieldManager(Manager.VERTICAL_SCROLL){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height-(_height/6)-(_height/10);
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
   
    _dataController.setBackground(_black);
   
   
    ToolbarManager _manager = new ToolbarManager(){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/10;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
   
    Image _homeI = ImageFactory.createImage(MyApp.resize("home.png", 62, 62));
    Image _favI = ImageFactory.createImage(MyApp.resize("Favorites-icon.png", 62,62));
    Image _webI = ImageFactory.createImage(MyApp.resize("Web-icon.png", 62,62));
   
    ToolbarButtonField _home = new ToolbarButtonField(_homeI,new StringProvider("Home"));
    ToolbarButtonField _fav = new ToolbarButtonField(_favI,new StringProvider("Favourites"));
    ToolbarButtonField _web = new ToolbarButtonField(_webI,new StringProvider("Web"));
   
    _manager.add(_home);
    _manager.add(_fav);
    _manager.add(_web);
   
    this.add(_master);
    _master.add(_header);
    _master.add(_dataController);
    _master.add(_manager);
   
    }
    public boolean onClose(){
    int st = Dialog.ask(Dialog.D_YES_NO,"Are you sure ?");
    if(st==Dialog.YES){
        System.exit(1);
    }else{
    return false;
    }
    return false;
    }
}




How to display a dialog with yes and no option on close

Hello friends,
                     Still following those bulky confusing tutorials to just display a simple Dialog box for confirmation??? Here it is , i found it yesterday and tried it ...it works....

CODE:

suppose you have a screen and on back button click you want to ask the user if he is sure or not....

so override the onClose function like this...


public boolean onClose(){
    int st = Dialog.ask(Dialog.D_YES_NO,"Are you Sure?");
   if(st==Dialog.YES){
      System.exit(1);
      return true;
     }    
     return false;
}



Thursday, 14 June 2012

Create a Unique UI to manage thousands of images on single screen in blackberry

Hello friends ,
                      Here is the UI , i designed for Blackberry,Actually was free and dint have any idea wht to do ....so i did this its just an idea may be it will be of lil helpful in your app.....
See the image below.....every single Horizontal Manager is scrollable you can add as many images as u want ...
CODE:
package mypackage;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;


public final class MyScreen extends MainScreen
{
   int _width,_height;
    public MyScreen()
    {       
        _width = Display.getWidth();
        _height = Display.getHeight();
       
        Background _black = BackgroundFactory.createLinearGradientBackground(Color.BLACK,Color.BLACK,Color.BLACK,Color.BLACK);
    VerticalFieldManager _master = new VerticalFieldManager(){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    _master.setBackground(_black);
    this.add(_master);
    HorizontalFieldManager _first = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/4;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    HorizontalFieldManager _second = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/4;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    HorizontalFieldManager _third = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/4;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    HorizontalFieldManager _fourth = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL){
        public int getPreferredWidth(){
            return _width;
        }
        public int getPreferredHeight(){
            return _height/4;
        }
        public void sublayout(int maxWidth,int maxHeight){
            super.sublayout(getPreferredWidth(), getPreferredHeight());
            setExtent(getPreferredWidth(),getPreferredHeight());
        }
    };
    Background _gradient = BackgroundFactory.createLinearGradientBackground(Color.GRAY,Color.GRAY,Color.BLACK,Color.BLACK);
    _first.setBackground(_gradient);
    _second.setBackground(_gradient);
    _third.setBackground(_gradient);
    _fourth.setBackground(_gradient);
    BitmapField one = new BitmapField(MyApp.resize("1.jpg", _width/3,_height/4-10));
    one.setMargin(5,0,0,10);
    BitmapField two = new BitmapField(MyApp.resize("2.jpg", _width/3,_height/4-10));
    two.setMargin(5,0,0,10);
    BitmapField three = new BitmapField(MyApp.resize("3.jpg", _width/3,_height/4-10));
    three.setMargin(5,0,0,10);
    BitmapField four = new BitmapField(MyApp.resize("4.jpg", _width/3,_height/4-10));
    four.setMargin(5,0,0,10);
    BitmapField five = new BitmapField(MyApp.resize("5.jpg", _width/3,_height/4-10));
    five.setMargin(5,0,0,10);
    BitmapField six = new BitmapField(MyApp.resize("6.jpg", _width/3,_height/4-10));
    six.setMargin(5,0,0,10);
    BitmapField seven = new BitmapField(MyApp.resize("7.jpg", _width/3,_height/4-10));
    seven.setMargin(5,0,0,10);
    BitmapField eight = new BitmapField(MyApp.resize("8.jpg", _width/3,_height/4-10));
    eight.setMargin(5,0,0,10);
    BitmapField nine = new BitmapField(MyApp.resize("9.jpg", _width/3,_height/4-10));
    nine.setMargin(5,0,0,10);
    BitmapField ten = new BitmapField(MyApp.resize("10.JPG", _width/3,_height/4-10));
    ten.setMargin(5,0,0,10);
    BitmapField eleven = new BitmapField(MyApp.resize("11.jpg", _width/3,_height/4-10));
    eleven.setMargin(5,0,0,10);
    BitmapField twelve = new BitmapField(MyApp.resize("12.jpg", _width/3,_height/4-10));
    twelve.setMargin(5,0,0,10);
    BitmapField thirteen = new BitmapField(MyApp.resize("13.jpg", _width/3,_height/4-10));
    thirteen.setMargin(5,0,0,10);
    BitmapField fourteen = new BitmapField(MyApp.resize("14.jpg", _width/3,_height/4-10));
    fourteen.setMargin(5,0,0,10);
    BitmapField fifteen = new BitmapField(MyApp.resize("15.jpg", _width/3,_height/4-10));
    fifteen.setMargin(5,0,0,10);
    BitmapField sixteen = new BitmapField(MyApp.resize("16.jpg", _width/3,_height/4-10));
    sixteen.setMargin(5,0,0,10);
    _first.add(one);
    _first.add(two);
    _first.add(three);
    _first.add(four);
    _second.add(five);
    _second.add(six);
    _second.add(seven);
    _second.add(eight);
    _third.add(nine);
    _third.add(ten);
    _third.add(eleven);
    _third.add(twelve);
    _fourth.add(thirteen);
    _fourth.add(fourteen);
    _fourth.add(fifteen);
    _fourth.add(sixteen);
    _master.add(new SeparatorField());
    _master.add(_first);
    _master.add(new SeparatorField());
    _master.add(_second);
    _master.add(new SeparatorField());
    _master.add(_third);
    _master.add(new SeparatorField());
    _master.add(_fourth);
    _master.add(new SeparatorField());
    }
}


How to get touchevent on any field in Blackberry.

Hello friends,
                     Here is something interesting , what if you wana use some icons in your app and want to do something on click like for simplicity change that icon on click ....here it is a simple code...

Code:

Suppose we have a png image in res folder with the name 'abc.png'

So, first we initialize and declare a BitmapField...

Bitmap _icon = Bitmap.getBitmapResource("abc.png");
Bitmap _iconClick = Bitmap.getBitmapResource("abcClick.png");
BitmapField _icon1 = new BitmapField(_icon){
//Now we do something on Click on this BitmapField

public boolean touchEvent(TouchEvent message){
    if(message.getEvent()==TouchEvent.CLICK){
       //Do something on click here

       //Change the icon on Click
       this.setBitmap(_iconClick);
       return true;
   }

return false;
}
};



How to handle the Back button event in Blackberry

Hello fellas,
              Wana do something on Backbutton click in your app??? like sending the app in background ,if in case you want your app always running.Here it is , as easy as 1 2 3 ...follow the code...

Code:

What you need to do is Override the 'onClose' method of that particular screen, like the main screen of your app....


public boolean onClose(){
//Do something on back button click
return true;
}


Now , suppose you want that your app should go in background and keep running on back button Click....Follow the Code...

public boolean onClose(){
UiApplication.getUiApplication.requestBackground();
return true;
}

Wednesday, 13 June 2012

How to use MessageListener in Blackberry

Hello friends,
               Sorry for not posting as i am not doing any development from last few days.Here it is a very much simple thing ,using message listener in Blackberry and doing some task on incoming message.

Code:
public final class MyScreen extends MainScreen implements MessageListener
{
   
    public MyScreen()
    {       
      
       
    }

    public void onMessage(Destination arg0, Message arg1) {
        System.out.println("OnMessage Countered.");
       
       
    }

    public void onMessageCancelled(Destination destination,
            int cancelledMessageId) {
        System.out.println("On message Cancelled Countered.");
       
    }

    public void onMessageFailed(Destination destination,
            MessageFailureException exception) {
        System.out.println("On Message Failed Countered.");
       
    }
    public boolean onClose(){
        UiApplication.getUiApplication().requestBackground();
        return true;
    }
}

Monday, 4 June 2012

How to make a call from your Blackberry App

Hello Friends,
                     Do you ever wanted to make a call from your app , whether automatically or on button click?It is useful when you are working with security apps...So here is the simple one line code ....

CODE:
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, 
new PhoneArguments(PhoneArguments.ARG_CALL, phoneNumber));

How to add a MenuItem in Blackberry App

Hello friends,
 Here is the simple one , how you can add a menuitem in your app menu .......

CODE:

Initialize :
MenuItem _currentPlayingM = new MenuItem(new StringProvider("Currently Playing"),0,1);


Do something on Click on MenuItem....:
_currentPlayingM.setCommand(new Command(new CommandHandler(){
            public void execute(ReadOnlyCommandMetadata arg0, Object arg1) {
     //Do something on click on menuItem                     

 }
        }));

this.addMenuItem(_currentPlayingM);



Saturday, 2 June 2012

Make your app talkative,by using speech for messages

Hello friends,
                   Still using those old style Dialog box for giving message , or showing error in your app???.....Old school Out! here it is make your app play verbal messages on any event you want....follow the code...
And yes use this link to convert text into voice...http://www2.research.att.com/~ttsweb/tts/demo.php


CODE:

Copy your wave file that you get from this link....into res folder of your app.

Now, just do this as below.....

try {
                     
                    InputStream stream = (InputStream)this.getClass().getResourceAsStream("/messagesent.wav");
                   
                    Player p = javax.microedition.media.Manager.createPlayer(stream,"audio/wav");
                    p.realize();
                    VolumeControl _volume = (VolumeControl)p.getControl("VolumeControl");
                    _volume.setLevel(100);
                    p.prefetch();
                    p.start();
                } catch (IOException e) {
                    System.out.println("Error :"+e.toString());
                    e.printStackTrace();
                } catch (MediaException e) {
                    System.out.println("Error :"+e.toString());
                    e.printStackTrace();
                }


BINGO!!! its done and ready to roll....see your app is saying something to you....

Friday, 1 June 2012

How to convert string into integer value in java or in Blackberry development...

Hello friends ,
                   This one is not so big issue but some how i was getting my app strucked because of this stupid thing, as in my previous post i told you hoe to use Persistent store ....same thing i was doing but,it gives me error once in a while ...and what i found is that i was using String variable , i dont know what's the problem with that but......ok i converted it into integer and sharing that thing with you nothing big to share actually :P

CODE:

Suppose we have a string variable _str with some value:

int _status  = Integer.parseInt(_str);

Thats it , the String value is converted into integer value

How to get image from server and show it on Blackberry device

Hello friends,
                   No explanations , just copy and use this function to get the image from server and display.....

CODE:

 public static Bitmap connectServerForImage(String url) {
        HttpConnection httpConnection = null;
        DataOutputStream httpDataOutput = null;
        InputStream httpInput = null;
        int rc;
        String ConnParameter="";
        
        if(WLANInfo.getWLANState()==WLANInfo.WLAN_STATE_CONNECTED){
            ConnParameter = ";interface=wifi";
        }else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
            String carrierUid = getCarrierBIBSUid();
            if(carrierUid == null)
            {
                // Has carrier coverage, but not BIBS.  So use the carrier's TCP network
//                logMessage("No Uid");
                ConnParameter = ";deviceside=true";
            }
            else
            {
                // otherwise, use the Uid to construct a valid carrier BIBS request
//                logMessage("uid is: " + carrierUid);
                ConnParameter = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
            }
       
           
        }else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
        {
//            logMessage("MDS coverage found");
             ConnParameter = ";deviceside=false";
        }
       
        Bitmap bitmp = null;
        try {
            httpConnection = (HttpConnection) Connector.open(url+ConnParameter);
            rc = httpConnection.getResponseCode();
            if (rc != HttpConnection.HTTP_OK) {
                throw new IOException("HTTP response code: " + rc);
            }
            httpInput = httpConnection.openInputStream();
            InputStream inp = httpInput;
            byte[] b = IOUtilities.streamToBytes(inp);
            EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
            int currentWidthFixed32 = Fixed32.toFP(hai.getWidth());
            int currentHeightFixed32 = Fixed32.toFP(hai.getHeight());
            int reqWidthStandard = Display.getWidth();
            int reqWidth = reqWidthStandard;
            int reqHeight = Display.getHeight()/2;
            int requiredWidthFixed32 = Fixed32.toFP(reqWidth);
            int requiredHeightFixed32 = Fixed32.toFP(reqHeight);
            int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
            int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
            hai = hai.scaleImage32(scaleXFixed32, scaleYFixed32);
            bitmp= hai.getBitmap();

        
            } catch (Exception ex) {
                System.out.println("URL Bitmap Error........" + ex.getMessage());
            } finally {
                try {
                    if (httpInput != null)
                        httpInput.close();
                    if (httpDataOutput != null)
                        httpDataOutput.close();
                    if (httpConnection != null)
                        httpConnection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bitmp;
            }

  

How to convert byte array into image in blackberry development

Hello friends,
                   As in my previous post i showed you how to get an image by integrating camera in your app,you were getting that image in byte array, now here is the code to convert it into Bitmap....follow the code

CODE:
Suppose you have a byte array _rawImage....

EncodedImage hai = EncodedImage.createEncodedImage(_rawImage, 0, _rawImage.length);


now simply ,create a Bitmap object and use getBitmap function of EncodedImage class...

Bitmap _finalImage = hai.getBitmap();

How to integrate camera in your Blackberry app

Hello friends,
                  Till today afternoon, i was wondering how can i integrate camera in my app to take picture and send it to server....then i get it.....follow the code,and you still need to do some work as this will return the captured image in byte array , after that you have to convert it into an image....

CODE:

import javax.microedition.media.Player;
import net.rim.device.api.ui.Field;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;


Player camera;
VidepControl _videoControl;

try{
            camera = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
            camera.realize();
            _videoControl = (VideoControl)camera.getControl("VideoControl");
            if(_videoControl!=null){
                Field videoField = (Field)_videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
                _videoControl.setDisplayFullScreen(true);
                _videoControl.setVisible(true);
               
                camera.start();
               
//                EnhancedFocusControl efc = (EnhancedFocusControl)camera.getControl("net.rim.device.api.amms.control.camera.EnhancedFocusControl");
//                efc.startAutoFocus();
               
                if(videoField!=null){
                    _main.add(videoField);
                }else{
                    Dialog.alert("Video Field is null");
                }
            }else{
                Dialog.alert("Video Control is null");
            }
        }catch(Exception e){
           
            Dialog.alert("Error Found :"+e.toString());
        }


Then use this below function to get snapshot on click on touchscreen,touchpad or trackball....

protected boolean invokeAction(int action)
    {
        boolean handled = super.invokeAction(action);
   
        if(!handled)
        {
            if(action == ACTION_INVOKE)
            {  
                try
                {                     
                    byte[] rawImage = _videoControl.getSnapshot(null);  
                    System.out.println("Capturedddddd.......: "+rawImage.length);
                }
                catch(Exception e)
                {
                    Dialog.alert(e.toString());
                }
            }
        }          
        return handled;               
    }