Thursday, 31 July 2014

How to show alternate image if source image is not found?

A example is here

Phonegap/Cordova: Download file

To download file in cordova you have to add following plugins:

1. File
2. File System
3. File Transfer

And example is here:
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, app.fileSystemSuccess, app.fileSystemFail);
        console.log('Received Event: ' + id);
    },

fileSystemSuccess: function(fileSystem) {
var directoryEntry = fileSystem.root;
directoryEntry.getDirectory("folder_rahul", {create: true, exclusive: false}, app.onDirectorySuccess, app.onDirectoryFail);
var rootdir = fileSystem.root;
var fp = rootdir.toURL();
alert(fp);
fp = fp + "folder_rahul/120px-State-lib-sum.png";
var fileTransfer = new FileTransfer();
   fileTransfer.download("http://data-gov.tw.rpi.edu/w/images/thumb/b/b1/State-lib-sum.png/120px-State-lib-sum.png",fp,
   function(entry) {
       alert("download complete: " + entry.fullPath);
   },
   function(error) {
cosnole.log(error);
       alert("download error source " + error.source);
       alert("download error target " + error.target);
       alert("upload error code" + error.code);
   }
);
},

fileSystemFail: function(evt) {
    alert("Failed---"+evt.target.error.code);
},

onDirectorySuccess: function(parent) {
console.log(parent);
},

onDirectoryFail: function(error) {
alert("Unable to create new directory: " + error.code);
}
};

More details are here and here

Monday, 28 July 2014

Angularjs filtered array length

In this example, I am applying a filter on list and after that I am getting the length.

<tr ng-show="showdate && (yourlist | filter:searchEmp).length > 0"><td class='appointment_header' style="font-weight:bold;" colspan="3"><span> {{----}}</span></td></tr>

Tuesday, 22 July 2014

Is it valid to replace http:// with // in a script src=“http://…”?

Yes, It is valid and good.

We don't have to think about protocol It can be http or https.

It is very helpful when we use CDN or any Google/Facebook or any other API.

Load javascript file dynamically using jquery with callback

Que: How to load javascript file dynamically using jquery?

Ans: jQuery.getScript("/xyz/abc/your.js", function(){
initialize(); // this function will call after loading of your.js
});

Solved: Android uninstall APK file from command line

Que: How to uninstall APK file from command line?

Ans: ./adb uninstall com.example.hello

"com.example.hello" this is the package name of your application.

Select2 get value and label of selected option

Que: How to get the value and label of option from select2 using jQuery?

Ans:

var theID = jQuery("#tags").select2('data').id;
var theSelection = jQuery("#tags").select2('data').text;

Here #tags is the id of your select2 field in html code. 

Solved:: Phonegap access origin problem with angularjs

I am giving simple steps to solve Phonegap access origin problem with angularjs

You have to create a filter at your java server side to allow cross domain requests (If your angularjs requests resources from any other java server):


A. Your java filter class will be look like as:
package com.abc.security.corsfilter.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CORSFilter implements Filter {
    public void destroy() {
    }

    public static String VALID_METHODS = "DELETE, HEAD, GET, OPTIONS, POST, PUT";

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException,
            IOException {
        HttpServletRequest httpReq = (HttpServletRequest) req;
        HttpServletResponse httpResp = (HttpServletResponse) resp;

        // No Origin header present means this is not a cross-domain request
        String origin = httpReq.getHeader("Origin");
        if (origin == null) {
            // Return standard response if OPTIONS request w/o Origin header
            if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
                httpResp.setHeader("Allow", VALID_METHODS);
                httpResp.setStatus(200);
                return;
            }
        } else {
            // This is a cross-domain request, add headers allowing access
            httpResp.setHeader("Access-Control-Allow-Origin", origin);
            httpResp.setHeader("Access-Control-Allow-Methods", VALID_METHODS);

            String headers = httpReq.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                httpResp.setHeader("Access-Control-Allow-Headers", headers);

            // Allow caching cross-domain permission
            httpResp.setHeader("Access-Control-Max-Age", "3600");
        }
        // Pass request down the chain, except for OPTIONS
        if (!"OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

B. Make entry of this filter in web.xml. Remember entry of this filter should be first, if you have any other filters entry in your web.xml

      <filter>
         <filter-name>CorsFilter</filter-name>
         <filter-class>com.certain.security.corsfilter.util.CORSFilter</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>CorsFilter</filter-name>
         <url-pattern>/*</url-pattern>

     </filter-mapping>


*******Now we are going to make changes in code of your phonegap application.******


Your phonegap activity class should look like this:

package com.example.hello;

import android.os.Bundle;
import org.apache.cordova.*;
import android.webkit.CookieManager;

public class HelloWorld extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
CookieManager.setAcceptFileSchemeCookies(true); // this must be in this class
        // Set by <content src="index.html" /> in config.xml
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///index.html");
    }
}

Changes in /usr/local/src/node-v0.10.29/hello/config.xml

use <access origin="*" />