【问题标题】:Error while downloading & saving image to sd card in blackberry?在黑莓中将图像下载并保存到 SD 卡时出错?
【发布时间】:2012-06-18 09:58:35
【问题描述】:

我正在研究黑莓项目,我想在其中下载图像并将其保存在黑莓的 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 卡插槽……

等待您的回复.....

【问题讨论】:

    标签: blackberry blackberry-simulator blackberry-webworks


    【解决方案1】:

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

    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 模拟器上测试过。

    【讨论】:

    • 您好@Nate,非常感谢您发布代码。我在 Blackberry 9930 模拟器(7.0 版)中测试了代码,它在其中不工作(除了空白页不显示任何内容)。然后我在 Blackberry 9800 模拟器(6.0 版)中对其进行了测试,它在其中运行良好。不知道是什么问题。你能帮我解决这个...
    • @code_finder,如果没有关于问题的良好、具体的信息,很难提供帮助。如果您想下载图像,将其保存到 SDCard,然后显示它,有多个地方可能会出现问题。您需要告诉我们问题出在哪里(下载、保存、显示等)。 Have a look at the information about asking questions on stack overflow。听起来这应该是一个新问题。如果我发布的代码适用于您,但不适用于所有模拟器,请针对该特定问题提出一个新问题。
    • k 那么,我将根据我现在面临的问题发布新问题....感谢您的建议 Nate.......
    【解决方案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() 方法这样的极少数方法,它必须是静态的。

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

    【讨论】:

    • 感谢 Nate 的建议。实际上,为什么我在这里评论“connectServerForImage()”是,首先我尝试将图像保存在下载的 sd 卡中。它不起作用,然后我在图像文件夹中拍摄了一张图像,并在“copyfile()”方法中传递了该图像以将其保存在 SD 卡中。之后,我将 connector.open() 方法更改为 "Connector.open("file:///SDCard/BlackBerry/");" &保存文件,因为我将我的“rim.png”文件转换为字节 [] 图像,我在 sd 卡路径的末尾传递了那个“图像”。它正在保存,但是当我打开该图像时,它只显示空白屏幕。
    • 实际上我是黑莓新手,从最近两天开始我就一直在努力解决这个问题,请帮助我,否则你能发布一些代码,否则你会把一些代码发送到我的邮件中。如果意味着我将向您提供我的电子邮件 ID...
    • @code_finder,我明白了。学习新东西是困难的。但是,为了帮助您,请务必发布您现在正在使用的代码,并告诉我们您在使用该代码时遇到的确切问题。如果您发布的一组代码试图做 3 种不同的事情,其中​​的部分被注释掉,我们很难解决问题。
    • @code_finder, ...看看我在帖子中描述的问题。例如,我在上面 (4) 中显示的代码行。那行代码不可能工作,因为您将图像的 byte[] 二进制内容作为图像文件的 name 传递。无论图像是捆绑资源还是网络图像,这永远都行不通。同样,请更改代码以尝试只做一件事(下载图像和显示,或复制本地图像和显示,但不能两者兼而有之)。
    • 主要是我想要从服务器下载图像并需要将其保存在黑莓SD卡中......这是主要要求@Nate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多