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

そのイメージを SD カードにダウンロードして保存するには、このコードを使用できます。BlackBerrys の標準的な場所だと思われる写真フォルダーを使用するように、SDCard パスを変更しました。本当に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 に答える
2

投稿されたコードにはいくつかの問題があります。また、何をしようとしているのかが完全に明確ではありません。質問のタイトルから、インターネットからjpg画像をダウンロードして表示したいと思います。

1)画像をダウンロードするために呼び出されるメソッドを実装connectServerForImage()しますが、コメントアウトされています。したがって、メソッドが呼び出されない場合、メソッドは何もダウンロードしません。

2)コメント解除されていても、connectServerForImage()ここで呼び出されます

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

これにより、イメージのダウンロード中にメイン (UI) スレッドがブロックされます。このようにできたとしても、それは良いことではありません。代わりに、Threadイメージをバックグラウンド タスクとしてダウンロードする を作成し、それを使用してメイン/UI スレッドにUiApplication.invokeLater()イメージをロードすることができます。BitmapField

3)メソッドはrim.pngcopyFile()という名前のファイルをコピーしようとします。これは、アプリケーションにバンドルされている画像である必要があり、SDCard に保存しますこれは本当にあなたが望むものですか?代わりにダウンロードした画像を保存しますか? このメソッドは他に接続されていないようです。インターネットからダウンロードした画像を保存するのではなく、保存する画像が他の場所で使用されることはありません。

4)ではcopyFile()、この行

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

byte[]開くファイル名の一部としてa を渡しています (変数はimage)。おそらくString、SDCard パスの末尾に名前を追加する必要があります。コードが示すように、おそらく /SDCard/BlackBerry/images/ フォルダー内の、数字のような非常に長い名前のファイルを開いています。または、ファイル名の長さに制限がある場合、完全に失敗する可能性があります。

5) Java では、通常、すべてを .xml にするのは得策ではありませんstatic。static は通常、定数に対して使用するmain()必要があり、静的でなければならないメソッドのような非常に少数のメソッドに対して使用する必要があります。

これらをクリーンアップしてから、コードを再投稿してください。問題の解決に役立てることができます。ありがとう。

于 2012-06-20T03:58:32.607 に答える