Search code examples
blackberryblackberry-simulatorblackberry-webworks

Error while downloading & saving image to sd card in blackberry?


I am working on blackberry project where i want to download image & save it in sd card in blackberry. By going through many sites i got some code & based on that i wrote the program but when it is executed the output screen is displaying a blank page with out any response. The code i am following is..

code:

    public class BitmapDemo extends UiApplication
   {    
      public static void main(String[] args)
        {        
       BitmapDemo app = new BitmapDemo();
       app.enterEventDispatcher();        
   }
   public BitmapDemo()
   {
       pushScreen(new BitmapDemoScreen());
   }

      static class BitmapDemoScreen extends MainScreen
    {
       private static final String LABEL_X = " x ";
       BitmapDemoScreen()
        {
        //BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
        //add(bmpFld1);
        setTitle("Bitmap Demo");    

        // method for saving image in sd card
        copyFile();    

        // Add a menu item to display an animation in a popup screen
        MenuItem showAnimation = new MenuItem(new StringProvider("Show Animation"), 0x230010, 0);
        showAnimation.setCommand(new Command(new CommandHandler() 
        {
            public void execute(ReadOnlyCommandMetadata metadata, Object context) 
            {
                // Create an EncodedImage object to contain an animated
                // gif resource.      
                EncodedImage encodedImage = EncodedImage.getEncodedImageResource("animation.gif");

                // Create a BitmapField to contain the animation
                BitmapField bitmapFieldAnimation = new BitmapField();
                bitmapFieldAnimation.setImage(encodedImage);               

                // Push a popup screen containing the BitmapField onto the
                // display stack.
                UiApplication.getUiApplication().pushScreen(new BitmapDemoPopup(bitmapFieldAnimation));                    
            }
        }));

        addMenuItem(showAnimation);       
    }        

    private static class BitmapDemoPopup extends PopupScreen
    {    
        public BitmapDemoPopup(BitmapField bitmapField)
        {
            super(new VerticalFieldManager());                           
            add(bitmapField);                
        } 
        protected boolean keyChar(char c, int status, int time) 
        {
            if(c == Characters.ESCAPE)
            {
                close();
            }               
            return super.keyChar(c, status, time);
        }
    }
}

public static Bitmap connectServerForImage(String url) {

    System.out.println("image url is:"+url);
    HttpConnection httpConnection = null;
    DataOutputStream httpDataOutput = null;
    InputStream httpInput = null;
    int rc;
    Bitmap bitmp = null;
    try {
     httpConnection = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
     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);
     return 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;
   }


public static void copyFile() {
    // TODO Auto-generated method stub
    EncodedImage encImage = EncodedImage.getEncodedImageResource("rim.png"); 
            byte[] image = encImage.getData();
            try {

                // Create folder if not already created
                FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/");
                if (!fc.exists())
                    fc.mkdir();
                fc.close();

             // Create file
                fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
                if (!fc.exists())
                    fc.create();
                OutputStream outStream = fc.openOutputStream();
                outStream.write(image);
                outStream.close();
                fc.close();
                System.out.println("image saved.....");
            } catch (Exception e) {
                // TODO: handle exception
                //System.out.println("exception is "+ e);
            }
}

}

This is the code which i am using. Not getting any response except blank page.. As i am new to blackberry development unable to find out what is the problem with my code. Can anyone please help me with this...... Actually i am having other doubt as like android & iphone does in blackberry simulator supports for SD card otherwise we need to add any SD card slots for this externally...

Waiting for your reply.....


Solution

  • To simply download and save that image to the SDCard, you can use this code. I changed your SDCard path to use the pictures folder, which I think is the standard location on BlackBerrys. If you really want to store it in images, you may just need to create the folder if it doesn't already exist.

    package com.mycompany;
    
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.io.file.FileConnection;
    
    public class DownloadHelper implements Runnable {
    
       private String _url;
    
       public DownloadHelper(String url) {
          _url = url;
       }
    
       public void run() {
          HttpConnection connection = null;
          OutputStream output = null;
          InputStream input = null;
          try {
             // Open a HTTP connection to the webserver
             connection = (HttpConnection) Connector.open(_url);
             // Getting the response code will open the connection, send the request,
             // and read the HTTP response headers. The headers are stored until requested.
             if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
                input = new DataInputStream(connection.openInputStream());
                int len = (int) connection.getLength();   // Get the content length
                if (len > 0) {
                   // Save the download as a local file, named the same as in the URL
                   String filename = _url.substring(_url.lastIndexOf('/') + 1);
                   FileConnection outputFile = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/" + filename, 
                         Connector.READ_WRITE);
                   if (!outputFile.exists()) {
                      outputFile.create();
                   }
                   // This is probably not a robust check ...
                   if (len <= outputFile.availableSize()) {
                      output = outputFile.openDataOutputStream();
                      // We'll read and write this many bytes at a time until complete
                      int maxRead = 1024;  
                      byte[] buffer = new byte[maxRead];
                      int bytesRead;
    
                      for (;;) {
                         bytesRead = input.read(buffer);
                         if (bytesRead <= 0) {
                            break;
                         }
                         output.write(buffer, 0, bytesRead);
                      }
                      output.close();
                   }
                }
             }
          } catch (java.io.IOException ioe) {
             ioe.printStackTrace();
          } finally {
             try {
                if (output != null) {
                   output.close();
                }
                if (connection != null) {
                   connection.close();
                }
                if (input != null) {
                   input.close();
                }
             } catch (IOException e) {
                // do nothing
             }
          }
       }
    }
    

    This class can download an image in the background, as I suggested. To use it, you can start a worker thread like this:

    DownloadHelper downloader = new DownloadHelper("http://images03.olx.in/ui/3/20/99/45761199_1.jpg");
    Thread worker = new Thread(downloader);
    worker.start();
    

    This will save the file as /SDCard/BlackBerry/pictures/45761199_1.jpg. I tested it on a 5.0 Storm simulator.