13

Is there a way to show "Loading" screen with animation in blackberry?

Options:

  • PME animation content
  • multithreading + set of images + timer/counter
  • standard rim api
  • some other way

Any of this?

Thanks!

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
  • 1
    You can view the example using the popup screen here. http://supportforums.blackberry.com/t5/Java-Development/Sample-quot-Please-Wait-quot-screen-part-1/ta-p/493808 I solved my problem using this. – BSKANIA Apr 27 '12 at 10:47

7 Answers7

35

Fermin, Anthony +1. Thanks to all, you gave me the part of answer.
My final solution:

1.Create or generate (free Ajax loading gif generator) animation and add it to project.

2.Create ResponseCallback interface (see Coderholic - Blackberry WebBitmapField) to receive thread execution result:

public interface ResponseCallback {
    public void callback(String data);  
}

3.Create a class to handle your background thread job. In my case it was http request:

public class HttpConnector 
{
  static public void HttpGetStream(final String fileToGet,
    final ResponseCallback msgs) {
    Thread t = new Thread(new Runnable() {
      public void run() {
        HttpConnection hc = null;
    DataInputStream din = null;
    try {
      hc = (HttpConnection) Connector.open("http://" + fileToGet);
      hc.setRequestMethod(HttpsConnection.GET);
      din = hc.openDataInputStream();
      ByteVector bv = new ByteVector();
      int i = din.read();
      while (-1 != i) {
        bv.addElement((byte) i);
        i = din.read();
      }
      final String response = new String(bv.toArray(), "UTF-8");
      UiApplication.getUiApplication().invokeLater(
        new Runnable() {
          public void run() {
        msgs.callback(response);
              }
            });
    } 
        catch (final Exception e) {
          UiApplication.getUiApplication().invokeLater(
            new Runnable() {
              public void run() {
                msgs.callback("Exception (" + e.getClass() + "): " 
                  + e.getMessage());
              }
            });
        } 
        finally {
          try {
            din.close();
            din = null;
            hc.close();
            hc = null;
          }
          catch (Exception e) {
          }
        }
      }
    });
  t.start();
  }
}

4.Create WaitScreen (a hybrid of FullScreen and AnimatedGIFField with ResponseCallback interface):

public class WaitScreen extends FullScreen implements ResponseCallback 
{
    StartScreen startScreen;
    private GIFEncodedImage _image;
    private int _currentFrame;
    private int _width, _height, _xPos, _yPos;
    private AnimatorThread _animatorThread;
    public WaitScreen(StartScreen startScreen) {
        super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
        setBackground(
            BackgroundFactory.createSolidTransparentBackground(
                Color.WHITE, 100));
        this.startScreen = startScreen;
        EncodedImage encImg = 
          GIFEncodedImage.getEncodedImageResource("ajax-loader.gif");
        GIFEncodedImage img = (GIFEncodedImage) encImg;

        // Store the image and it's dimensions.
        _image = img;
        _width = img.getWidth();
        _height = img.getHeight();
        _xPos = (Display.getWidth() - _width) >> 1;
        _yPos = (Display.getHeight() - _height) >> 1;
        // Start the animation thread.
        _animatorThread = new AnimatorThread(this);
        _animatorThread.start();
        UiApplication.getUiApplication().pushScreen(this);
    }

    protected void paint(Graphics graphics) {
        super.paint(graphics);
            // Draw the animation frame.
            graphics
              .drawImage(_xPos, _yPos, _image
                .getFrameWidth(_currentFrame), _image
                  .getFrameHeight(_currentFrame), _image,
                _currentFrame, 0, 0);
    }

    protected void onUndisplay() {
        _animatorThread.stop();
    }

    private class AnimatorThread extends Thread {
        private WaitScreen _theField;
        private boolean _keepGoing = true;
        private int _totalFrames, _loopCount, _totalLoops;
        public AnimatorThread(WaitScreen _theScreen) {
            _theField = _theScreen;
            _totalFrames = _image.getFrameCount();
            _totalLoops = _image.getIterations();

        }

        public synchronized void stop() {
            _keepGoing = false;
        }

        public void run() {
            while (_keepGoing) {
                // Invalidate the field so that it is redrawn.
                UiApplication.getUiApplication().invokeAndWait(
                  new Runnable() {
                    public void run() {
                        _theField.invalidate();
                    }
                });
                try {
                  // Sleep for the current frame delay before
                  // the next frame is drawn.
                  sleep(_image.getFrameDelay(_currentFrame) * 10);
                } catch (InterruptedException iex) {
                } // Couldn't sleep.
                // Increment the frame.
                ++_currentFrame;
                if (_currentFrame == _totalFrames) {
                  // Reset back to frame 0 
                  // if we have reached the end.
                  _currentFrame = 0;
                  ++_loopCount;
                  // Check if the animation should continue.
                  if (_loopCount == _totalLoops) {
                    _keepGoing = false;
                  }
                }
            }
        }

    }

    public void callback(String data) {
        startScreen.updateScreen(data);
        UiApplication.getUiApplication().popScreen(this);
    }
}

5.In the end, create Start screen to call HttpConnector.HttpGetStream and to show WaitScreen:

public class StartScreen extends MainScreen
{
    public RichTextField text;
    WaitScreen msgs;
    public StartScreen() {       
        text = new RichTextField();
        this.add(text);
    }

    protected void makeMenu(Menu menu, int instance) {
        menu.add(runWait);
        super.makeMenu(menu, instance);
    }

    MenuItem runWait = new MenuItem("wait", 1, 1) {
        public void run() {
            UiApplication.getUiApplication().invokeLater(
                new Runnable() {
                    public void run() {
                        getFile();
                    }
            });             
        }
    };

    public void getFile() {
        msgs = new WaitScreen(this);
        HttpConnector.HttpGetStream(
            "stackoverflow.com/faq", msgs);                 
    }

    //you should implement this method to use callback data on the screen.
    public void updateScreen(String data)
    {
        text.setText(data);
    }
}

UPDATE: another solution naviina.eu: A Web2.0/Ajax-style loading popup in a native BlackBerry application

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
  • Thanks for sharing this. I could also show text beside the image by adding "graphics.drawText(text, xText, yImage);" in paint() method. To calculate coordinates for image and text, used "this.getFont().getAdvance(text)" and "this.getFont().getHeight();". – bob Aug 30 '11 at 22:44
  • can I add images of any frames? I am adding an image with 12 frames, but it is not painted properly. it appears and disappears.. not sure where the problem is.. – varunrao321 May 23 '12 at 08:35
  • @Newbie print out or see _totalLoops value in debug - it's count of loops to play. Check if your animation has infinity loop caount value, maybe it's 1 so played only once. – Maksym Gontar May 23 '12 at 12:37
  • 1
    If you happen to encounter NPE(NullPointerEx) when loading the GIF image, please read this: http://supportforums.blackberry.com/t5/Java-Development/Loading-a-gif-image-using-GIFEncodedImage/m-p/362524#M67850 – Mark Joseph Del Rosario Oct 03 '12 at 02:24
4

This is simple code for loading screen ....

                HorizontalFieldManager popHF = new HorizontalFieldManager();
                popHF.add(new CustomLabelField("Pls wait..."));
                final PopupScreen waitScreen = new PopupScreen(popHF);
                new Thread()
                {
                    public void run() 
                    {

                        synchronized (UiApplication.getEventLock()) 
                        {
                            UiApplication.getUiApplication().pushScreen(waitScreen);
                        }
                       //Here Some Network Call 

                       synchronized (UiApplication.getEventLock()) 
                        {
                            UiApplication.getUiApplication().popScreen(waitScreen);
                        }
                     }
                 }.start();
Dhiral Pandya
  • 10,311
  • 4
  • 47
  • 47
4

The basic pattern for this kind of thing is:

Have a thread running a loop that updates a variable (such as the frame index of the animated image) and then calls invalidate on a Field which draws the image (and then sleeps for a period of time). The invalidate will queue a repaint of the field.

In the field's paint method, read the variable and draw the appropriate frame of the image.

Pseudo code (not totally complete, but to give you the idea):

public class AnimatedImageField extends Field implements Runnable {

   private int currentFrame;
   private Bitmap[] animationFrames;

   public void run() {
     while(true) {
       currentFrame = (currentFrame + 1) % animationFrames.length;
       invalidate();
       Thread.sleep(100);
      }
    }

   protected void paint(Graphics g) {
      g.drawBitmap(0, 0, imageWidth, imageHeight, animationFrames[currentFrame], 0, 0);
    }
  }

Note also here I used an array of Bitmaps, but EncodedImage lets you treat an animated gif as one object, and includes methods to get specific frames.

EDIT: For completeness: Add this to a PopupScreen (as in Fermin's answer) or create your own dialog by overriding Screen directly. The separate thread is necessary because the RIM API is not thread-safe: you need to do everything UI related on the event thread (or while holding the event lock, see BlackBerry UI Threading - The Very Basics

Anthony Rizk
  • 3,666
  • 20
  • 21
3

If it's just an animation could you show an animated gif on a popup and close it when loading operation is complete?

Fermin
  • 34,961
  • 21
  • 83
  • 129
2

I would suggest to take a look at this simple implementation. I liked this but never used it. May be helpful to you.

link text

Sameer
  • 191
  • 1
  • 2
  • 8
2

Easiest way is probably to use the standard GaugeField, setting style GaugeField.PERCENT. This will give you a progress bar. Add this to a PopupScreen and it will sit on top of your content. Something like..

private GaugeField _gaugeField;
private PopupScreen _popup;

public ProgressBar() {    
    DialogFieldManager manager = new DialogFieldManager();
    _popup = new PopupScreen(manager);
    _gaugeField = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT);    
    manager.addCustomField(_gaugeField);
}

Then have an update method which will use _gaugeField.setValue(newValue); to update the progress bar.

I normally have this called from whichever thread is doing the work (loading in your case, everytime an operation is complete the progress bar is updated.

Fermin
  • 34,961
  • 21
  • 83
  • 129
  • Thanks for your answer, but I need not a progress bar, but an animation "wait" dialog. Can you suggest some continuous self-update technique? – Maksym Gontar Apr 29 '09 at 08:16
1

ActivityIndicator is a good option if you are working with at least BB OS 6.0.

http://www.brighthub.com/mobile/blackberry-platform/articles/94258.aspx

http://docs.blackberry.com/en/developers/deliverables/17966/Screen_APIs_1245069_11.jsp

milkersarac
  • 3,399
  • 3
  • 31
  • 31