PhoneGap: File API Sample Client Class Code


/**
 * User: mdshahabuddin
 * Date: 11/1/12
 * Time: 11:56 AM
 * To change this template use File | Settings | File Templates.
 */
var FileClient = (function () {

    var fileSystem = null;

    /*
     init function must be called once before using any other function of this class
     */
    function init(successCallback, errorCallback) {
        console.log("||FileClient.init||");
        /*
         LocalFileSystem.PERSISTENT: persistent file system
         LocalFileSystem.TEMPORARY: Used for storage with no guarantee of persistence.
         */
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
            function (result) {
                fileSystem = result;
                console.log('fileSystem Created at: ' + fileSystem.root.fullPath);
                // we may call successCallback here, or after creating directories
                createDirectory(successCallback,
                    function (err) {
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
            }
        );
    }

    function createDirectory(successCallback, errorCallback) {
        console.log("||FileClient.createDirectory||");

        var directoryList = ['folder1/', 'folder2/', 'folder3/'];
        var len = directoryList.length;

        (function createNext(index) {
            if (index < len) {
                fileSystem.root.getDirectory(directoryList [index], {create:true, exclusive:false},
                    function (parent) {
                        console.log("directory: " + directoryList [index] + " created successfully");
                        createNext(index + 1);
                    },
                    function (err) {
                        console.log("directory: " + directoryList [index] + " failed to create");
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            } else {
                successCallback();
            }
        })(0);      // calling the createNext function with arg 0
    }

    function writeToFile(file, data, successCallback, errorCallback) {
        console.log("||FileClient.writeToFile||");
        fileSystem.root.getFile(file, {create:true, exclusive:false},
            function (fileEntry) {
                fileEntry.createWriter(
                    function (writer) {
                        writer.write(data);
                        writer.onwrite = function (evt) {  // Called when the request has completed successfully.
                            if (successCallback) successCallback(evt);
                        }
                    },
                    function (err) {
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
            }
        );
    }

    function readFileContent(filepath, successCallback, errorCallback) {
        console.log("||FileClient.readFileContent||");
        fileSystem.root.getFile(filepath, {create:true},
            function (fileEntry) {
                fileEntry.file(
                    function (file) {
                        var reader = new FileReader();
                        reader.onload = function (evt) {  // Called when the read has successfully completed.
                            if (successCallback) successCallback(evt.target.result);
                        };
                        reader.onerror = function (err) {
                            if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                        };
                        reader.readAsText(file);
                    },
                    function (err) {
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
            }
        );
    }

    function removeFile(file, successCallback, errorCallback) {
        console.log("||FileClient.removeFile||");
        fileSystem.root.getFile(file, {create:false, exclusive:true},
            function (fileEntry) {
                fileEntry.remove(successCallback,
                    function (err) {
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            },
            function (err) {
                if (err.code == FileError.NOT_FOUND_ERR) {
                    // file not found means its not there or may be already deleted. calling successHandler ...
                    if (successCallback) successCallback();
                } else {
                    if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                }
            }
        );
    }

    function removeDirectory(directoryPath, successCallback, errorCallback) {
        console.log("||FileClient.removeFile||");
        fileSystem.root.getDirectory(directoryPath, {},
            function (parent) {
                parent.removeRecursively(successCallback, errorCallback);
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});

            });
    }

    function removeFilesInADirectory(directoryPath, successCallback, errorCallback) {
        console.log("||FileClient.removeFile||");
        fileSystem.root.getDirectory(directoryPath, {},
            function (parent) {                                 // successHandler: directory found
                var dirReader = parent.createReader();          // creating a reader to read the directory
                dirReader.readEntries(// trying to read the directory
                    function (entries) {
                        var len = entries.length;               // directory files list

                        (function deleteNext(currIndex) {
                            currIndex++;
                            if (currIndex < len) {
                                entries [currIndex].remove(// removing a single file
                                    function (data) {
                                        deleteNext(currIndex + 1);
                                    },
                                    function (err) {
                                        // there is an error though, shouldn't we try to continue?
                                        deleteNext(currIndex + 1);
                                    }
                                );
                            } else {
                                if (successCallback) successCallback();
                            }
                        })(0);
                    },
                    function (err) {
                        if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
                    }
                );
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileErrorMessage(err)});
            }
        );
    }

    function fileUpload(filePath, successCallback, errorCallback) {
        console.log("||FileClient.fileUpload||");
        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
        options.mimeType = "text/plain";
        options.params = {'key1':'value1', 'key2':'value2'};  // additional data, json object

        var fileTransfer = new FileTransfer();
        fileTransfer.upload(filePath, encodeURI("https://file.server.com/upload"),
            function (data) {
                console.log("Response: " + data.response);
                if (successCallback) successCallback(data);
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileTransferErrorMessage(err)});
            }
            , options);
    }

    function fileDownload(remoteUrl, localPath, successHandler, errorHandler) {
        console.log("||FileClient.fileUpload||");
        var fileTransfer = new FileTransfer();
        fileTransfer.download(remoteUrl, localPath,
            function (data) {
                console.log("download complete: " + data.fullPath);
                if (successHandler) successHandler(data);
            },
            function (err) {
                if (errorCallback) errorCallback({'obj':err, 'msg':getFileTransferErrorMessage(err)});
            }
        );

    }

    function getFileErrorMessage(err) {
        console.log("||FileClient.getFileErrorMessage||");
        var ret = "";

        switch (err.code) {
            case FileError.NOT_FOUND_ERR:
                ret = "Not Found Error";
                break;
            case FileError.SECURITY_ERR:
                ret = "Security Error";
                break;
            case FileError.ABORT_ERR:
                ret = "Abort Error";
                break;
            case FileError.NOT_READABLE_ERR:
                ret = "Not Readable Error";
                break;
            case FileError.ENCODING_ERR:
                ret = "Encoding Error";
                break;
            case FileError.NO_MODIFICATION_ALLOWED_ERR:
                ret = "Not Modification Allowed Error";
                break;
            case FileError.INVALID_STATE_ERR:
                ret = "Invalid State Error";
                break;
            case FileError.SYNTAX_ERR:
                ret = "Syntax Error";
                break;
            case FileError.INVALID_MODIFICATION_ERR:
                ret = "Invalid Modification Error";
                break;
            case FileError.QUOTA_EXCEEDED_ERR:
                ret = "Quota Exceeded Error";
                break;
            case FileError.TYPE_MISMATCH_ERR:
                ret = "Type Mismatch Error";
                break;
            case FileError.PATH_EXISTS_ERR:
                ret = "Path Exists Error";
                break;
            case "null":
                ret = "Null Error";
                break;
            default:
                ret = "Undefined Error";
        }

        ret = "Err code: " + err.code + " Err Msg: " + ret;

        return ret;
    }

    function getFileTransferErrorMessage(err) {
        console.log("||FileClient.getFileTransferErrorMessage||");
        var ret = "";

        switch (err.code) {
            case FileTransferError.FILE_NOT_FOUND_ERR:
                ret = "File Not Found Error";
                break;
            case FileTransferError.INVALID_URL_ERR:
                ret = "Invalid URL Error";
                break;
            case FileTransferError.CONNECTION_ERR:
                ret = "Connection Error";
                break;
            case "null":
                ret = "Null Error";
                break;
            default:
                ret = "Undefined Error";
        }

        ret = "Err code: " + err.code + " Source: " + err.source + " Target: " + err.target + " HttpStatus: " + err.http_status + " Err Msg: " + ret;

        return ret;
    }

    var pub = {};

    pub.init = init;
    pub.createDirectory = createDirectory;
    pub.writeToFile = writeToFile;

    return pub;

})();
Advertisements

PhongGap: Rotate image using Compass or Phone Position


compass.html

<!DOCTYPE html>
<html>
<head>
    <title>PhongGap</title>
</head>
<body>

<div data-role="page" id="compass-page">
    <div>
        <img src="images/compassneedle.png" id="needle"/>
    </div>

    <div data-role="footer" data-position="fixed">
        <div data-role="navbar">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="map.html">Map</a></li>
                <li><a href="compass.html" class="ui-btn-active">Compass</a></li>
            </ul>
        </div>
    </div>

    <script type="text/javascript" charset="UTF-8" src="scripts/jQueryRotateCompressed.2.2.js"></script>
    <script type="text/javascript" charset="UTF-8" src="scripts/compass.js"></script>
</div>

</body>
</html>

compass.js


// get called when clicked on compass.html link
$(document).delegate("#compass-page", 'pageinit', function (event) {
    onCompassLoad();
});

function onCompassLoad(){
    console.log('onCompassLoad');
    var options = {frequency: 500}; // rotateNeedle will fire at every 500ms
    navigator.compass.watchHeading(rotateNeedle, compassError, options);
}

function rotateNeedle(degree){
    console.log('rotateNeedle: ' + JSON.stringify(degree));
    // sample content of variable 'degree':
    // {"magneticHeading":138.59375,"trueHeading":138.59375,"headingAccuracy":0,"timestamp":1350667862515}
    // 'magneticHeading' is a heading relative to the magnetic poles of the Earth;
    // 'trueHeading' is a heading relative to the actual North and South Poles of the Earth (around which the planet rotates)
    $('#needle').rotate(degree.magneticHeading);
}

function compassError(err){
    alert('code: ' + err.code + '\n' + 'message: ' + err.message);
}

PhoneGap: Displaying Google Maps with Markers


map.html


<!DOCTYPE html>
<html>
<head>
    <title>PhoneGap</title>
    <meta name="viewport" content="initial-scale=1.0" user-scalable="no"/>
</head>
<body>

<div id="map" data-role="page" id="map-page">
    <div id="map_canvas" style="width: 300px; height: 400px"></div>
    <div data-role="footer" data-position="fixed">
        <div data-role="navbar">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="map.html" class="ui-btn-active">Map</a> </li>
            </ul>
        </div>
    </div>

    <script type="text/javascript" charset="utf-8" src="scripts/map.js"></script>
</div>

</body>
</html>

map.js


// get called when map.html will be loaded 
$(document).delegate("#map", 'pageinit', function (event) {
    onMapLoad();
});

function onMapLoad(){
    console.log("*onMapLoad*");
    if(navigator.network.connection.type != Connection.NONE) {
        // internet available

        var fileref = document.createElement('script');
        fileref.setAttribute('type', 'text/javascript');
        // getGeolocation get fired when google maps api script loaded successfully
        fileref.setAttribute('src', 'http://maps.googleapis.com/maps/api/js?sensor=true&callback=getGeolocation');
        document.getElementsByTagName('head')[0].appendChild(fileref);
    } else {
        alert('Internet Connection not available.')
    }
}

function getGeolocation(){
    console.log("*getGeolocation*");
    var options = {
        maximumAge: 600000,         // We accept positions whose age is not greater than 10 minutes.
        timeout: 30000,             // if there is no cached position available at all, the user agent
                                    // will immediately invoke the error callback after "timeout" 30 seconds
        enableHighAccuracy: false   // true, if you need high accuracy
    };
    // when the geolocation is successfully received, loadMap will be fired
    navigator.geolocation.getCurrentPosition(loadMap, geoError, options);
}

function loadMap(position){
    console.log("*loadMap*: " + position.coords.latitude + ' ' + position.coords.longitude);
    var latlng = new google.maps.LatLng(
        position.coords.latitude, position.coords.longitude);
    var myOptions = {
        zoom: 12,           // zoom level. more value = more details
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var mapObj = document.getElementById("map_canvas");
    var map = new google.maps.Map(mapObj, myOptions);

    // marker will be displayed on the lat long position
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
}

function geoError(err) {
    console.log("*geoError*");
    alert('code: ' + err.code + '\n' + 'message: ' + err.message + '\n');
}

PhoneGap: Startup or Bootstrap Javascript & index file


init.js

// collected from: Jamie Munro

// Global variable that will tell us whether phonegap is ready
var isPhoneGapReady = false;

function init(){
    // onDeviceReady will be fired: soon as device is ready
    document.addEventListener('deviceready', onDeviceReady, false);
}

function onDeviceReady() {
    isPhoneGapReady = true;

    console.log('*Device is ready');
    console.log('*Device UUID: ' + device.uuid);
    console.log('*Device Platform: ' + device.platform);
    console.log('*Device Name: ' + device.name);
    console.log('*Device Version: ' + device.version);

    networkDetection();

    // attach events for online and offline detection
    document.addEventListener("online", onOnline, false);   // fired: soon as user go online
    document.addEventListener("offline", onOffline, false); // fired: soon as user go offline
}

function networkDetection(){
    if(isPhoneGapReady) {
        if(navigator.network.connection.type != Connection.NONE) {
            console.log('*Internet Available: ' + navigator.network.connection.type);
        }
        /*
         navigator.network.connection.type values:

         consider slow internet connection
         Connection.UNKNOWN
         Connection.CELL_2G

         consider fast internet connection
         Connection.CELL_3G
         Connection.WIFI
         */
    }
}

function onOnline(){
    console.log('*user connected Online');
}

function onOffline(){
    console.log('*user goes Offline');
}

// fired: when the application first loads
window.onload = init;

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Cordova</title>

    <!--Jquery Mobile library with respective css files added -->

    <link rel="stylesheet" href="styles/jquery.mobile-1.2.0.min.css"/>
    <link rel="stylesheet" href="styles/jquery.mobile.structure-1.2.0.min.css"/>
    <link rel="stylesheet" href="styles/jquery.mobile.theme-1.2.0.min.css"/>

    <script type="text/javascript" charset="UTF-8" src="scripts/cordova-2.0.0.js"></script>
    <script type="text/javascript" charset="UTF-8" src="scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" charset="UTF-8" src="scripts/jquery.mobile-1.2.0.min.js"></script>
    <script type="text/javascript" charset="UTF-8" src="scripts/common.js"></script>
</head>
<body>

<h1>Hello Phonegap</h1>

<div data-role="footer" data-position="fixed">
    <div data-role="navbar" data-theme="e">
        <ul>
            <li><a href="index.html" class="ui-btn-active">Home</a></li>
            <li><a href="about.html">About</a></li>
        </ul>
    </div>
</div>

</body>
</html>

phonegap first screen