• We Code
  • We Design
  • We Develope
  • We Write
  • We Share

menu

Wednesday, November 19, 2014

Cordova Contact API example with AngularJS and Onsen UI

0 comments
This tutorial is divide into three parts.

  1. Designing the template with onesen ui
  2. cordova contact plugin
  3. rendering the contact with angularl

First we will design the layout in onsen UI for the application.So first we will create a page holder. Onsen UI provides <ons-navigator> component to serve this purpose.As the page holder is created by <ons-navigator>.Now lets create a page by using <ons-page>.One thing i would like to clear before proceeding ahead <ons-page>  should be used as root element of the page. The whole page will be encapsulated within <ons-page>.We want to show the contact image  to right side and the contact information to left side.For doing this lets create a row by using <ons-row align="center">. Now devide this row into two columns by using <ons-col>.As we have now two equally devide layouts at the center.

Now lets create the placeholder for the contact information by using simple <div> component.Now lets add a button at the end to envoke some method. For creating a button in onen UI we need <ons-button> component. Lets add this component just before where page gets close i.e. before </ons-page>. So the final template of the app will be
<ons-navigator>
    <ons-page>
          <h3></h3>
          <ons-row align="center">
              <div class="Demo">
            <ons-col>                
               <div class="Demo">
              </div>               <hr />                
               <div class="Demo">
               </div>                <hr />                
              <div class="Demo">
              </div>             </ons-col>             <ons-col>
          <ons-button ng-click="pickAcontact()">Pick contact</ons-button>
                              </div>             </ons-col>           </ons-row>
</ons-navigator>
    </ons-page>
  Now our template is ready lets quickly add some css rules.
.item {
padding: 10px;
line-height: 1;
}
background-color: #ccc;
.item-thum {
height: 50px;
width: 50px;
.item-title {
border-radius: 4px; }
font-weight: 500;
font-size: 15px; } .item-desc {
line-height: 1.3;
font-size: 14px; color: #666; margin: 4px 0 0 0;
font-size: 12px;
padding: 0 30px 0 0; } .item-label { color: #999; float: right;
overflow: hidden;
} .col { border: 1px solid #ccc; background: #fff; padding: 4px;
padding: 8px;
color: #999; } .page__content { background-color: #f6f6f6; } h3 {
color: #666;
font-size: 17px;
}

  Now lets jump to the contact plugin of the cordova.First add the plugin by using "cordova plugin add org.apache.cordova.contacts" command. once the plugin is added into the application we can move ahead with this plugin . Lets quickly check whether plugin installed correctly by using cordova plugin ls.it will list the all installed plugin.
  Cordova provide navigator.contacts.pickContact api to access the contact from contact list. navigator.contacts.pickContact  takes two arguments first a success callback or a error callback.
   navigator.contacts.pickContact(function(contact){
    // contact can accessed here
   }).
   },function (err){
    //error callcback
   So  now lets play with angularJS.First of all define app ,module. Now create a controller. I have created a controller "AppController".Now create a method pickAcontact and bind this to button we created while designing the layouts by using ng-click directive.Now inside this methode call the pickContact api and on the success callback of the api add the result to $scope.contact. which we will use in the template. Now come cak to template and make data binding.The final html will be.

<ons-navigator>
    <ons-page>
          <h3></h3>
          <ons-row align="center">
              <div class="Demo">
            <ons-col>
              </div>
                {{ contact.name.formatted }}               <hr />
                {{ contact.emails[0].value }}            
               <div class="Demo">                 {{ contact.phoneNumbers[0].value }}
                {{ contact.addresses[0].postalCode }} <br />
               </div>                <hr />                <div class="Demo">
                {{ contact.addresses[0].streetAddress }} <br />
                {{ contact.addresses[0].locality }} <br />                 {{ contact.addresses[0].region }} <br />
              <div class="Demo">
                {{ contact.addresses[0].country }}               </div>             </ons-col>             <ons-col>
          <ons-button ng-click="pickAcontact()">Pick contact</ons-button>
                <img ng-src = "{{contact.photos[0].value}}" />               </div>             </ons-col>           </ons-row>     </ons-page>
  </ons-navigator>
  Come back to controller , after assigning the contact value to $scope.contact call the  $scope.$apply() ,  $scope.$apply(); will let the angular know there has been some changes made in values.

Read more ►

Monday, September 1, 2014

AngularJS ui-router tutorial from scratch - Part 1

0 comments
AngularJS is very powerful framework and provide the solution for almost every challenge without integrating any outside libraries. Angular UI library is broken in many parts so you can pick the feature and include only that in your angularJS application.
But still we can add libraries and make the angular application more powerful.
ui-router is one of most powerful ui library of the angularJS . Instead for just providing the url route it plays with the state. ui-router provide many extra and more powerful feature. We can have nested views , multiple views on one page or the multiple view wich have common controller .

INSTALLATION : For installing ui-router in your application you can install it through the bower
$ bower install angular-ui-router --save 



and then include the it in your HTML file
<script src="phoneCatApp/bower_components/angular-ui-router/release/angular-ui-router.js" type="text/javascript"></script>   
or

you can save the source code  from the GITHUB .



For using the ui-route you need to ui-router as a dependency in your module



<html ng-app="phoneCatApp">

<head>

<script src="script/angular.js"></script>

<!-- Include the ui-router script -->

<script src="script/angular-ui-router.min.js"></script>

<script>

    // ...and add 'ui.router' as a dependency

    var phoneCatApp= angular.module('phoneCatApp', ['ui.router']);

  </script>

</head>

<body>

</body>

</html>


If you used ng -router  then you most probably came across the ng-view directive . So here instead of using the ng-view we use ui-view ,the  views will get change inside this ui-view

<div ng-controller="mainController">

<div ui-view="">

</div>

</div>


Now we will write the config of the app for routing . It is very simmiler to the ng-route but instead of playing upon $routeProvider we deal with $stateProvider.

.config(function($stateProvider, $urlRouterProvider) {

$stateProvider

.state('first', {

url: '/first',

templateUrl: 'template/first.html',

controller :firstController

})

});


template  templateUrl and  templateProvider 

 These three are used  for setting the views .You can use any of them according to your needs .

  1. template - template is a  string of HTML content or a function that returns HTML
  2. templateUrl - templateUrl is a  string of a URL path to a template or a function that returns a URL path string
  3. templateProvider - templateProvider is a  function that returns an HTML content string

Controller 

 controller is used to bind the controller to the view. Which can operate over the view 

url 

 This work very simmiler to the ng-route  but have many upgrades in it .Which we will discuss in future.



How to route ?

1 . ui-sref 

 ui-sref work smiler to the href but it have more capability . It takes the stateName as the the parameter .


<a  ui-sref="first">First</a> 

2 . $state.go

  If you want to change the view from controller then you need to use $state.go . The syntax is

go(to, params, options)

  • $state.go('first') will take it to first state.
  • $state.go('^') - will take it to a parent state
  • $state.go('^.sibling') - will take it to a sibling state
  • $state.go('.child.grandchild') - will take it to grandchild state



This is the first part of ui-router. I will discuss many other parts in next series of it.
Read more ►

Sunday, July 20, 2014

Promises in JavaScript: What are they and How to use them?

0 comments
Asynchrony is unavoidable in any platform these days. Asynchrony doesn’t just help the servers to serve their clients better but it also maximizes effective utilization of the resources. JavaScript is no exception.
In recent times, use of asynchronous programming became very important as the expectations out of the software systems that we are writing is went up drastically. And even some of the browser APIs like Indexed DB work on an asynchronous model.
Traditional way of handling asynchronous tasks is the callback model. As the asynchronous tasks are handled by a separate thread or a separate process in some cases, the main program using the asynchronous task doesn’t know when the operation is going to be finished. So, we attach a callback function to the asynchronous task and the attached method would be called when the task is done.Though this approach looks good for upto a chain of one or two asynchronous tasks, it makes the code less readable when we have 3 or more async operations that depend on the result of the previous
operation. Following is an example of such scenario:

Promises: What are they and How to use them?

firstAsyncOperation.onOperationCompleted = function(

if(operationObject.state == “success”){

var secondAsyncOperation = secondAsyncFunction(operation.resultData);

  secondAsyncOperation.onOperationCompleted = function(){

   if(secondAsyncOperation.state == “success”){

     var thirdAsyncOperation = thirdAsyncOperation();

      thirdAsyncOperation.onOperationCompleted = function(){

       if(thirdAsyncOperation.state == “success”){


       }


      };


    }

      };

}else {

//May be some other async operation to handle error case
}

};
That might look beautiful with nice switch between the curly braces and parentheses, but it becomes difficult to manage such code blocks. It becomes really painful when you have to write such blocks multiple times in your code. Promise is a pattern created to solve this issue. Rest of the article speaks about the pattern of promises and how to use them to address this kind of issue.

What is Promise ?
A promise is an object that holds an asynchronous operation. At any given point of time, the object is in one of the three states:

• Pending: When the asynchronous operation is still going on

• Success: When the async operation is successfully completed

• Failed: When the async operation is completed but failed

The promise specification doesn’t tell how to implement a promise, but it says what should be implemented. According to the specification, any promise implementation should have a then callback that accepts two callbacks: one for success and the other for failure. Some implementations (such as Q) also accept a third callback that is invoked when the operation is in progress.

A typical asynchronous operation handled by a Q promise looks like:



asyncOperationObject.then(successCallback, errorCallback, inProgressCallback);

function successCallback(data){
     //----------
     //----------

     //---------- 

    }

function failureCallback(error){

 //----------
 //----------
 //---------- 

 }


 function inProgressCallback(info){

 //----------
 //----------

 //---------- 
 }

 

In general, we pass in anonymous functions as callbacks to the then method. The syntax is shown below:




asyncOperationObject.then(function (data){
//--------
//--------
}, function (error){
//----------
//----------

}, function (info){
//----------
//----------

});


One can include or ignore the callbacks depending upon the need. In most of the scenarios, we ignore the in-progress callback. It can be used to show when there is a need to show a progress bar to indicate the current state.

Chaining Promises

The very first thing we saw in this article is, how dangerous the callback model is for chaining async operations. The best part about the promises is that, the then method also returns a promise object.
This means, we can return another then on the return object.




asyncOperationObject.then(function(data){

   return data;

  }, function(error){

    console.log(error);

  })

  .then(function(data){

    return data

  }, function(error){

    console.log(error);

  })

  .then(function(data){

   return data;

  }, function(error){

   console.log(error);

  });


Though the above operation is chained,it still looks flat. It is very easy to manage such operations as well. More than everything, it is easy to read the subsequent then blocks.

Conclusion:
Understanding promises is very crucial these days. It is an important pattern to be followed in every JavaScript heavy application. There are several implementations of promises, including Q, jQuery’s deferred API, Angular’s $q (inspired from Q), RSVP, when.js and so on. Promises got a place in the ES6 specification as well. It is already implemented in latest versions of many of the major browsers.

Happy promising!



About Author : 
Name :S Ravi 
Twitter : https://twitter.com/SRavi_Kiran
Bio: Software Professional, Passionate about Microsoft technologies, Blogger, Love to pass time with Music and Cricket
Read more ►

Monday, June 2, 2014

AngularJs $apply $digest in Detail With Error Handeling

0 comments
The best practice to change the value of bindings is $apply . What $apply actually does ? it update the bindings of the page and notify the value has changes . it calls $digest internally and return the promise. Almost whole angular binding run inside $digest.
 $scope.$apply('foo = "bar"');

//or
 $scope.$apply(function(scope) {
scope.foo = 'bar';
});

//or
 $scope.$apply(function(){
$scope.foo = 'bar';
 });


I was trying to change the scope value with ng-click . And i kept getting a error . Error: $apply already in progress.
If you are also facing the same error I found two solution for it
First Solution : you can put the putAsafeApply method , which wil check the status of the $apply .

$scope.putAsafeApply = function(fn) {
var status = this.$root.$$phase;
if(status == '$apply' || status == '$digest') {
 if(fn && (typeof(fn) === 'function')) {
 fn();
 }
 } else {
this.$apply(fn);
}
};


$scope.$$phase or $scope.$root.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and it's children, and $apply will process the watchers of all scopes.

So now we have putAsafeApply method and we can use it where ever we want to use instead of $apply.


$scope.putAsafeApply(function() {
 $scope.foo = 'bar';
});



Second Solution : It is simpler then the first one .You can use the $apply inside the $timeout function without delay.

$timeout(function(){
$scope.foo = 'bar';
})


 $timeout(callback) will wait until the current digest cycle (if any) is done, then execute your code, then run at the end a full $apply which will call $digest internally as explained earlier .



Read more ►

Thursday, May 29, 2014

PhoneGap / Cordova Unzip Plugin for android

0 comments


While developing A phoneGap application i faced a problem in unzipping a folder. I downloaded a folder in zip from server using FileTransfer API.
I searched a lot for UnZIP plugin of phone gap but did not find any one the net . Than i started writing a fresh cordova plugin for unzipping

There is few prerequisite before using this plugin
Node.js and Cordova CLI or PhoneGap's CLI


Installation : 1 . Open Your terminal and go to your project directory
2 . Enter this command
phonegap  plugin add https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git
  
or If you using cordova
cordova  plugin add https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git
or you can download the plugin from Git repo Manually

https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git



3 .I Assume you downloaded the plugin manually from git repo

Copy the com folder inside the src folder under your android project

4 .Copy ExtractZipFile.js file inside your www folder and make its reference in index.html

5 . Open res/xml/config.xml file from your project and paste the line
   <feature name="ExtractZipFile">
                        <param name="android-package" value="com.phonegap.plugin.ExtractZipFile.ExtractZipFilePlugin"/>
                </feature>

or 
 <plugin name="ExtractZipFile" value="com.phonegap.plugin.ExtractZipFile.ExtractZipFilePlugin" />


or Usage :
function extractOK(status)
{
    console.log("extractOK");
}

function extractError(error)
{ 
    console.log("extractError "+error);
}


function extractFile(zipfile)
{
    console.log("Extracting "+ zipfile);
    extractZipFile.unzip(zipfile, extractOK, extractError);
}


Get the file reference and pass as parameter in function extractFile(zipfile) . And you are done with extractFile


Git Repo Link : https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin
Read more ►

Friday, May 23, 2014

Knowledge Optimization and Knowledge Sharing in Java Technology

0 comments
Information is crucial to the organizations and individuals as it helps them to protect their data, wealth as well as assets but often there has been the challenge of sharing this data with others for them to exploit it to their advantage and any other intended purpose. As a result of this therefore, there is need to allocate more resources and time to the sharing of this information by the different people. Governments, individuals as well as corporate and organizations therefore have set out to come up with better ways of enhancing the sharing of their data in the information systems. One better way of doing this is through the sharing of the knowledge through the Java Technology and software.

Consistency in publishing of the blog posts
Although patterns of publishing of blog posts with regards to the regularity with which they are done are determined by the nature of the content and the idea of the blog site, it should be done as often as possible. Often the successful way to attract and maintain visitors to a site could be through regular publishing of quality content for the blog site which will not only appeal to the visitors but also keep them coming back to the site. Attracting more people will widen the scope of the search of the website on the search engines as well as improve the rank of the website in the search engines and this will improve the visitors to the website as well.
Maintaining the visitor numbers high to the website can also achieved through other strategies such as inclusion of survey or polls done on a frequent regular basis like daily or weekly. This could also be done alongside inclusion of a visitor’s book in the website as a strategy to improve and notice the guest frequency.
Keep the visitors interested by asking questions related to the blog post
The development of questions relevant to the particular blog post will always keep the visitors asking more about the topic of discussion. This will also ensure their involvement as they will attempt to respond to the question in the comments section. Their contribution not only improves the content of the website but may also highlight the challenges especially with regards to products or services for a business, advertisement or sales promoting or related website.
Networking
This is especially relevant when done with other blogs which are directly related to the area of interest of the website. It provides users of other sites a direct link to your website from the other site. Inclusion of links to the website in comment sections of other blogs which are dealing with related fields could also be a good strategy to improve visitor frequency in the site.
Inclusion of sharing button or option in the site also allows the users as well as visitors to share information that they find useful or relevant to the site. This will also allow them to spread the links of the bog by sharing them on social media as well as through their personal emails. Use of handles such as twitter, Facebook which allow for instant feedback is also good for the promotion of the site as well as attracting more users.
Quality content
Successful implementation of the java technology as a tool of sharing information will heavily hinge on the content that is being shared. When the content is short, precise and to the point then it is likely to appeal to many people rather than a redundant, long and boring content that is discouraging to read. Sharing of information that is useful and healthy for people will ensure that they read and want to read more the content associated or being passed through the Java technology. However much any content is shared and optimized across the different mediums and channels for consumption by the users, it will not be able to do much or achieve much with regards to impact if the content is not acceptable by the readers.
Avoid duplication of content
When the content being shared is one that has been duplicated and lack originality, it tends not to appeal to the readers and this may perhaps affect the consumption of the content and the general perception of the contents with regards to the reliability of the java technology as a source of information. It is therefore critical to avoid the duplication of content that is especially to be passed on to the people through the java technology.
Avoid issues of copyright
Any content that is to be passed on through the java technology should be able to be shared without any challenges especially with regards to issues of copyright. Most of the copyright issues have to do with the plagiarism of content without the author’s knowledge or permission or even acknowledging the author. Hence therefore there is need to prevent the issues of plagiarism or any other issues that may lead to copyright law suits and such.
Content should be content specific
When content is said to be specific this implies that is should be precise so that it only highlight the key point and remains within the scope of the subject of interest. Redundancy tends to arise because of the inclusion of irrelevant content which does not even relate or touch on the subject of interest in any way.
Avoid promotional content
Such technology is supposed to pass knowledge and not be used as forums to do promotion of other products and services. Therefore this should be avoided at all cost as it may lead to disregard of the content being shared even if it is relevant and worth reading.
Create links and addition share buttons
Inclusion of links and share buttons are necessary to allow for further sharing of the knowledge especially through the social sites. This could also be extended and done on the email so that the information can be channeled out as much as possible.


Author’s Bio: He is a writer by profession. He contributes articles and blogs on travelling, education, technology, fashion and shopping. He has good knowledge in all writing field. He helps the student’s any papers to buy from custom essay writers.
Google+ profile

Read more ►

Thursday, February 13, 2014

Show loading screen in Phonegap app over inAppBrowser

0 comments
The trick is very simple for showing the loading screen in phonegap application.You Just need to call activityStart function of the notification.


For hiding the loading screen in phonegap just call activityStop function.

The loading screen is very helpful while making Ajax call or while using the inappbrowser.It is really useful when loading the external link in inappbrowser.It is useful because you can not create a loading screen through your HTML in client side if you are loading the external link.Because inappbrowser overlay on the application.You can show the loading screen when loadstart events fire in Inappbrowser hide it when loadstop events fire.
Here is an example of loading screen with inappbrowser.




This phonegap loading screen only works with the android .And if you will touch the screen The loading screen will get hide.
Read more ►