FileConnection problem

System.out.println("In read file data: reading file"+filePath);
                FileConnection fc = null;
                InputStream fis = null;
                byte fileData[] = null;
                try{
                    fc = (FileConnection) Connector.open(filePath, Connector.READ);
                    System.out.println("Opening file connection - 1");
                    if(fc.exists()){
                        //read only if the file exists
                        fis = fc.openRawInputStream();
                        System.out.println("Opening file connection - 2");
                        int len = (int) fc.fileSize();
                        _modDate = fc.lastModified();
                        System.out.println("Size of file: "+len);
                        if(len == -1){
                            len = 4096;
                        }
                        fileData = new byte[len];
                        int length = fis.read(fileData, 0, len);
                        System.out.println("Opening file connection - 3");
                        if(length > 0 ){
                            System.out.println("Opening file connection - 4");
                        }
                    }
                }catch(OutOfMemoryError error){
                    System.gc();
                    //in case of out of memory error replace with dummyImage
                    System.out.println("Out of Memory Exception in creating Image: "+error.getMessage());
                }catch(Exception e){
                    System.gc();
                    System.out.println("Exception in reading file data: "+e.getMessage());
                    e.printStackTrace();
                }finally{
                    try{
                        fc.close();
                        System.out.println("FileConnection closed successfully");
                    }catch(Exception e){
                        System.out.println("Error while closing file Connection"+e.getMessage());
                    }
                }
             return fileData;

I am trying to load 15 to 20 images at once. I am a connection file for each file - reading the file, then creating an image. But on blackberry storm 9550 Device/Simulator I have a weird situation.

Device: after loading of 6 images it does not load the remaining images.

Simulator: after loading 15 images 2 - 3 times it stops loading 1 image.

I tried debugging and found that filconnection.filesize () return-1 for the first image, after which it stops to load subsequent images. Please refer to the above code.

My debugging logs is:

iCount: 1 loadingIndex: 19

Called paint function

In the data file reading: reading filefile:///store/home/user/pictures/IMG00003-20100625-0831.jpg

The name of the file loading: file:///store/home/user/pictures/IMG00002-20100625-0831.jpg

Files opened - 1 connection

Connection files opening - 2

In the data file reading: reading filefile:///store/home/user/pictures/IMG00002-20100625-0831.jpg

Files opened - 1 connection

FileConnection closed successfully

Loading default filedata null Image

File size:-1

Files opened - 3 connection

Files opened - 4 connection

FileConnection closed successfully

iCount: loadingIndex 2:20

The name of the file loading: file:///store/home/user/pictures/village.jpg

Loading default filedata null Image

In the data file reading: reading filefile:///store/home/user/pictures/village.jpg

Files opened - 1 connection

FileConnection closed successfully

As you can see for loadingindex 20 he treats the file as if it does not exist.

Help, please.

@geeneeus-

From my experience, fileSize() works correctly without anything read, or even open any watercourse. In fact, he is supposed to report that the size of the file without taking into account how much has been read. (He will miss all the data that has been written to an output stream but not emptied.) However, which does apply here.) It only returns-1 if the file does not exist or is not accessible.

@dodgeviper-

The main problem with the code, it is the input stream are not closed, so the connections remain open and the application runs on the file handles.

The newspaper, it seems that this code is called simultaneously on multiple threads. (I see two 'opening file connection - 1' before the first 'file connection fermΘe with success'.) This probably isn't a problem in itself, although it may cause the connection limit to be affected, even after the code is changed to close the stream. Be sure to limit the number of threads simultaneously calling this code.

There are several other problems with the code. I would like to change it:

if (len == -1) {    len = 4096;}

TO:

if (len == -1) {    throw new Exception("File " + filePath + " not available.");}

If fileSize() (or rawFileSize()) returns-1, you do not have to be anything reading this file.

Copy the following code:

int length = fis.read(fileData, 0, len);

is not correct. Even if 'len' bytes are available, a single call to read() is not guaranteed to read that many bytes. It must be replaced by something like:

int length = 0;int read;while ((read = fis.read(fileData, length, len - length) != -1 && length < len) {    length += read;}

(Not very elegant, but I am writing this late at night.)

In addition, as sonicboomboy says, you must use fc.openInputStream () and fc.fileSize () instead of fc.openRawInputStream () and fc.rawFileSize (). Unless (a) your files are encrypted and (b) that you are trying to transfer the entire file without decryption, the first methods are not suitable. They are certainly not the way to get the decoded image data.

Finally, eliminate the OutOfMemoryException catches. The system.GC() call at that time is always futile. The jvm throws this exception until he has already run the gc to try to save the situation. Unless your application can immediately free up a lot of memory (by emptying a cache in memory, say), then it is wildly optimistic to think that a lot of other useful is going to happen inside your application at this time. The only thing you can do is prepare for an abnormal exit (and not much use preparation of memory, either!)

Tags: BlackBerry Developers

Similar Questions

  • problem using the FileConnection API (JSR 75) in an application for Blackberry "BOLD" MIDLET

    Hello

    I developed a MIDLET which is to read files and store the contents of files in arrays. I could make using the FileConnection API in J2ME (Java ME) and it works very well in mobile emulators provided by Sun, Sun Kit tool 2.5.1 wireless and Sprint Wireless tool 3.3.2 Kit. I have been using netbeans IDE 6.8 for this.

    Now, here's the deal. Playback of the files does not work when in one of the Blackberry mobile emulators. I tried to install all versions of Blackberry JDE 4.2.1 to 5.0 and test the same thing, but none of them worked.  After reading that the Blackberry plugin for Eclipse is good, I used it to find that I am always faced with the problem.

    I desperately need help. Can someone help me do the reading work file in a Blackberry emulator? I insert the code that makes the file reading. It reads a file containing a single column of 60 entries, and stores it in an array of double type.

    Vector time = new Vector();
    
    try{
    
     FileConnection filecon = (FileConnection) Connector.open("file:///" +"SDCard/BlackBerry/documents/"+"timescale.dat");
    
     if(!filecon.exists()) {    Dialog.show("Note ! ", "File doesn't exists !", "okay","cancel"); }
    
         StringBuffer sb = new StringBuffer();      try      {       InputStream in = filecon.openInputStream();       int chars;
    
           while ((chars = in.read()) != -1)// read until EOF is reached       {          if(chars == '\n') // read all characters until the end of line is reached          {              time.addElement(sb.toString().trim()); // stores all the characters as a vector element when the end of line is reached
    
                  sb.delete(0,sb.length());// clear the stringbuffer for storing the next line of the file
    
              }
    
              else          {              sb.append((char)chars); // appends each character read          }
    
          }// end of while
    
        }    catch(IOException e)    {               }
    
        filecon.close();
    
    }// end of outer try
    
       int i =0;   Enumeration etime = time.elements();
    
       while(etime.hasMoreElements() && i < 60) // timescale.dat has 60 entries in one column   {       time_1d[i]=Double.parseDouble(etime.nextElement().toString());// convert to double       i++;   }
    

    Can you elaborate on what does not work?  Is an error or exception thrown?  If Yes, what is it and what line of code triggers it?

    You have configured the BlackBerry smartphone Simulator to simulate a micro SD card?

    Use a computer filesystem in the form of microSD card

    http://supportforums.BlackBerry.com/T5/testing-and-deployment/use-a-computer-file-system-as-a-microS...

  • Dealing with problem FileConnection class

    Hello guys I am experiencing problem dealing with FileConnection class. My app uses the class "javax.microedition.io.file.FileConnection". And when to start the application, the problem occurs that

    "Error starting ApplicationName class 'javax.microedition.io.file.Fileconnection' not found."

    My device name: BlackBerry8703e

    OS version: 4.1.0 profile / Verizon Wireless BlackBerry

    Do you know this problem? How can I solve it?

    TNX'

    FileConnection is supported to 4.2.0.

  • Problem with OPenInputStream and FileConnection

    I've already checked all the directory in Blackberry using FileConnection and filter all jpg and png files and store them in vector.

    When I show them use dialogue, the spectacle of the Directory dialog box all I need and it's true.

    Here is my code:

    int length = imageName.size ();
    If (imageName.size () > 0) {}
    try {}
    for (cnt int = 0; cnt)< length;="" cnt++)="">
    FileConnection fc = Connector.open (imageName.elementAt (cnt) m:System.NET.SocketAddress.ToString (()) (FileConnection);
    InputStream is = null;
    If (fc.exists ()) {}
    InputStream input = fc.openInputStream ();
    ByteArrayOutputStream Baos = new ByteArrayOutputStream();
    int j = 0;
    While ((j = input.read ())! = - 1) {}
    Baos.Write (j);
    }
    data Byte [] = baos.toByteArray ();
                           
    Input.Close ();
    FC. Close();
    IMG [cnt] = Image.createImage (data, 0, data.length) .scaled (60, 45);
    addComponent (img [cnt], null, null, null);
    } else {}
    Utilities.showDialog ("info", "the file is connection does not exist");
    }
    }

    } catch (Exception e) {}
    Utilities.showDialog ("info", "error:" + e.getMessage ());
    }

    imageName is a vector variable to contain all the images in the directory. I followed one by one, but when " InputStream input = fc.openInputStream ();" always returns null.

    My code works well in Simulator 8310 but when I test it on the device real inputstream always return a null value.

    and I signed my application before I install it in the real device... I have no idea with my prob. Please help me...

    Best regards

    ASRI Dwitiya

    Make sure you set the permissions to ALLOW for your application and your application attempts to read images that are stored in the folder 'user '.

  • Download file problem

    package com.blackberry.util.network;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.Hashtable;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.io.file.FileConnection;
    
    import net.rim.device.api.io.http.HttpProtocolConstants;
    import net.rim.device.api.io.transport.ConnectionDescriptor;
    import net.rim.device.api.io.transport.ConnectionFactory;
    import net.rim.device.api.io.transport.TransportInfo;
    import net.rim.device.api.ui.UiApplication;
    
    import com.blackberry.util.Function;
    import com.blackberry.util.StringUtility;
    import com.blackberry.util.log.Logger;
    
    public class NetworkThread extends Thread
    {
        private static final String twoHyphens = "--";
        private static final String Boundary = "****************256176b82bde4478"; //what_hell_is_that
        private static final String lineEnd = "\r\n";
    
        private ObserverInterface _ourObserver;
        private String _targetURL;
        private Hashtable _params;
        private String _fileField;
        private String _fileName;
        private String _fileType;
        private String _fileURI;
        private boolean _stopRequest = false;
    
        private ConnectionFactory cf;
        private Logger log;
        private int[] preferredTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI, TransportInfo.TRANSPORT_TCP_CELLULAR};
        private int[] disallowedTransportTypes = {TransportInfo.TRANSPORT_BIS_B, TransportInfo.TRANSPORT_MDS, TransportInfo.TRANSPORT_WAP, TransportInfo.TRANSPORT_WAP2};
    
        private long postSize = 0;
    
        public NetworkThread(String requestURL, Hashtable params, String fileField, String fileName, String fileType, String fileURI, ObserverInterface observer)
        {
            super();
    
            log = Logger.getLogger(getClass());
    
            cf = new ConnectionFactory();
            cf.setPreferredTransportTypes(preferredTransportTypes);
            cf.setDisallowedTransportTypes(disallowedTransportTypes);
            cf.setTimeoutSupported(true);
            cf.setAttemptsLimit(10);
            cf.setConnectionTimeout(120000);
    
            _targetURL = requestURL;
            _params = params;
            _fileField = fileField;
            _fileName = fileName;
            _fileType = fileType;
            _fileURI = fileURI;
            _ourObserver = observer;
    
            postSize = getMultipartPostBytesSize(_fileField, _fileName, _fileType, _fileURI);
        }
    
        public void stop()
        {
            observerError(ObserverInterface.CANCELLED, "Cancelled by User");
            _stopRequest = true;
    
            Thread.currentThread().interrupt();
        }
    
        private void observerStatusUpdate(final int status, final String statusString)
        {
            if (!_stopRequest)
            {
                _ourObserver.processStatusUpdate(status, statusString);
            }
        }
    
        private void observerError(int errorCode, String errorMessage)
        {
            if (!_stopRequest)
            {
                _ourObserver.processError(errorCode, errorMessage);
            }
        }
    
        private void observerResponse(byte [] reply)
        {
            if (!_stopRequest)
            {
                _ourObserver.processResponse(reply);
            }
        }
    
        public void run ()
        {
            HttpConnection httpConn = null;
            FileConnection fileConn = null;
            InputStream input = null;
            OutputStream output = null;
            StringBuffer buffer = new StringBuffer();
            StringBuffer responeBuffer = new StringBuffer();
    
            try {
                if ((_targetURL == null) || _targetURL.equalsIgnoreCase("") || (cf == null))
                {
                    if (!_stopRequest)
                    {
                        _ourObserver.processError(ObserverInterface.ERROR, "Target url empty or http connection initial failed!");
                    }
                }
    
                StringBuffer urlBuffer = new StringBuffer(_targetURL);
    
                if ((_params != null) && (_params.size() > 0)) {
                    urlBuffer.append('?');
                    Enumeration keysEnum = _params.keys();
    
                    while (keysEnum.hasMoreElements())
                    {
                        String key = (String) keysEnum.nextElement();
                        String val = (String) _params.get(key);
                        urlBuffer.append(key).append('=').append(val);
    
                        if (keysEnum.hasMoreElements()) {
                            urlBuffer.append('&');
                        }
                    }
                }
    
                ConnectionDescriptor connd = cf.getConnection(urlBuffer.toString());
                String transportTypeName = TransportInfo.getTransportTypeName(connd.getTransportDescriptor().getTransportType());
                httpConn = (HttpConnection) connd.getConnection();
    
                if (httpConn != null)
                {
                    try {
                        httpConn.setRequestMethod(HttpConnection.POST);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                        //httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + "; boundary=" + Boundary);
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Long.toString(postSize));
                        output = httpConn.openOutputStream();
    
                        buffer.append(twoHyphens + Boundary + lineEnd);
                        buffer.append("Content-Disposition: form-data; name=\"" + _fileField + "\"; filename=\"" + _fileName + "\"" + lineEnd);
                        buffer.append("Content-Type: " + _fileType + lineEnd);
                        buffer.append(lineEnd);
                        output.write(buffer.toString().getBytes());
                        observerStatusUpdate(1, "Started");
    
                        fileConn = (FileConnection)Connector.open(_fileURI, Connector.READ);
                        long totalBytes = fileConn.fileSize();
                        if (totalBytes == -1) {throw new IOException("File " + _fileURI + " not available.");}
    
                        long sentBytes = 0;
                        int percentPre = 0;
    
                        input = fileConn.openInputStream();
                        byte[] temp = new byte[1024];
    
                        int len = 0;
    
                        while ((len = input.read(temp)) > -1)
                        {
                            if (_stopRequest)
                            {
                                observerError(ProgressListener.CANCELLED, "User canceled.");
                                return;
                            }
    
                            output.write(temp, 0, len); 
    
                            //Thread.yield();
    
                            sentBytes += len;
                            int percentageFinished = (int) ((sentBytes * 100) / totalBytes);
                            percentageFinished = Math.min(percentageFinished, 99); 
    
                            if (percentageFinished != percentPre)
                            {
                                observerStatusUpdate(percentageFinished, StringUtility.formatSize(sentBytes, 1) + " / " + StringUtility.formatSize(totalBytes, 1));
                            }
    
                            percentPre = percentageFinished;
                        }
    
                        output.write(lineEnd.getBytes());
                        output.write((twoHyphens+Boundary+twoHyphens+lineEnd).getBytes());
    
                        output.flush();
                        output.close();
                    } catch (IOException e)
                    {
                        observerError(ProgressListener.ERROR, "Post data exception: \n\n" + e.getMessage());
                    }
    
                    log.info("HTTP-POST-MULTI (" + transportTypeName + "): " + httpConn.getURL());
    
                    int resCode = 0;
                    String resMessage = "";
    
                    try {
                        resCode = httpConn.getResponseCode();
                        resMessage = httpConn.getResponseMessage();
    
                        log.info("HTTP-POST-MULTI Response: " + resCode + " " + resMessage);
                    } catch (IOException e) {
                        observerError(ProgressListener.ERROR, "get respone code ioexception: \n\n" + e.getMessage());
                    }
    
                    switch (resCode)
                    {
                        case HttpConnection.HTTP_OK:
                        {
                            InputStream inputStream;
                            int c;
    
                            try {
                                inputStream = httpConn.openInputStream();
                                while ((c = inputStream.read()) != -1)
                                {
                                    responeBuffer.append((char) c);
                                }
    
                                inputStream.close();
                            } catch (IOException e)
                            {
                                Function.errorDialog("HTTP_OK ioexception: " + e.toString());
                            }
    
                            observerStatusUpdate(100, "File uploaded.");
    
                            UiApplication.getUiApplication().invokeAndWait(new Runnable()
                            {
                                public void run()
                                {
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {}
                                }
                            });
    
                            observerResponse(responeBuffer.toString().getBytes());
                            break;
                        }
                        case HttpConnection.HTTP_BAD_REQUEST:
                        {
                            InputStream inputStream;
                            int c;
    
                            try {
                                inputStream = httpConn.openInputStream();
                                while ((c = inputStream.read()) != -1)
                                {
                                    responeBuffer.append((char) c);
                                }
    
                                inputStream.close();
                            } catch (Exception e)
                            {
                                Function.errorDialog("HTTP_BAD_REQUEST ioexception: " + e.toString());
                                observerError(ProgressListener.ERROR, e.getMessage());
                            }
    
                            observerError(ProgressListener.ERROR, "File transfer problems!");
    
                            break;
                        }
                        case HttpConnection.HTTP_TEMP_REDIRECT:
                        case HttpConnection.HTTP_MOVED_TEMP:
                        case HttpConnection.HTTP_MOVED_PERM:
                        {
                            observerError(ProgressListener.ERROR, "File transfer moved!");
                            break;
                        }
                        case HttpConnection.HTTP_INTERNAL_ERROR:
                        {
                            observerError(ProgressListener.ERROR, "Internal server error");
                            break;
                        }
                        default:
                            break;
                    }
                }
    
                log.info("HTTP-POST-MULTI Body: " + httpConn.getType() + "(" + responeBuffer.length() + ")");
                log.debug(responeBuffer.toString());
            } catch (Throwable t)
            {
                Function.errorDialog(t.toString());
                log.error("New Thread Throwable: " + t.getMessage());
                t.printStackTrace();
            } finally {
                if (input != null) {try {input.close();} catch (IOException e) {}}
                if (fileConn != null) {try {fileConn.close();} catch (IOException e) {}}
                if (output != null) {try {output.close();} catch (IOException e) {}}
                if (httpConn != null) {try {httpConn.close();} catch (IOException e) {}}
            }
    
            _stopRequest = true;
            _ourObserver = null;
    
            observerStatusUpdate(100, "Finished"); // Tell Observer we have finished
            observerResponse("Succeeded".getBytes());
        }
    
        private long getMultipartPostBytesSize(String name, String fileName, String fileType, String fileURI)
        {
            StringBuffer buffer = new StringBuffer();
            FileConnection fconn = null;
            long fileSize = 0;
    
            /*
             * @multipart post format
             *  --****************256176b82bde4478\r\n
             *  Content-Disposition: form-data; name="uploadfile"; filename="fileName"\r\n
             *  Content-Type: txt/plain\r\n
             *  \r\n
             *  [content bytes of upload file]
             *  \r\n
             *  --****************256176b82bde4478--\r\n
            */
            buffer.append(twoHyphens + Boundary + lineEnd);
            buffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"" + lineEnd);
            buffer.append("Content-Type: " + fileType + lineEnd);
            buffer.append(lineEnd);
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            try
            {
                baos.write(buffer.toString().getBytes());
                baos.write(lineEnd.getBytes());
                baos.write((twoHyphens+Boundary+twoHyphens+lineEnd).getBytes());
    
            } catch (IOException e) {
                Function.errorDialog("flush byte data ioexception: " + e.toString());
            }
    
            try {
                fconn = (FileConnection)Connector.open(fileURI);
                fileSize = fconn.fileSize();
                fconn.close();
            } catch (IOException e) {
            }
    
            return baos.toByteArray().length + fileSize;
        }
    }
    

    I use post multipart via httpConnection method to upload files on server (website a service net disk, single file size is limited to 500 MB), I tested the Simulator (9800 Asia, software: 6.0.0.706, platform: 3.0.0.159, network: wifi) and download a large file 40 MB, but when I signed my record of cod and tested on the device (9900 (, software: 7.1.0.1098, platform: 5.1.0.701 network: wifi), I had an interruption during about 3 MB of data download and threw a ConncectionClosedException.

    Here is my proposal, when output.write (filled with all bytes) amount (perhaps 10240 bytes), it will download bytes in the buffer to the server immediately, and waiting for filled with bytes remaining and so on. Download the bytes in the buffer may take a long time to wait, if the ConnectionClosedException is took place during this freeze period?

    If I download a file less than 1 MB on the device, it will be probably successful, Yes, not 100% success rates, I do not know what problem I am facing now

    "I don't have limits of authority to deal with pieces of data on the server.

    You might have problems if you do this on mobile service because they can or can not cut you if you try to upload too many bytes, more WiFi, it should work good Chunking is really useful for recovery reboot only, does not provide all of the extra features.

    «the network indicator in the upper right corner of the device screen will flash several times, until the flash stopped writing bytes will continue progress.»

    OK, not my experience with mobile connections, maybe it works that way with WiFi or using the https protocol, which does not establish the connection at first.

    That being said, I don't think I can help a lot here sorry.

  • FileConnection leak

    Hi, expert,

    I think that there are a few FileConnection flee to my code (doesn't have to call a close on this method), Marvel just to the following questions about this:

    1. If there is leak memory during the execution of the process, once the process is stopped, the operating system must be able to claim the FileConnection, right?  I think about C + c++ / C is like that, unless I'm missing sth here.

    2. I have a few leaks FileConnection every 4 hours, but my application may work for a while (several days) without any problem. If it leads to thinking that if garbage would help the BONES to recover the FileConnection as well. Are there such opportunities?

    Thanks in advance for your understanding on this.

    (1) Yes

    (2) I believe that the garbage collector would effectively close the connection when he sees, there is no valid references to the fileconnection special within the application and removes the object from memory. It is difficult to predict the exact behavior of the garbage collector, however. In most cases, the garbage collector does not clean until the system needs memory. I saw connections persist even after the reference that them has been withdrawn, so I wouldn't say that you can rely on the GC to clean your fileconnections in due course.

    Scott

  • Problem in opening a card encrypted database

    Hello

    I'm having problems when trying to open a connection to a database sqlite stored on the SD card. I'm moving the file from database on the network when the application is run first, and if the phone is set to encrypt files from media card then it is written with the suffix ".rem". Then I try to open a connection to the database by using the following:

    DatabaseFactory.open(dbPath)
    

    dbPath here is a URI pointing to ' / SDCard/data/database.db' is the file that I downloaded on the network. With encryption disabled it works fine and I can open the database and run queries on it etc. However, with encryption on, I get the following exception:

    net.rim.device.api.database.DatabaseIOException: file not found

    I tried it change at the first glance to 'database.db.rem' in the case of encryption but then receive this error:

    net.rim.device.api.database.DatabaseIOException: decryption header error

    I don't know how to get around this, because I can't find a way to override the settings for encryption on the phone and write the file of database to the SD card without encryption. Or maybe is there a way I can decrypt the database file after writing it if necessary?

    Anyone have any ideas on how to solve this problem?

    Thank you

    It is a known problem. Fortunately, the following workaround solution should solve the problem for you:

    Instead of download the .db and then open it directly in SQLite using the DatabaseFactory class, follow these steps:

    1. create the database (file) using the DatabaseFactory class.
    2. close the database.
    3. open a connection file in the database file that was created in step 1 and 2
    4 truncate the file to 0 by calling FileConnection.truncate (0)
    5. download the database on the network and write the data in the file previously created using FileConnection.openOutputStream)
    6. close the connection files
    7. now re-open the database using the DatabaseFactory class and your SQL should work as expected.

    Creating the file database using the results in the file DatabaseFactory class *not* marked as requiring encryption.

    I hope it works for you.

  • FileConnection help

    Hello!

    I'm doing a photo gallery that I have in the folder img/photos/in the project resource.

    To do this, I need to read the directory and a list of the files inside, and then, successively, to get an image file and resize and print.

    But I have the problem doing a FileConnection of the resource... I tried so many ways... but no one worked for me...

    I tried:

    Conexion FileConnection = Connector.open("file:///img/photos") (FileConnection);

    Conexion FileConnection = (FileConnection) Connector.open ("file://img/photos");

    Conexion FileConnection = Connector.open("file:///img/photos") (FileConnection);

    Conexion FileConnection = Connector.open("file:///store/img/photos") (FileConnection);

    etc... and everyone returns a NullPointerException.

    I bend the path have the resource...

    Thank you

    Albert

    Sorry that I misunderstood your question.

    The files that are included in project resources cannot be read using the FileConnection API.  If you want to display a list of the included resource files, you have to do it manually.  To "read" each file, you can use Bitmap.getBitmapResource, but there is no way that I'm aware of have a program to get the list of files that are included.

    As you add these files to the project, in any case, you can add them to a list that you maintain too.

  • Problem: How to upload files to server

    I'm a newbie to BB development. I have problems to download the file from my BB to the server.

    Any help would be appreciated... Thank you...

    Code of the thread:

    class UploadThrd extends Thread
    {
    Limit string = "*";
    String lineend = "\r\n";
    String twoHyphens = "-";
    int maxBufferSize = 0;
    DataInputStream fileInputStream = null;
    public void run()
    {
    try {}
    FileConnection fis=(FileConnection)Connector.open("file:///store/home/user/newfile.txt");
    CreateFileScreen.showMsg ("recovered file name");
    InputStream inputStream = fis.openInputStream ();

    ByteArrayOutputStream Bos = new ByteArrayOutputStream();
    int buffersize = (int) fis.fileSize ();
    ubyte [] buffer = new byte [buffersize];
    int length = 0;
    While ((length = InputStream.Read (buffer))! = - 1).
    {
    Bos.Write (buffer, 0, Length);
    }
    Byte [] b = bos.toByteArray ();
    CreateFileScreen.showMsg ("copied file...");

    ConnectionFactory connFact = new ConnectionFactory();
    ConnectionDescriptor connDesc;
    connDesc = connFact.getConnection ("http://www.myserver.net/z/upload.php");
    If (connDesc! = null)
    {
    HttpConnection conn;
    Conn = (HttpConnection) connDesc.getConnection ();
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("http connected...");
    }
    });
    conn.setRequestMethod (HttpConnection.POST);
    conn.setRequestProperty ("Content-Type", "multipart/form-data; limit = "" + limit); "
    conn.setRequestProperty ("login", "Keep-Alive");
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("' HTTPConnection TOGETHER... verification response Code.. '");
    }
    });
    conn.setRequestProperty ("Content-Length", Long.toString (b.length));
    end of series

    If (conn.getResponseCode () == HttpConnection.HTTP_OK)
    {
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("response Code: HTTP_OK!");
    }
    });
    OutputStream os = conn.openOutputStream ();
    Write bytes
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("written bytes..");
    }
    });

    String CT = "Content-Type: multipart/form-data;" limit = "+ limit;"
    OS. Write ("Content-Disposition: form-data;") Name =-"source\" "." GetBytes());
    OS. Write (LineEnd.GetBytes ());
    OS. Write (LineEnd.GetBytes ());
    OS. Write ("BlackBerry". GetBytes());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (twoHyphens.GetBytes ());
    OS. Write (Boundary.GetBytes ());
    OS. Write (LineEnd.GetBytes ());

    String filename = "z\newfile.txt; »
    OS. Write ("Content-Disposition: form-data;") name =-"Filedata\"; filename =------"". GetBytes());
    OS. Write (FileName.GetBytes ());
    OS. Write("\"".) GetBytes());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (CT. GetBytes());
    OS. Write (LineEnd.GetBytes ());
    OS. Write (LineEnd.GetBytes ());

    OS. Write (b, 0, b.length);

    OS. Write (LineEnd.GetBytes ());

    OS. Write (twoHyphens.GetBytes ());
    OS. Write (Boundary.GetBytes ());
    OS. Write (twoHyphens.GetBytes ());
    OS. Write (LineEnd.GetBytes ());
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("downloaded file!");
    }
    });
    OS. Flush();
    OS. Close();
    }
    on the other
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert ("no connection");
    }
    });
    Conn.Close ();
    }

    }
    catch (Exception e) {}
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run() {}
    Dialog.Alert("===exception!");
    }
    });
    }
    }
    }

    Class app:

    SerializableAttribute public class CreateFileApp extends UiApplication
    {
    /**
    * Entry point for application
    @param args command-line arguments (not used)
    */
    Public Shared Sub main (String [] args)
    {
    Try
    {
    FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt");
    If (! fc.exists ())
    {
    FC. Create(); create the file if it doesn't exist
    }
    OutputStream outStream = fc.openOutputStream ();
    outStream.write ("happy test".getBytes ());
    outStream.close ();
    FC. Close();
    CreateFileScreen.showMsg ("I'll upload file..");
    Thread UploadThrd = new UploadThrd();
    thread. Start();
    }
    catch (IOException e)
    {
    System.out.println ("= IOException:"+ e.getMessage () ");
    }
    catch (Exception e1)
    {
    System.out.println ("= Exception:"+ e1.getMessage () ");
    }
    Create a new instance of the application and make the currently
    who runs the thread of the application of the event dispatch thread.
    PAP CreateFileApp = new CreateFileApp();
    theApp.enterEventDispatcher ();
    }

    /**
    * Creates a new CreateFileApp object
    */
    public CreateFileApp()
    {
    Push a screen onto the stack in the user interface for rendering.
    pushScreen (CreateFileScreen.cfs);
    }
    }

    The screen class:

    / public final class CreateFileScreen extends screen
    {
    /**
    * Creates a new CreateFileScreen object
    */
    public static CreateFileScreen SFC = new CreateFileScreen();
    public CreateFileScreen()
    {
    Set the displayed title of the screen
    setTitle ("create a file");
    }
    public static void showMsg (String msg)
    {
    LabelField lbl = new LabelField (msg);
    CFS. Add (LBL);
    }
    }

    Hello, welcome to the Forums!

    You must use the property tto line allow multi part download on your BB using Post server.

    It is a good example in nokia Forums, where you can fashion it accordint to your settings & file Type.

    http://www.developer.Nokia.com/community/wiki/HTTP_Post_multipart_file_upload_in_Java_ME

    Thank you

  • ClassCastException on Manager.createPlayer problem with DataSource

    I run the code BufferedPlayback (JDE 4.7.0) example loading a local file (LimitedRateStreamingSource to the source of data):

    final LimitedRateStreamingSource source = new LimitedRateStreamingSource("file:///store/home/user/test/test.wav");
    source.setContentType("audio/x-wav");
    final Player player = Manager.createPlayer(source);
    

    but when I create the player a ClassCastException is thrown.
    Search with google I found this method performs a cast to CommonDataSource, and this leads to the exception (http://discussion.forum.nokia.com/forum/showthread.php?t=113902).

    I can't figure out how to solve this problem... someone has any advice?

    LimitedRateStreamingSource in this example expects a HTTP URL.  When you use it with a file:/// URL a FileConnection is returned by the Connector.open call, which triggers a ClassCastException.

    You will need to modify the example to use a FileConnection instead of a ContentConnection.

  • FileConnection questions when you debug on device

    I am writing a program that uses files on the blackberry system and it works perfectly on a simulator, when it comes to debugging on a blackberry, however, it gets stuck when trying to call a fileconnection. Here is my code at the base:

    try{
        FileConnection fconn = (FileConnection)Connector.open("File:///store/home/user/");
                if (fconn.exists())
                    System.out.println("exists");
                else
                    System.out.println("nexists");
    }catch (IOException ioe){System.out.println("ERROR");}
    

    He arrived at the fileconnection statement and then does not continue with the function. It ends without error thrown, before arriving at the if statement. I don't know if it's due to permissions issues or what as I am new to the development of BB.

    BB don't ask me if I want to give the status of the program trust, say yes to it not would still give the program the relevant permissions?

    Problem found. It is always the simplest that I end up spending days looking in!

    "File:///store/home/user/"
    

    Should have been...

    "file:///store/home/user/"
    
  • Problem downloading and saving a file text not in the SD card

    Hi all

    My goal is to download a KML file and save it to the SD card.

    My code did not throw any error and has also created a new file in the SD card. But the data inside is not correct.

    Someone please correct my mistake.

    Here is my code:

    public final class MyTest_ToDownloadAndSave extends {screen

    public MyTest_ToDownloadAndSave() throws IOException

    {

    StreamConnection conn = null;

    InputStream inputStream = null;

    FileConnection fConn = null;

    OutputStream outputStream = null;

    byte [] byteVal;

    StringBuffer sb = new StringBuffer();

    try {

    Conn is Connector.open (StreamConnection) ("https://sites.google.com/site/mykmltest1/multilockml/cta.kml", Connector.READ_WRITE);.

    inputStream = conn.openInputStream ();

    int ch;

    while ((ch = inputStream.read ())! = - 1).

    {

    SB. Append ((char) ch);

    }

    }catch(IOException e) {}

    throw new IOException ("problem with the URL");

    } {finally

    try {

    if (inputStream! = null ) {

    inputStream.close ();

    }

    if (conn! = null ) {

    Conn.Close ();

    }

    }catch(System.Exception e) {}

    throw new IOException ("close connections problem");

    }

    }

    "Rtx RichTextField = new RichTextField (downloaded successfully"+ sb.toString ());

    Add (RTX);

    try {

    fConn = (FileConnection)Connector.open("file:///SDCard/BlackBerry/cta2.kml",Connector.READ_WRITE);

    if (! fConn.exists ()) {

    fConn.create ();

    }

    outputStream = fConn.openOutputStream ();

    if (sb! =null & sb.toString ()! = "") {

    byteVal = new byte[sb.length ()];

    byteVal = sb.toString () .getBytes ();

    outputStream.write (byteVal);

    }

    RichTextField rtx1 is new RichTextField ("registered successfully");.

    Add (rtx1);

    }catch(IOException e) {}

    throw new IOException ("writing to SD card problem");

    } {finally

    try {

    if (outputStream! = null ) {

    outputStream.close ();

    }

    if (fConn! = null ) {

    fConn.close ();

    }

    }catch(System.Exception e) {}

    throw new IOException ("close connections problem");

    }

    }

    }

    }

     

    http://en.Wikipedia.org/wiki/List_of_HTTP_status_codes

    3xx is the guy you want

  • A few questions about FileConnection/JSR 75

    [I posted these issues some time ago, but got no response]

    I am writing an application that targets the 4.2.1 and upward. After reading everything I can find (api docs, forum, kb, guides, web search), I still have many questions about the BlackBerry file system:

    1. Are store / and SDCard / internal name of the memory and the SD card root on all BlackBerry devices?
    2. JSR 75 leaves open the question of whether an application sees the virtual roots that are private to itself or if all applications share the same roots. How does on BBs? I have seen many examples where the path name starts by "/ store/home/user/app_name /" or "/ SDCard/BlackBerry/app_name / '. Is this necessary, or can my request simply use "/ store /" or "/SDCard/" and add the file name? If the former, are there best practices documented anywhere to manage collisions between app names?
    3. If the files are visible in many applications, there are layers of security available to protect data (I think something similar to how a PersistentObject can be encapsulated in an object ControlledAccess using the PersistentStore) or do make us our own?
    4. I read on this forum somewhere that store / is not available when a device is connected via USB and mass storage is active. Is this and other information like this documented somewhere?
    5. May restrict the COMPUTER strategies how an application uses FileConnection, particularly to the store / and SDCard /? If so, is there any guidance on common restrictions that developers should know when you write applications for general use?
    6. What restrictions are there on the names of files (allowed characters, length, etc.)?

    Any guidance or pointers will be appreciated!

    Hi Ted,

    I'm not sure on your remaining questions, but I'll try to answer as best I can:

    1. did not have different names on the devices until today.

    2. you have no problem on SD card and you are allowed to save files anywhere it. Not quite sure

    shop around, but you should be able to save files on the file system visible and own created folders. There will be

    some folders inaccessible devices that require internal processing (installed Te of applications etc..).

    3. you can open files as readonly etc. but elsethere it is not the layers of security installed. If you have data

    issues of security, you must save this Te using the RuntimeStore class!

    4. I don't know, but it's a fact. But for this purpose, you can detect the toggling of mass storage

    programmatically.

    5 see point No. 3

    6 see restrictions as specified in JSR 75.

    Kind regards

    Jochen

  • FileConnection Connector.open throws the exception on Blackberry 7 when there is no file

    I'm trying to run a program I developed on Blackberry 6 on the torch 9801 running Blackberry 7.  When I try to open a folder that doesn't exist isn't using FileConnection Connector.open Blackberry 7 to launch a 1003 error. Under 6 Backberry, no exception is thrown, and I could use the FileConnection.exists () function to determine if the file exists. The directory, I'm trying to reference/store/home/user/IUIDChecker/my code below:

    private void createresultdirectory(String result_path) {
            try
            {    // the final slash in the folder path is required
                 FileConnection fc = (FileConnection)Connector.open("file:///" + result_path, Connector.READ_WRITE);
                 // If no exception is thrown, the URI is valid but the folder may not exist.
                 if (!fc.exists())
                 {
                     fc.mkdir();  // create the file if it doesn't exist
                 }
                 fc.close();
                 _currentPath = result_path;
             }
             catch (IOException ioe)
             {
                 Dialog.alert("Error: " + ioe.getMessage());
             }
        }
    

    I found the problem.  The error only occurs when I am runing through the debugger and I select USB key when I connect to my PC.  If I select Media Sync, the exception is not thrown.

  • FileConnection

    IM using the following code in 4.5 and it works perfectly for images on file / / / store, but fails in file:///SDcard. Can someone enlighten me.

    try {}
    FileConnection fconn = (FileConnection) Connector.open (myfile);
    If (fconn.exists ()) {}
    InputStream input = fconn.openInputStream ();
    available int = input.available ();
    data Byte [] = new ubyte [available];
    Input.Read (data, 0, available);
    EncodedImage image = EncodedImage.createEncodedImage(data,0,data.length);
    Bitmap b = image.getBitmap ();
    Photo of BitmapField = new BitmapField (b);
    hand. Add (Picture);
    hand. Add (new LabelField ("length of data:" + data.length));
    }
    else {}
    hand. Add (new LabelField ("photo does not exist"));
    }
    fconn. Close();
    }
    {} catch (Exception GOOSE)
    hand. Add (new LabelField ("Error"));
    }

    The problem is in your creation bytearray of inputstream.

    Try like this:

    try{
       FileConnection fconn = (FileConnection)Connector.open(myfile);
       if (fconn.exists())
       {
           InputStream input = fconn.openInputStream();
    
           //////////
           int SIZE = 100000;
           ByteArrayOutputStream byteArrayOutputStream = new
                              ByteArrayOutputStream();
           byte[] buffer = new byte[SIZE];
           while (true)
           {
             int bytesRead = input.read( buffer, 0, SIZE );
             if (bytesRead == -1) break;
             byteArrayOutputStream.write( buffer, 0, bytesRead );
           }
           byte[] data = byteArrayOutputStream.toByteArray();
           byteArrayOutputStream.flush();
           byteArrayOutputStream.close();
           ////////////
           //int available = input.available();
           //byte[] data = new byte[available];
           //input.read(data, 0, available);
           EncodedImage image =
                     EncodedImage.createEncodedImage(data,0,data.length);
           Bitmap b = image.getBitmap();
           BitmapField picture = new BitmapField(b);
           main.add(picture);
           main.add(new LabelField("Data Length:" + data.length));
       }
       else
       {
           main.add(new LabelField("Picture doesn't exist"));
       }
       fconn.close();
    }
    catch (Exception ioe) {
       main.add(new LabelField("Error"));
    }
    

    Concerning

    Bika

Maybe you are looking for