0

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

等待你的回复.....

4

2 回答 2

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()将图像加载到您BitmapField的主/UI线程中。

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

4)copyFile(), 这行

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

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

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

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

于 2012-06-20T03:58:32.607 回答
2

要简单地将该图像下载并保存到 SDCard,您可以使用此代码。我更改了您的 SDCard 路径以使用图片文件夹,我认为这是 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 模拟器上对其进行了测试。

于 2012-06-20T09:05:33.110 回答