下载时出错&将图像保存到黑莓的SD卡?

时间:2012-06-18 09:58:36

标签: blackberry blackberry-simulator blackberry-webworks

我正在开发黑莓项目,我想下载图片&将它保存在黑莓的SD卡中。通过浏览许多网站我得到了一些代码&基于我编写的程序,但是当它执行时,输出屏幕显示一个没有任何响应的空白页面。我关注的代码是..

代码:

    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);
            }
}

}

这是我正在使用的代码。除了空白页面之外没有得到任何回复..因为我是黑莓开发的新手,无法找出我的代码有什么问题。任何人都可以请帮助我......实际上我还有其他疑问,如android& iphone在黑莓模拟器支持SD卡,否则我们需要为外部添加任何SD卡插槽...

等待你的回复.....

2 个答案:

答案 0 :(得分:2)

发布的代码有几个问题。它还不完全清楚你要做什么。从问题标题,我假设你想从互联网上下载jpg图像,并显示它。

1)您实现了一个名为connectServerForImage()的方法来下载图片,但随后它被注释掉了。因此,如果没有调用它,该方法不会下载任何内容。

2)即使取消注释,此处也会调用connectServerForImage()

BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));

这将在下载图像时阻止主(UI)线程。即使你可以这样做,但这不是一件好事。相反,您可以创建Thread以将图像下载为后台任务,然后使用UiApplication.invokeLater()将图像加载到主/ UI线程上的BitmapField

3)您的copyFile()方法尝试复制名为 rim.png 的文件,该文件必须是与您的应用程序捆绑在一起的图像,并将其保存到SDCard。这真的是你想要的吗?是否要保存下载的图像?此方法似乎与其他任何内容都没有关联。它没有保存从互联网上下载的图像,它保存的图像从未在其他任何地方使用过。

4)copyFile(),此行

fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);

正在传递byte[]作为文件名的一部分打开(您的变量名为image)。您可能应该在SDCard路径的末尾添加String名称。正如代码所示,它可能在/ SDCard / BlackBerry / images /文件夹中打开一个文件,其名称很长,看起来像一个数字。如果文件名的长度有限制,也可能完全失败。

5)在Java中,制作所有内容static通常不是一个好主意。静态通常应该用于常量,并且用于极少数方法,例如main()方法,它必须是静态的。

尝试清理这些内容,然后重新发布代码,我们可以尝试帮助您解决问题。感谢。

答案 1 :(得分:2)

要简单地下载该图像并将其保存到SD卡,您可以使用此代码。我更改了SDCard路径以使用图片文件夹,我认为该文件夹是黑莓手机的标准位置。如果您确实想将其存储在图像中,则可能只需要创建该文件夹(如果该文件夹尚不存在)。

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
         }
      }
   }
}

这个类可以在后台下载图像,正如我所建议的那样。要使用它,您可以启动这样的工作线程:

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

这会将文件另存为/SDCard/BlackBerry/pictures/45761199_1.jpg。我在5.0 Storm模拟器上测试过它。