java Blackberry multimedia is distorted when download resumes

Hello, I'm developing a blackberry app and I'M having a problem while recovery of a download. The code works well if the download is not interrupted, but if it is interrupted and the download is restarted, the media file is distorted.

To allow the resumption of the download, I request the file into segments from the server and persist the last piece of downloaded/written correctly. So if I have to restart the download, I check the last song downloaded and written, increment and to determine the scale at the request of the server.
My code is listed below... :

    public final class Downloader extends Thread {

      private String remoteName;
      private String localName;
      private String parentDir;
      private String dirName;
      public String fileName;

      private int chunkSize = 512000;
      public boolean completed = false;
      public boolean failed = false;

      public CacheObject cacheObject = null

      public Downloader(String remoteName, String localName, String musicTitle, String parentDir, String dirName) {

          this.remoteName = remoteName;
          this.parentDir = parentDir;
          this.dirName = dirName;
          this.localName = localName;
          this.secureDownload = false;
          this.musicTitle = musicTitle;

          this.cacheObject = CachedObject.getInstance().findCachedObject(musicTitle);

          if (this.cacheObject == null) // create new object
              this.cacheObject = new CachedObject(musicTitle, remoteName);

          this.thisObj = this;
        }

        public void run() {
            downloadFile(localName);
        }

        public void downloadFile(String fileName) {
            try {
                int chunkIndex = 0; int totalSize = 0;

                String tempFileName = "file:///" + FileConnect.getInstance().FILE_ROOT+parentDir+ FileConnect.getInstance().FILE_SEPARATOR;

                if (!FileConnect.getInstance().fileExists(tempFileName))
                    FileConnect.getInstance().createDirectory(parentDir);

                if (dirName != null) {
                    tempFileName = "file:///" + FileConnect.getInstance().FILE_ROOT+ parentDir + "/" + dirName + FileConnect.getInstance().FILE_SEPARATOR;

                    if (!FileConnect.getInstance().fileExists(tempFileName))
                       FileConnect.getInstance().createDirectory(parentDir + "/" + dirName);
                }

                fileName = tempFileName + fileName;
                this.fileName = fileName;

                file = (FileConnection) Connector.open(fileName, Connector.READ_WRITE);

                if (!file.exists()) {
                   file.create();
                }

                if(cacheObject.file_path.length() < 1)
                    cacheObject.file_path = fileName;

                file.setWritable(true);

                // Trying to check the file size.
                long fSize = (int)file.fileSize();

                // If it is greater than 1 byte, then we open an output stream at the end of the file
                if(fSize > 1){
                    out = file.openOutputStream((fSize+1));
                }
                else{
                  out = file.openOutputStream();
                }

                int rangeStart = 0; int rangeEnd = 0;

               // Want to know the total fileSize on server (used for updating the UI..
                HttpConnection conn2;
                conn2 = (HttpConnection) Util.getHttpConnection(remoteName);
                String totalFileSize = "" + conn2.getLength();
                conn2.close();

               //Number of chunks
               int numChunks = (int) Math.ceil( Integer.parseInt(totalFileSize) / chunkSize);
               cacheObject.chunk_size = numChunks;

               // Set the total file size..
               content_length = Integer.parseInt(totalFileSize);
               fileSize = 0;
               String url = remoteName + HttpRequestDispatcher.getConnectionString();

               if(cacheObject.last_successfully_downloaded_chunk > -1){
                  //This is a resume..
                  if( (cacheObject.last_successfully_downloaded_chunk + 1) < numChunks ){
                      chunkIndex = cacheObject.last_successfully_downloaded_chunk + 1;

                      fileSize = cacheObject.curr_download_size;
                  }
               }    

              while (file != null) {
                  try{
                      conn = (HttpConnection)Connector.open(url);

                      if(chunkIndex < (numChunks-2)){
                          rangeStart = chunkIndex * chunkSize; rangeEnd = rangeStart + chunkSize - 1;
                      }
                      else{
                          rangeStart = chunkIndex * chunkSize;
                          int remainingBytes = Integer.parseInt(totalFileSize) - rangeStart; rangeEnd = rangeStart + (remainingBytes - 1);
                      }

                      conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
                      conn.setRequestProperty("Connection", "keep-alive");

                      conn.setRequestProperty("Range", "bytes=" + rangeStart + "-" + rangeEnd);
                      responseCode = conn.getResponseCode();                

                      if (responseCode != 200 && responseCode != 206) {
                         out.flush(); out.close(); file.close(); in.close(); conn.close();
                         in = null; conn = null; file = null; out = null;
                         Thread.yield(); break;
                      }
                      else{

                         in = conn.openInputStream(); int length = -1;
                         byte[] readBlock = new byte[256];

                         while ((length = in.read(readBlock)) != -1) {
                             out.write(readBlock, 0, length);
                             fileSize += length;
                             cacheObject.curr_download_size = fileSize;
                         }

                         totalSize += fileSize;

                         in.close(); conn.close(); in = null; conn = null;

                          // Update after the byte read..
                          cacheMusicbox.last_successfully_downloaded_chunk = chunkIndex;
                          CachedObject.getInstance().saveCachedObject( cacheObject);

                          System.out.println("Last successful chunk downloaded: " + cacheObject.last_successfully_downloaded_chunk);

                          chunkIndex++;
                          if(chunkIndex == numChunks){
                              out.flush(); out.close();  file.close(); break;
                          }

                          Thread.yield();
                      }
                  }
                  // Network error related
                  catch(Exception e){
                     System.out.println("Download failed. Some kind of error - " + e.getMessage());
                     System.out.println("fileSize b4 closed: ." + file.fileSize());
                     System.out.println("Last successful chunk downloaded: " + cacheMusicbox.last_successfully_downloaded_chunk);

                      if (out != null) {
                          out.flush(); out.close();
                          System.out.println("We just closed the outputStream");
                          System.out.println("fileSize when closed: ." + file.fileSize());
                      }
                      if (file != null && file.exists()) {
                          if (file.isOpen()) {
                              file.close();
                          }
                      }

                      in = null; conn = null; file = null; out = null;
                      failed = true;
                      System.out.println("Ensuring this block is called " + cacheObject.last_successfully_downloaded_chunk);

                      break;
                  }
              }

              System.out.println("Full file downloaded: " + totalSize + " Bytes");
              System.out.println("Wrote file to local storage");
              Thread.sleep(3000);

              if(!failed)
                  completed = true;

           }
           // any other error...
           catch (Exception e) {
              System.out.println(e.getMessage());

              try{
                  out.flush(); out.close(); file.close();
                  in = null; conn = null;   file = null; out = null;
              }
              catch(Exception ee){
                  System.out.println("While closing catch that belongs to the top guy: " + ee.getMessage());
              }
              failed = true;
            }
        }

    }

I don't know where I am doing wrong. Help, please

Finally this sorted out. What had happened was if the link turns off and I close the output stream, the calculation is distorted.

So the next time I want to continue with the download, I'll open a stream of output at the end of the file and start asking the file to the server from the file size, for example, if the file size is 500 kb (already downloaded b4 network connection went wrong) then I'll start asking to between 500 - (500 + chunkSize) until the end of the file

Tags: BlackBerry Developers

Similar Questions

  • audio media player 12 is distorted when I play *. AVI files

    audio media player 12 is distorted when I play *. AVI files - video is ok, noise is not

    Hello

    Codecs: Frequently asked questions
    http://Windows.Microsoft.com/en-us/Windows7/codecs-frequently-asked-questions

    All you need is good Codec - get these if 32-bit.

    -Free - CCCP also get free tool of insurgents
    http://CCCP-project.NET/

    FFDSHOW - free
    http://sourceforge.NET/projects/ffdshow/

    Check here:

    Plug-ins for Windows Media Player
    http://www.Microsoft.com/windows/windowsmedia/player/plugins.aspx

    ---------------------------------------

    VLC needs, of no use so usually Codec as a backup when asked to support associations of files just say no.

    VLC - free
    http://www.videolan.org/VLC/

    -------------------------------------------------------------

    If 64 bits and you need codec.

    Read this 1st and go that route, or use the one below. (Vista or Windows 7)

    http://www.Vistax64.com/sound-audio/152850-Vista-codec-pack-32bit-64bit-Media-Player-codecs.html

    --------------------------------------------------------------------

    If 64-bit - can run WMP in 32 or 64 bit mode.

    Or try these: download - SAVE - go to the place where your put them RIGHT CLICK – RUN AS ADMIN.

    For 32-bit use these - OR the 32 bit ones listed above which I prefer.

    K - Lite Codec Pack 8.0.8 (or newer)
    http://www.codecguide.com/

    Use them for 64-bit:

    K - Lite Codec Pack 5.5.0 (64-bit) (or newer)
    http://www.codecguide.com/

    -------------------------------------------------------------

    You know that you use WMP 32 or 64

    Change, modify or value 64-bit Windows Media Player 11 (WMP11) in Windows Vista x 64 as default (or WMP12 - Windows7)
    http://www.mydigitallife.info/2007/01/19/switch-change-or-set-64-bit-Windows-Media-Player-11-WMP11-in-Windows-Vista-x64-as-default/

    -------------------------------------------------------------

    And you can use it when necessary because no codex is usually required.

    VideoLAN - VLC media player
    http://www.videolan.org/

    I hope this helps.

    Rob Brown - Microsoft MVP<- profile="" -="" windows="" expert="" -="" consumer="" :="" bicycle=""><- mark="" twain="" said="" it="">

  • Pictures distorted after downloading

    I can upload perfectly good photos. Shortly after they are downloaded, maybe a second or so, they distort: high contrast, low light, 3D effect, shadow. Computer is Dell XPS420 running Windows Vista. I use a Nikon Coolpix 885 camera.

    Hi Manofgifts,
     
    1. When you try to download the pictures?
    2. What is the file type of the pictures?
    3 - is this problem occurs with other photos, when downloaded?
    4. How do you post pictures? (Any third party viewer of photos on your computer)?
    5. where do you see them distorted? It is online or on the pc?
    6. do the same thing happen on image of other download sites?
                
    I suggest you to uninstall your driver graphics card and re - install the latest driver on the manufacturer's Web site. To uninstall the driver, follow the steps below.
     
    a. Click Start; in the type of research start devmgmt.msc and press to enter.
    b. expand display adapter; Right-click on the display component and click on uninstall.
    c. once the driver is uninstalled, restart the computer.
     
    Now try to update your display driver manually by following the steps in the link below.
     
    Manually update your drivers
    http://Windows.Microsoft.com/en-us/Windows-Vista/update-a-driver-for-hardware-that-isn ' t-work correctly
     
    To download the latest drivers, you can visit this link below.
    http://support.dell.com/support/downloads/driverslist.aspx?os=WLH&catid=-1&dateid=-1&impid=-1&osl=EN&typeid=-1&formatid=-1&servicetag=&SystemID=DIM_PNT_9200_XPS_420&hidos=WV64&hidlang=en&TabIndex=&scanSupported=True&scanConsent=False
     
    Now look for how the pictures look like in Windows Photo Gallery.
    Thank you, and in what concerns:
    I. Suuresh Kumar - Microsoft technical support.

    Visit our Microsoft answers feedback Forum and let us know what you think.

  • EOFException when downloading files from the server FTP of Bluetooth

    Hello, I am developing an application that downloads a file from a FTP of Bluetooth server. If I use this code to download a list of files works fine, but if I use the same code to download a real file it doesn't. I tried using plain text, image, video (mp4 and 3gp) and audio with the same result. If I install my app in a Nokia (N95) or a Motorola (K3) works perfectly, but I can't get it to work on my Blackberry 8310
    The problem in the BlackBerry is an EOFException when reading the first byte, no 1 is returned to indicate the end of the file, but an EOFException. BlackBerry Handheld Software (v4.2.2.173)

    This is the code to get the InputStream:

    public InputStream getFileInputStream(ClientSession conn, Operation op, String stFile, String stType) throws IOException {        InputStream inputStream = null;        byte[] FBUUID = {(byte) 0xF9, (byte) 0xEC, (byte) 0x7B, (byte) 0xC4, (byte) 0x95,                   (byte) 0x3C, (byte) 0x11, (byte) 0xD2, (byte) 0x98, (byte) 0x4E, (byte) 0x52, (byte) 0x54,                   (byte) 0x00, (byte) 0xDC, (byte) 0x9E, (byte) 0x09 };        String file = stFile;        String type = stType;        if (file==null) file="";        if (type==null) type="";        //Prepare the headers for the OBEX commands        HeaderSet header = conn.createHeaderSet();        header.setHeader(HeaderSet.TARGET, FBUUID);        //Send OBEX Connect        HeaderSet response = conn.connect(header);        //In order to go the desired folder the OBEX SETPATH command is beeing used        //Prepare the header for the SETPATH commad        header = conn.createHeaderSet();        //folder_name is set to the name of the desired folder        //if left blank the root folder will be used        String folder_name = "";        header.setHeader(HeaderSet.NAME, folder_name);        //Send the SETPATH command        HeaderSet result = conn.setPath(header, false, false);
    
            //Prepare the header for the GET command        header = conn.createHeaderSet();        header.setHeader(HeaderSet.NAME, file);        header.setHeader(HeaderSet.TYPE, type);        op = conn.get(header);        //The selected file will be send to the operation's input stream        inputStream = op.openInputStream();        return inputStream;    }
    

    And the call:

    InputStream in = getFileInputStream(conn, op, "text.txt", "text/plain");
    

    The same call that works perfectly for the list of files (in BlackBerry too):

    InputStream in = getFileInputStream(conn, op, "", "x-obex/folder-listing");
    

    This call produces an xml file which can be read perfectly by any phone.

    Any help is very appreciated!

    Concerning

    Solved. The problem is to use >-1 instead of ! =-1

  • BlackBerry smartphones "Application unavailable for download on BB App World"

    Hello!

    I had to replace my phone (Blackberry Curve 8530) a few days ago while I was trying to download some apps I had on my previous phone. But, when I try to download the applications, a message appears indicating "application unavailable for download from blackberry app world" I know is false. I tried to remove the app world and reinstall and it does not help. So, please... anyone have any ideas on how to solve this problem? Thank you!

    Hi and welcome to the Forums!

    Here's a knockout who deals with this error:

    • KB25521"" is not available for download on BlackBerry App World "appears when you try to download an application from BlackBerry App World "

    I hope that it contains something useful

    Good luck and let us know

  • BlackBerry 8130 smartphones only to download BB app world 2.0 - WHY and how downloaded applications

    I tried to download BB App - the phone says unsupported system world2.0

    Must the 8130 Pearl have a multimedia card installed to download APP world?

    I put e-mail messages without problem but the App World and the Facbook I can't download.

    HELP Please

    Hi and welcome to the Forums!

    Please check this page to ensure that you meet the minimum requirements (including if it is available in your country):

    If it is available in your country and you feel you meet the requirements at the level of the device, and then contact your provider to make sure you meet the requirements of the plan (to them) access (via their network) service to AppWorld.

    Finally, know that AppWorld is simply a portal, vending apps developed mainly by others. Therefore, it is not your exclusive supply source - there are others that you can try (e.g., Handango, Handmark, BPlay, GetJAR and Mobihand). I found that there are very few applications that is exclusive to AppWorld. You can see the online catalogue and then look for other sources of supply, including quite often on the developer website.

    Good luck!

  • BlackBerry Smartphones not able to download updated version of the OS for Pearl 3 G updated

    I received a notice from Blackberry to an update available to the OS (5.0.0.882) but I'm unable to download wireless, via Blackberry Desktop or via the Blackberry site. My current version is 5.0.0.629. My service provider, Rogers Wireless, has no version 5.0.0.882 available on their web page. I get an error message indicating that an error occurred when downloading software for your device. Please check your internet connection or try again later, if the problem persists. I tried to update using my desktop and my laptop and can find no explanation either on the Blackberry site, nor the site Web of Rogers Wireless.

    Hello Shad14 and welcome to the community of BlackBerry Support Forums.

    I checked on the Rogers www.blackberry.com download site and I see the 5.0.0.882 bundle is now listed. You can click here to access the site.

    Try to download the software directly to your computer and use the BlackBerry Desktop Manager to perform the update.

    Let me know how make you out.

    Thank you!

  • says that there is an update of firmware available for my 3 t time capsule. I get "an error occurred when downloading". How to find the problem?

    I said that there is an update of the firmware available for my 3 t time capsule. I get the message "an error occurred when downloading". How to find the problem? I have elcapitan 10.11.6 and capsule version 7.7.3

    Try temporarily, connect your MacBook Pro to your Time Capsule using an Ethernet connection... If not already, then try downloading the firmware again.

  • Piece of Apple's music hangs when downloading

    Hello

    Very often when I play an album on Apple music track hangs when downloading. Download line is blue, but nothing happens. Sometimes, after a long while, is starting. When I double click on the track, he goes to the next and when I double click on it once again the track begins to download and play immediately. It is with iTunes on Mac OX 10.11.5 12.4.1.6. It was the same with previous versions. The Internet connection is fine when I test if a track is suspended. I have to add that I am using Airplay, but it makes no difference what camera I'm streaming to.

    Best regards

    Werner.

    Hey wdonne!

    It is important to be able to download music and listen to it unless it is interrupted. So, lets take a look and see which is the cause because you mentioned that what is also happening on previous versions.

    First, take a look at this article here that helps out with downloads not completing: If an iTunes Store purchase suddenly stops downloading

    We want to do is to reinstall iTunes to see if it would deal with the issue if the steps above does not.  Here, this article gives you the steps on how to do it: OS X El Capitan: reinstall the applications that came with your Mac

    If it still does not after you complete these steps, we need to isolate the problem more far away to see what is the cause.

    What we want to do next is to test in an new user account and the Safe Mode to see if it works or not.  (Please note that Safe Mode, he would not listen to you, but it would allow you to see whether or not the download ends.) After these two, it allow you to isolate the problem more far away to see what is causing the problem.

    Have a wonderful day!

  • PC crashes with DBO when downloading a file using Firefox to my iPad

    PC crashes with DBO when downloading a large file via WiFi to my iPad and using AVPlayerHD player on the iPad. There is no report of error in Firefox, just the crash dump Windows 7 due to the accident. Only the combination of Firefox on PC and player AVPlayerHD on iPad causes this crash. Any other combination of PC and iPad works.
    Examples:
    Firefox on PC and iFile on iPad works well.
    Google Chrome on PC works with all programs on iPad.
    Firefoc on PC and player AVPlayerHD on iPad crashes.

    So you get a Blue Screen of Death on your Windows Machine? You have the exact error codes that appear when you get this blue screen?

    Blue screens mean that you have a problem with a driver, hardware or virus on your PC, not with Firefox. I try to launch a program of analysis such as http://www.resplendence.com/whocrashedand see if she can tell you what triggered the accident. Also, make sure that all your drivers are up to date on your computer (especially the graphics driver: update your drivers graphics to use hardware acceleration and WebGL) and check the virus (Troubleshooting Firefox problems caused by malware).

    After that, if you still get the blue screen and crashed does not help, I would say to try to test your RAM with a utility such as http://www.memtest.org/

  • Drops of WiFi when download/games

    I have a Macbook Pro early 2015 specs i5 2.7 GHz, 8 GB ram, 128 GB of sad, 6100 embedded chart.

    I am running Version El Capitan 10.11.4.

    For some reason any, whenever I download large downloads, such as League of Legends or Hearthstone or an update, my WiFi starts to decline. My internet is fine because he does not drop any other device when they download, but it is a little laggy when downloading, but usually it is very well. Sometimes my WiFi just turns off and when I press the button to turn on the WiFi, it does not work and I have to restart my laptop.

    It also drops whenever I play League of Legends, even when I do not download.

    Howdy TFNY,

    I understand that you are having some stability issues with your Wi - Fi connection. Fortunately, you can use Wireless Diagnostics to identify and resolve the problem.

    Use Wireless Diagnostics helps you troubleshoot Wi - Fi on your Mac.
    https://support.Apple.com/en-us/HT202663

    All my best.

  • When downloading using firefox I should save the download, and then must go to the download file to start the download. When I download using internet explore I can run a download at the time where as it is downloaded. Can I change a setting somewhere?

    I use Windows 7 with firefox as my default browser. When I download a program using firefox, I wonder if I want to save the file, and then must go to the download folder to start the download. When I download using internet explorer, I gives me the ability to run the download at the time where it is downloaded instead of save the download. Is there a setting I can change to allow me to run downloads when using firefox instead of record?

    Hi shortwedge3,

    You can use the OpenDownload2 extension for the run option when downloading files with Firefox

  • iPad connection cable 2 showing when downloading itunes

    I have Pad 2 connection cable when downloading I have tunes

    Do you mean the iPad displays the icon image and cable iTunes on its screen? If you do then the iPad went into recovery mode, you must connect the iPad to iTunes to your computer by cable and should allow you to reset the iPad and you can restore/resync your content

  • Firefox 5: distortion when scrolling on web pages. appearance Wavey

    There is distortion when scrolling on all webpages using Firefox 5. It doesn't matter how fast or slow scrolling, screen becomes wavey to stop scrolling. I uninstalled and reinstalled Firefox and did not help. This happens not using Safari or in documents or spreadsheets open outside of the Firefox browser.

    Its best to take a Screenshot of your toolbars before you run the following suggestion.

    Launch Firefox in Mode safe mode by holding the SHIFT key while starting Firefox-> window Mode safe if poster-> place checkmark on the 2nd option "Reset Toolbars and of orders"-> click "make changes and restart".

    Check and tell if its working.

  • Is it normal for the 128 GB ipod to heat up when downloading

    I just bought this ipod and noticed that it heats up a lot when downloading. Is this normal?

    Hi Sperit,

    It is normal that the iPod to heat up during use, and this should not be a cause for concern.

    I hope this helps!

    Jonty

Maybe you are looking for