Tag: PopupScreen

Implement Switch Application

this is how to implement “switch application” [1]

Well here is the code:

In all your Screens makeMenu method, add this:
if(instance == 0) // Full Menu
menu.add(new SwitchApplicationMenuItem());

Now create the following file, and add it to your project.


/*
* SwitchApplicationMenuItem.java
*
* Created by Lionscribe based on code from dangihitesh
* Free for anyone to use.
*/

package ;

import net.rim.device.api.system.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;


/**
*
*/
class SwitchApplicationMenuItem extends MenuItem
{
ApplicationManager _appm;
PopupScreen _pop;
LabelField _appname;
static boolean _colorSupported = Graphics.isColor();

public SwitchApplicationMenuItem()
{
super("Switch Application", 268501007, 268501007); // 268501007 comes right before the Close (0x10010010) Menu
}

private final class ApplicationIconField extends BitmapField
{
private Bitmap _icon;
private String _name;
private int _pcid;
ApplicationIconField(ApplicationDescriptor appdescriptor)
{
super(appdescriptor.getIcon(), Field.FOCUSABLE);
_icon = appdescriptor.getIcon();
if (_icon == null) // Just for safety
_icon = Bitmap.getPredefinedBitmap(Bitmap.QUESTION);
_name = appdescriptor.getName();
if (_name.length() >= 2 && _name.charAt(1) == 0x0332) // remove underscores
{
StringBuffer temp = new StringBuffer(_name);
temp.deleteCharAt(1);
_name = temp.toString();
}
_pcid = _appm.getProcessId(appdescriptor);
setSpace(10, 3);
}

protected void paint(Graphics graphics)
{
int x, y, width, height, iconWidth, iconHeight, xOffset, yOffset;
width = getContentWidth();
height = getContentHeight();
iconWidth = _icon.getWidth();
iconHeight = _icon.getHeight();
if (iconWidth <= width)
{
x = (width - iconWidth) / 2;
xOffset = 0;
}
else
{
x = 0;
xOffset = (iconWidth - width) / 2;
iconWidth = width;
}

if (iconHeight <= height)
{
y = (height - iconHeight) / 2;
yOffset = 0;
}
else
{
y = 0;
yOffset = (iconHeight - height) / 2;
iconHeight = height;
}
if (_colorSupported && this.isFocus())
{
int circleSize = Math.min(iconHeight, iconWidth);
int maxSize = Math.min(height, width);
if (circleSize < maxSize)
circleSize = Math.min(maxSize, circleSize + ((maxSize - circleSize) / 2));
else
circleSize = maxSize;
graphics.setColor(Color.YELLOW);
graphics.fillRoundRect((width - circleSize) / 2, (height - circleSize) / 2, circleSize, circleSize, circleSize, circleSize); // circle
}
if (_colorSupported && _icon.getBitsPerPixel() == 1) // add some color to Mono images
{
graphics.setColor(Color.DARKBLUE);
graphics.rop(Graphics.ROP_SRCMONOEXPAND_ALPHA, x, y, iconWidth, iconHeight, _icon, xOffset, yOffset);
}
else
{
graphics.drawBitmap(x, y, iconWidth, iconHeight, _icon, xOffset, yOffset);
}
}

protected void drawFocus(Graphics graphics, boolean on)
{
if (!_colorSupported)
super.drawFocus(graphics, on);
// else - Do nothing. We handle it already in Paint
}

protected boolean trackwheelClick(int status, int time)
{
HandleSelect();
return true;
}

protected boolean keyChar(char key, int status, int time)
{
if (key == '\n')
{
HandleSelect();
return true;
}
return super.keyChar(key, status, time);
}

public void HandleSelect()
{
_pop.close();
_appm.requestForeground(_pcid);
}
protected void onFocus(int direction)
{
super.onFocus(direction);
_appname.setText(_name);
}
public int getPreferredHeight()
{
return 48;
}
public int getPreferredWidth()
{
return 48;
}
}

public void run()
{
try
{
_appm = ApplicationManager.getApplicationManager();
ApplicationDescriptor [] appdes = _appm.getVisibleApplications();
int tot_app = appdes.length;
VerticalFieldManager vfm = new VerticalFieldManager();
HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL);
ApplicationIconField focusField = null;
for (int i = 0; i < tot_app; i++)
{
ApplicationIconField iconField = new ApplicationIconField(appdes[i]);
hfm.add(iconField);
if (i <= 1) // We want the second one, if it exists
focusField = iconField;
}
vfm.add(hfm);
_appname = new LabelField(" ",Field.NON_FOCUSABLE);
vfm.add(_appname);

_pop = new PopupScreen(vfm, PopupScreen.DEFAULT_CLOSE);
UiApplication.getUiApplication().pushScreen(_pop);
focusField.setFocus();

}
catch (Exception e)
{
System.out.println("Error from Switch Application:" + e);
}

}

}

[1] http://www.blackberryforums.com/developer-forum/114028-how-implement-switch-application-menu-item.html


file selection popup screen

this is how to create a file selection popup screen

/*
 * FileSelectorPopupSample.java
 *
 * © Research In Motion, 2003-2009
 * Confidential and proprietary.
 */

package com.samples.fileSelectorPopup;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.MenuItem;
import java.lang.String;

/**
 * A sample application demonstrating the use of a custom
 * FileSelectorPopupScreen.
 */

public final class FileSelectorPopupSample extends UiApplication
{
    public static void main(String[] args)
    {
        FileSelectorPopupSample theApp = new FileSelectorPopupSample();
        theApp.enterEventDispatcher();
    }

    public FileSelectorPopupSample()
    {
        MainScreen mainScreen = new MainScreen();
        mainScreen.setTitle("FileSelectorPopupScreen Example");

        MenuItem showAllMenu = new MenuItem("Select a File", 40, 40)
        {
            public void run()
            {
                FileSelectorPopupScreen fps = new FileSelectorPopupScreen();
                fps.pickFile();
                String theFile = fps.getFile();

                if (theFile == null)
                {
                    Dialog.alert("Screen was dismissed. No file was selected.");
                }
                else
                {
                Dialog.alert("File selected: " + theFile);
                }
            }
        };

        mainScreen.addMenuItem(showAllMenu);

        MenuItem showImagesMenu = new MenuItem("Select an Image", 40, 40)
        {
            public void run()
            {
                String imageExtensions[] = {"jpg", "jpeg",
                     "bmp", "png", "gif"};

                FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
                fps.pickFile();
                String theFile = fps.getFile();

                if (theFile == null)
                {
                    Dialog.alert("Screen was dismissed. No file was selected.");
                }
                else
                {
                    Dialog.alert("File selected: " + theFile);
                }
            }
        };

        mainScreen.addMenuItem(showImagesMenu);

        pushScreen(mainScreen);
    }
}
/*
 * FileSelectorPopupScreen.java
 *
 * © Research In Motion, 2003-2009
 * Confidential and proprietary.
 */

package com.samples.fileSelectorPopup;

import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.DialogFieldManager;
import javax.microedition.io.Connector;
import javax.microedition.io.file.*;
import java.util.*;

/**
 * A PopupScreen with a file browser allowing for file selection.
 */

public class FileSelectorPopupScreen extends PopupScreen
{

    String _currentPath; //The current path;
    String[] _extensions; //File extensions to filter by.
    ObjectListField _olf; //Lists fields and directories.

    /**
     * Open the screen to the root folder and show all files
     * and directories.
     */
    public FileSelectorPopupScreen()
    {
        this(null, null);
    }

    /**
    * Open the screen starting at the specified path and filter
    * results based on a list of extensions.
    * @param startPath The initial path to open.
    * Use null to start at the root file systems.
    * @param extensions Allowable file extensions to display.
    * Use null to display all file types.
    */
    public FileSelectorPopupScreen(String startPath, String[] extensions)
    {
        super(new DialogFieldManager());
        _extensions = extensions;
        prepScreen(startPath);
    }

    /**
     * Display the screen, prompting the user to pick a file.
     */
    public void pickFile()
    {
        UiiApplication.getUiApplication().pushModalScreen(this);
    }

    /**
     * Retrieves the current directory if the user is still
     * browsing for a file, the selected file if the user has      * chosen one or null if the user dismissed the screen.
     * @return the current directory if the user is still
     * browsing for a file, the selected file if the user has
     * chosen one or null if the user dismissed the screen.
     */
    public String getFile()
    {
        return _currentPath;
    }

    //Prepare the DialogFieldManager.
    private void prepScreen(String path)
    {
        DialogFieldManager dfm = (DialogFieldManager)getDelegate();
        dfm.setIcon(new BitmapField(Bitmap.getPredefinedBitmap(Bitmap.QUESTION)));
        dfm.setMessage(new RichTextField("Select a file"));

        _olf = new ObjectListField();
        dfm.addCustomField(_olf);

        updateList(path);
    }

    //Reads all of the files and directories in a given path.
    private Vector readFiles(String path)
    {
        Enumeration fileEnum;
        Vector filesVector = new Vector();

        _currentPath = path;

        if (path == null)
        {
            //Read the file system roots.
            fileEnum = FileSystemRegistry.listRoots();

            while (fileEnum.hasMoreElements())
            {
                filesVector.addElement((Object)fileEnum.nextElement());
            }
        }
        else
        {
            //Read the files and directories for the current path.
            try
            {
                FileConnection fc = (FileConnection)Connector.open("file:///" + path);
                fileEnum = fc.list();
                String currentFile;

                while (fileEnum.hasMoreElements())
                {
                    //Use the file extension filter, if there is one.
                    if (_extensions == null)
                    {

                        filesVector.addElement((Object)fileEnum.nextElement());
                    }
                    else
                    {
                        currentFile = ((String)fileEnum.nextElement());

                        if (currentFile.lastIndexOf('/') ==
                           (currentFile.length() - 1))
                           {
                           //Add all directories.
                           filesVector.addElement((Object)currentFile);
                           }
                        else
                        {
                            //This is a file. Check if its
                            //extension matches the filter.
                            for (int count = _extensions.length - 1;
                                  count >= 0; --count)
                            {
                                if (currentFile.indexOf(_extensions[count]) != -1)
                                 {
                                      //There was a match, add the file and
                                      //stop looping.

                                      filesVector.addElement((Object)
                                          currentFile);
                                      break;
                                 }
                            }
                       }
                  }
                }
             }
              catch (Exception ex)
              {
                  Dialog.alert("Unable to open folder. " + ex.toString());
              }
        }
        return filesVector;
    }

    //Handles a user picking an entry in the ObjectListField.
    private void doSelection()
    {
        //Determine the current path.
        String thePath = buildPath();

        if (thePath == null)
        {
            //Only update the screen if a directory was selected.
            updateList(thePath);
        }
        else if (!thePath.equals("*?*"))
        {
            //Only update the screen if a directory was selected.
            //A second check is required here to avoid
            //a NullPointerException.
            updateList(thePath);
        }
        else
        {
            //The user has selected a file.
            //Close the screen.
            this.close();
        }
    }
    //Updates the entries in the ObjectListField.
    private void updateList(String path)
    {
        //Read all files and directories in the path.
        Vector fileList = readFiles(path);

       //Create an array from the Vector.
       Object fileArray[] = vectorToArray(fileList);

       //Update the field with the new files.
       _olf.set(fileArray);
    }

    //Build a String that contains the full path of the user's selection.
    //If a file has been selected, close this screen.
    //Returns *?* if the user has selected a file.
    private String buildPath()
    {

        String newPath = (String)_olf.get(_olf, _olf.getSelectedIndex());

        if (newPath.equals(".."))
        {
            //Go up a directory.
            //Remove the trailing '/';
            newPath = _currentPath.substring(0, _currentPath.length() - 2);

            //Remove everything after the last '/' (the current directory).
            //If a '/' is not found, the user is opening the
            //file system roots.
            //Return null to cause the screen to display the
            //file system roots.
            int lastSlash = newPath.lastIndexOf('/');

            if (lastSlash == -1)
            {
                newPath = null;
            }
            else
            {
                newPath = newPath.substring(0, lastSlash + 1);
            }
        }
        else if (newPath.lastIndexOf('/') == (newPath.length() - 1))
        {
            //If the path ends with /, a directory was selected.
            //Prefix the _currentPath if it is not null (not in the
            //root directory).
            if (_currentPath != null)
            {
                newPath = _currentPath + newPath;
            }
        }
        else
        {
            //A file was selected.
            _currentPath += newPath;

            //Return *?* to stop the screen update process.
            newPath = "*?*";
        }

        return newPath;
    }

    //Saves the files and directories listed in vector format
    //into an object array.
    private Object[] vectorToArray(Vector filesVector)
    {
        int filesCount = filesVector.size();
        int dotIncrementor;
        Object[] files;

        //If not in the root, add ".." to the top of the array.
        if (_currentPath == null)
        {
            dotIncrementor = 0;
            files = new Object[(filesCount)];
        }
        else
        {
            dotIncrementor = 1;
            files = new Object[(filesCount + dotIncrementor)];

            //Add .. at the top to go back a directory.
            files[0] = (Object)("..");
        }

        for (int count = 0; count < filesCount; ++count)
        {
            files[count + dotIncrementor] =
               (Object)filesVector.elementAt(count);
        }

        return files;
    }

    //Handle trackball clicks.
    protected boolean navigationClick(int status, int time)
    {
        doSelection();
        return true;
    }

    protected boolean keyChar(char c, int status, int time)
    {
        //Close this screen if escape is selected.
        if (c == Characters.ESCAPE)
        {
            _currentPath = null;
            this.close();
            return true;
        }
        else if (c == Characters.ENTER)
        {
            doSelection();
            return true;
        }

        return super.keyChar(c, status, time);
    }
}

[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800505/800256/How_To_-_Create_a_File_Selection_Popup_Screen.html?nodeid=1498743&vernum=0


sample application extends PopupScreen

this a sample application extends PopupScreen[1]

import net.rim.device.api.i18n.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
public class PasswordPopupScreen extends PopupScreen implements
   KeyListener, TrackwheelListener {
   private String _response;
   // This EditField in RIM API provides built in password
   // masking so the password does not appear on the screen
   // as the user enters it
   private PasswordEditField answer;

   // Hard coded password, normally it is a better idea to have
   // the password stored in an internal RecordStore but here
   // it is hard coded for simplification
   private String password = "password";
   public PasswordPopupScreen()
   {
       super(new VerticalFieldManager(),Field.FOCUSABLE);
       LabelField question = new LabelField("Please enter password");
       answer = new PasswordEditField(" ","");
       add(question);
       add(new SeparatorField());
       add(answer);
   }
   // This function gets called if the password gets called
   // it pops the password screen and pushes the apps main screen
   public void accept() {
       UiApplication.getUiApplication().popScreen(this);
   }
   public void close() {
       UiApplication.getUiApplication().popScreen(this);
   }
   public String getResponse() {
       return _response;
   }
   ////////////////////////////////////////////
   /// implementation of TrackwheelListener
   ////////////////////////////////////////////
   public boolean trackwheelClick(int status, int time) {
       _response = answer.getText();
       if (_response.equals(password)) {
           accept();
       }
       else {
           Dialog.alert("Invalid Password !");
       }
       return true;
   }
   /** Invoked when the trackwheel is released */
   public boolean trackwheelUnclick(int status, int time) {
       return false;
   }
   /** Invoked when the trackwheel is rolled. */
   public boolean trackwheelRoll(int amount, int status, int time) {
       return true;
   }
   /////////////////////////////////////
   /// implementation of Keylistener
   /////////////////////////////////////
   public boolean keyChar(char key, int status, int time) {
       //intercept the ESC key - exit the app on its receipt
       boolean retval = false;
       switch (key) {
           case Characters.ENTER:
               _response = answer.getText();
               if (_response.equals(password)) {
                   accept();
               }
               // an alert is displayed if the password is incorrect
               else {
                   Dialog.alert("Invalid Password !");
               }
               retval = true;
               break;
           case Characters.ESCAPE:
               close();
               break;
           default:
               retval = super.keyChar(key,status,time);
       }
       return retval;
   }
   /** Implementation of KeyListener.keyDown */
   public boolean keyDown(int keycode, int time) {
       return false;
   }
   /** Implementation of KeyListener.keyRepeat */
   public boolean keyRepeat(int keycode, int time) {
       return false;
   }
   /** Implementation of KeyListener.keyStatus */
   public boolean keyStatus(int keycode, int time) {
       return false;
   }
   /** Implementation of KeyListener.keyUp */
   public boolean keyUp(int keycode, int time) {
       return false;
   }
}

[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800505/800256/How_to_-_Protect_BlackBerry_applications_with_a_password_screen.html?nodeid=800506&vernum=0


  • Copyright © 1996-2010 vaks.in. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress