Sunday, 31 March 2013

Create a Custom Model Validation Method in Sencha Touch 2

If you don't have knowledge on Model Validation in Sencha Touch 2 , Please visit this link for brief introduction about how model validation works in sencha touch2.

 Sencha Touch 2 Models have strong support for validating its data and it supports various validation types shown below

 1) presence -  Ensures that the field has a value. Zero counts as a valid value but empty strings do not.

 2) length  - Ensures that a string is between a minimum and maximum length. Both constraints are optional.

Saturday, 30 March 2013

How to declare global variables in Sencha Touch 2

Every Application requires to set Global Variables in order to access anywhere in your application.

For Example, Let's say if you want to set the BaseUrl and if you want to modify it, you need to modify it in one place instead of modifying more places of your application.

In Sencha Touch 2, declaring Global Variables is easy and it need to be  written inside Ext.Application. Below is the way to do it.

Thursday, 28 March 2013

How to merge objects in sencha touch 2

In sencha Touch 2,  Ext.Object.merge() is used to merge one or more objects into source object. In other Words, its used to add new properties and overwrite existing properties into source object.

This method accepts the following parameters
  • source : The first object into which to merge the others.
  • objs :  One or more objects to be merged into the first.
Let's demonstrate this by providing an example
var source = {
   id: '100',
   headline: 'This is test article',
   company:{
      name: 'opensource',
      platform: 'Extjs'
   }  
}

var object1 = {
   id: '110',
   company:{
      name: 'sencha',
      platform: 'Extjs',
      version: '4',
      mobile: 'sencha touch',
      mobileversion: '2'
   }  
}
var result = Ext.Object.merge(source,object1);
This method is very useful, if you need to merge objects into model object.

Here is the output for variable result
{
   id: '110',
   headline: 'This is test article',
   company:{
      name: 'sencha',
      platform: 'Extjs',
      version: '4',
      mobile: 'sencha touch',
      mobileversion: '2'
   }  
}

Hope, you enjoyed this Post.

Format Date issue in Sencha Touch 2

In order to display the date in sencha touch 2, I tried the below code
issueName = new Date("2013-02-14");
issueName = Ext.Date.format(issueName,"F d, Y");
It works fine in Google Chrome, But i got 'undefined' error in safari. So i tried the below code
var pubDate = "2013-02-14";
issueName = pubDate.replace(/-/g,'/');
issueName = Ext.util.Format.date(issueName,"F d, Y");

This works fine for both Chrome and Safari Browser. I hope this Post this will be helpful for those who may came across this same issue. Hope, you enjoyed this Post.

Create a Basic Form using Android SDK

Today, We are going to see how can create a Basic Form using Android SDK 4.2 . This Form will contain the following fields- Name, Email and Content.

Create a new Android Application project from eclipse with the following settings

Application Name: BasicForm
Project Name: BasicForm
Package Name: com.example.basicform
Activity Name: FormActivity
Android SDK: 4.2 (Choose a SDK that suits your test devices and favored emulator configuration)

In Package Explorer, create activity_form.xml file under res->layout folder and paste the below xml code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".FormActivity" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Fill The Form" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Name:" />
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email:" />
    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textEmailAddress" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Content:" />
   <EditText
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:ems="10"
        android:inputType="textMultiLine" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />
</LinearLayout>

In Package Explorer, Create FormActivity.java file under src->com.example.basicform folder and paste the below code
package com.example.basicform;
import android.os.Bundle;
import android.app.Activity;

public class FormActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form);
  }
}

Activity is used to create an UI for the application, in other words its similar to creating a window.
setContentView is used to display the desired content inside the activity window. The desired content is placed inside the layout activity_form.xml File.

In AndroidManifest.xml, Place the below activity XML code inside <application>
<activity
            android:name="com.example.basicform.FormActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

Thats it, Now you can run your application, by right clicking Package Name, then select Run As->Android Application. Based on my Android Emulator Configuration, i am getting the below Output.


Hope, you enjoyed this Post.

Download the Source Files Here

Wednesday, 27 March 2013

How to add events to native calendar App in Android

Today, Let's see how we can add events to user native calendar App in Android. The Calendar App is a most common application that users rely upon on their device. Applications can access the Calendar App using the new APIs available in Android 4.0. Adding new events to the Calendar is easy and  requires special Read and Write calendar  application permissions.

Let's demonstrate this by an example. This example will contain Add Events Button, but clicking on that button add Event Calendar screen will get displayed.

Create a new android application project from eclipse with these below settings

Application Name: EventCalendar
Project Name: EventCalendar
Package Name: com.example.eventcalendar
Target SDK: Android 4.2 (Choose a SDK that suits your test devices and favored emulator configuraton)

In Package Explorer, create activity_eventcalendar.xml file under res->layout folder and paste the below xml code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Events" />
</LinearLayout>

In Package Explorer, Create EventCalendarActivity.java file under
src->com.example.eventcalendar  folder and paste the below code
package com.example.eventcalendar;

import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class EventCalendarActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_eventcalendar);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {

         // Perform action on click
         addCalendarEvent();
      }

    });

  }

  public void addCalendarEvent(){

    Calendar cal = Calendar.getInstance();     
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", true);
    intent.putExtra("rrule", "FREQ=YEARLY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    intent.putExtra("description", "A Test Description from android app");
    intent.putExtra("eventLocation", "Geolocation");
    startActivity(intent);

  }
}

Explanation:
Calendar cal = Calendar.getInstance();

Above method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time.
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");

Above Intent class will launch the calendar app screen that will display add event form for add/edit purpose.
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
intent.putExtra("description", "A Test Description from android app");
intent.putExtra("eventLocation", "Geolocation");

Intent Extras are used to supply Event Information to Calendar, which contain title of the Event, its description, start and end date and so on.These details will be set in a  form that displays for the user to confirm the event in their calendar. There are several other intent extras you can set as well. For detailed information, please visit here.

startActivity() is used to launch a new activity  or get an existing activity to do something new.

Final Thing:

In AndroidManifest.xml, Place the below activity XML code inside <application>

<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<activity
            android:name="com.example.eventcalendar.EventCalendarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>


Thats it, Now you can run your application, by right clicking Package Name, then select Run As->Android Application.

Important Note: The user is responsible for configuring the Calendar application with the appropriate Calendar accounts (e.g. Google Account, Microsoft Exchange).

Hope, you enjoyed this Post.

How to get Screen Resolution in Android

Today, We are going to see how we can get device display screen resolution. Each mobile device in the market comes with different size and resolution. There will be situation in your project where you need to know the device display screen resolution. Let's demonstrate this by providing a example

We will be displaying a "Get Screen Resolution" Button, by clicking on that button we will be displaying the screen width and height information

Create a new android application project from eclipse with these below settings

Application Name: DisplayScreen
Project Name: DisplayScreen
Package Name: com.example.displayscreen
Activity Name: ScreenActivity
Target SDK: Android 4.2 (Choose a SDK that suits your test devices and favored emulator configuration)

In Package Explorer, create activity_screen.xml file under res->layout folder and paste the below xml code.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get Screen Resolution" />
<TextView
    android:id="@+id/hello"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Your Screen Resolution">
</TextView>
<TextView
    android:id="@+id/width"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</TextView>
<TextView
    android:id="@+id/height"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</TextView>

</LinearLayout>

In Package Explorer, Create ScreenActivity.java file under src->com.example.displayscreen folder and paste the below code
package com.example.displayscreen;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ScreenActivity extends Activity {

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_screen);
    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View arg0) {

    // Perform action on click

    getScreenResolution();

    }

    });      

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if present
    getMenuInflater().inflate(R.menu.main, menu);

    return true;

  }

  @SuppressLint("NewApi")

  public void getScreenResolution(){
    Display display = getWindowManager().getDefaultDisplay();

    Point size = new Point();

    display.getSize(size);

    TextView widthView = (TextView) findViewById(R.id.width);

    TextView heightView = (TextView) findViewById(R.id.height);

    widthView.setText("Width: "+size.x);

    heightView.setText("Height: "+size.y);

  }
}

In AndroidManifest.xml, Place the below activity XML code inside <application>

<activity
            android:name="com.example.displayscreen.ScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

Thats it, Now you can run your application, by right clicking Package Name, then select Run As->Android Application. Based on my Android Emulator Configuration, i am getting the below Output.


Hope, you enjoyed this Post.

Tuesday, 26 March 2013

How to redirect from one Activity to another in Android

This is my first post on Android Platform. I like to share my Android knowledge to all through this blog. Happy Learning

You need to use Intent Class in order to redirect from one activity class to another activity class.

Let's demonstrate this by providing an example. In this example, We will be displaying a 'show setting' menu in the action bar, by clicking on that, you will be redirect to another Activity

import android.app.Activity;

import android.os.Bundle;

import android.content.Intent;

import android.view.Menu;

import android.view.MenuItem;

public class MyActivity extends Activity {

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

       menu.add(Menu.NONE, 0, 0, "show setting");

       return super.onCreateOptionsMenu(menu);

  }

  @Override

  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

     case 0:

      Intent show = new Intent(this, MenuActivity.class);

      startActivity(show);

      return true;

    }

    return false;

  }

}

onOptionsItemSelected() Method will be trigged when you click the 'show setting' menu in the action bar. 'show setting' menu item index is set as '0', this will match the switch case statement present inside onOptionsItemSelected method.

We need to pass 2 parameters to the Intent Class
  •  Current/Source Activity Class (you can use 'this' to refer current activity class)
  •  Destination Activity Class Name
 startActivity() is used to launch a new activity  or get an existing activity to do something new.

 Hope, you enjoyed this Post.

Sunday, 24 March 2013

Using Data Provider Annotations in PHPUnit - Part2


Today, Let's see how we can create Test case Class that will return Iterator Object using Data Providers Annotation.Before that, if you haven't read part1 of this Post, Please read it first and Proceed below.

Using Data Provider as Iterator object

Let’s create a data provider method which will return object that implements the Iterator interface and yields an array for each iteration - ArrayIterator

Class ContentTest  extends PHPUnit_Framework_TestCase{

 public function contentProvider()
 {
    $content = array(
       array(9,'phpmaster'),
       array(9,'sitepoint'),
       array(3,'php')
    );
    return new ArrayIterator($content);
 }

 /**
  * @dataProvider contentProvider
  */

 public function testContentLength($length,$string)
 {
   $this->assertEquals($length, strlen($string));

 }
}
Only one change when compared to “Using Data Provider as Array of Array” section here is, Instead of returning array of array, we are returning Iterator Object. Please refer Part1 of this Post for detailed explanation regarding test case behavior. You can also write test cases using other iterator objects that PHP Supports like RecursiveArrayIterator, DirectoryIterator and so on.

When I run the above test case in Zend Studio (By Right-Click File name, then select Run as => PHPUnit Test). Following is the test case result.











Hope, you enjoyed this Post.

Using Data Provider Annotations in PHPUnit - Part1

Today, we are going to see “How to use Data Provider Annotations in PHPUnit”. Before entering into that topic, if you are new to PHPUnit, Please take a look my Previous Post, and then proceed reading this article. You can also find lot of PHPUnit Getting started guides available online by Googling.

Annotations:

As per PHPUnitManual, Definition for Annotations is:

An annotation is a special form of syntactic metadata that can be added to the source code of some programming languages“.

PHPUnit borrowed a handy featured from JUnit  Unit Testing Framework, called Annotations.
Annotations are meta information describing classes and its properties, methods or functions. They are always put in comments block above the code structure that they write.

The most common annotations that every PHP developer should know are the ones that used to document classes and their member properties. Annotation identifiers always start with a @ sign, there’s no other special rules associated on it.

While using annotations, you are making sure your code looks much more expressive and focusing on primary problem instead of writing lot of code.

Using Data Providers Annotations in PHPUnit

PHP usually lacks a way to parse the comments directly, so PHPUnit has its own tool that looks for certain phrases and characters to match in the comments. PHPUnit comes with list of annotations. Please refer to PHPUnitManual that contains the list of available annotations. Today, we will look how data provider annotations are being used in PHPUnit and what benefits it will provide for your application.

A Test Method in Test Case can accept arbitrary arguments, these arguments will be provided using dataprovider method.
These data provider method returns either array of array or an object that implements the Iterator interface and yields an array for each iteration. We will look each of one in details

Using Data Provider as Array of Array

Data provider method must be declared as public and method name doesn’t start with the word ‘test’. Let’s create a data provider method which will return array of array. This will become handy when you need to provide a series of different data sets to the test method.

PHPUnit will treat each array arguments as a different test and run the test method using the values of array returned from data provider method. This lets you check multiple sets of data against one test quite easily.

Class ContentTest  extends PHPUnit_Framework_TestCase{

    public function contentProvider()
    {
          return array(

              array(9,'phpmaster'),

              array(9,'sitepoint'),

              array(3,'php')

         );

    }
    /**
    * @dataProvider contentProvider
    */
    public function testContentLength($length, $string)

    {
      $this->assertEquals($length, strlen($string));

    }
}
From above code, the data provider method ‘contentProvider’ will be coupled with the test method ‘testContentLength’ using @dataProvider annotation. This data provider annotations will be added with the format ‘@dataProvider  <data provider name>’ under comments sections above the test method.

When I run the above test case in Zend Studio (By Right-Click File name, then select Run as => PHPUnit Test). Following is the test case result.

You will find the three passed test results that match with the three arrays values in data provider method. This Test method will check the length of the string using array values received as an arguments from data provider method, so  while running the first test, $length value will be ‘9’ and $string value will be 'phpmaster'. Using assertEquals, I am checking both $length value and the length of $string are Equals which is true so first test passes, similarly second and third test will also be passed.









In Next Post, Let's see how to use data provider Annotations as Iterator Object. Hope, you enjoyed this Post.

Why you need PHPUnit for your Project


Today, let me explain the importance of PHPUnit and why you need PHPUnit for your project.
Before that one, if you don’t have PHPUnit Installed in your system, Following URL explains “How to install PHPUnit using PEAR”. http://www.phpunit.de/manual/3.0/en/installation.html

Why you need PHPUnit Testing?

As Developers like me, tends to think why you need Unit Testing. If you came across the following issues while you are developing your applications, then its right time for you to use PHPUnit in your project.

1)      How many times have you seen a blank screen in your browser.
2)      How many times did you debug your PHP Script using var_dump() and other debug statements.
3)      How many times did you run your application in your browsers for checking various workflows of your application?

Your PHP Script can be easily broken, if you forgot to put semicolon or braces, and also by changing a single line of code that may broke the other part of applications without proper testing. Then you will get a Call from the client at the middle of the night and telling website is broken. In order to avoid these unexpected one, it’s right idea for PHP developers to use PHPUnit in your applications.

Get Start with PHPUnit Today

I first became aware of TestDriven Development and unit testing about a year ago, when I first read PracticalPHP Testing E-Books written by Giorgio Sironi. You can download this book free by clicking that above links. I suggest this book to those PHP Developers who want to learn PHPUnit. I am very glad that I did!.

Once you start using PHPUnit in your application, you will realize that importance of PHPUnit and how PHPUnit is making your development life easier and it will catch and eliminate bugs much more easily and sooner in the development process. If you are new to PHPUnit, there are lots of Getting started guides available online. Following are some for your reference.


If you haven’t used PHPUnit for your current project, please don’t postpone it for your next project, do it right now by creating a simple test case and checking the various possibilities of your classes using various assert methods. Following URL explains the various asserts present in the PHPUnit. http://www.phpunit.de/manual/3.4/en/api.html#api.assert

Hope, you enjoyed this Post.

Saturday, 23 March 2013

Capture Orientation Change on Sencha Touch 2

Sencha Touch comes with lot of useful Features like containers, panels, layouts, grid, list and so on. In addition to that, Sencha Touch  also provides an ability to adjust your UI according to the size and orientation of user device.

Today, Let's see how we can add orientation change listener to Panel when user physically rotate his/her device.

Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.Panel',
    alias: 'widget.MyPanel',
    config: {
    height: '80%',
        html: 'Orientation Change Event',
        styleHtmlContent: true,
        width: '80%',
    },

    // Fires when the Panel is initialized
    initialize: function () {
        console.log('Panel initialize');
        // Add a Listener. Listen for [Viewport ~ Orientation] Change.
        Ext.Viewport.on('orientationchange', 'handleOrientationChange', this);
        this.callParent(arguments);

    },

    handleOrientationChange: function(viewport,orientation,width,height){
        // Execute the code that needs to fire on Orientation Change.
        Ext.Msg.alert("Orientation",orientation);

    }
});

Output:

When you run the above code in the Mobile Device and rotate it horizontal, alert Message with 'Landscape' will get displayed. By rotating it vertical, alert Message with 'Portrait' will get displayed

Event Listener can be added to any sencha touch component using on(). If you don't know, how to add event Listerner, Please click here. Orientation Change Event can be handled only through viewport using the below code

// Add a Listener. Listen for [Viewport ~ Orientation] Change.
Ext.Viewport.on('orientationchange', 'handleOrientationChange', this);

handleOrientationChange() method will be trigged, when viewport orientation changes. This method accept four parameters
  • viewport - Ext.Viewport
  • orientation - The new orientation
  • width - The width of the Viewport
  • height - The height of the Viewport
This feature is really useful, if you need to adjust the UI of any component based on the viewport orientation changes.

Hope, you enjoyed this Post.

Tuesday, 19 March 2013

Add Event Listener to component in sencha touch 2

Adding Event Listener (swipe,tab etc) to component in sencha touch 2 can be done using  'on' Event (Alias  for addListener Event).

In order to demonstrate this, let's create a Panel and attach the 'swipe' Event at the time of panel is displayed on the screen i.e 'show' event.

Ext.define('CRN.view.TestPanel', {
    extend: 'Ext.Panel',     alias: 'widget.TestPanel',     config: {         height: '80%',         html: 'Swipe Here',         styleHtmlContent: true,         width: '80%',         listeners: [             {                 fn: 'onPanelShow',                 event: 'show'             }         ]},         onPanelShow: function(component, options) {           component.element.on('swipe',           function(){Ext.Msg.alert('swipe called');},component);     } });
Output: Alert Message "swipe called" will be displayed when you swipe on the screen

Attach Multiple Event to the component

You can also attach multiple events to the component using on(). Let's modify the above onPanelShow function to attach 'tap' Event in addition to 'swipe' Event.

onPanelShow: function(component, options) {
    component.element.on({
      swipe:function(){Ext.Msg.alert('swipe called');},
      tap: function(){Ext.Msg.alert('tap called');},
      scope:component});
}
Output: Alert Message "swipe called" will be displayed when you swipe on the screen and Alert Message "tap called" will be displayed when you tap on the screen.

Hope, you enjoyed this Post.

Friday, 15 March 2013

Sencha app build compass error in sencha touch 2 windows

Today, i tried to build package using sencha cmd  "sencha app build package" in windows

I got an error -"compass is not recognized as internal command". But i have rubyGem and compass installed in my machine. when i ran "compass -v" in command prompt, i able to get compass package details and version.

I spend around 4 to 5 hours trying to fix this issue by googling, atlast i found the solution.

Below are the two approach (Either one) you need to follow, inorder to fix this issue

Approach 1:

add "skip.sass=1" to local.properties file in your app or workspace folder present inside .sencha folder. By default this local.properties file won't exist in either of these 2 location.

If you need to apply this build changes only to this specific app - you need to place local.properties file inside app folder or else if you need this changes to apply for all apps in this workspace, you can place this local.properties file inside workspace folder. Choice is yours

Approach 2:

Go to this file - sencha/app/build-impl.xml and move to Build sass section, there either enter the full compass installation path  or something more general (like a new property) depending on if you are trying to share the project with others.

<x-shell>
${compass.dir}/compass compile --boring @{sass} --css-dir ${app-css-dir}/${sass.name} --force
</x-shell>

And define "compass.dir=<install-compass-path>" in your local.properties

Thats it.

Now, if you run again "sencha app build package" command in your command prompt, your build will get completed successfully without any Errors. You can see the build folder will be generated under your app base directory.

Hope, you enjoyed this Post.

Thursday, 14 March 2013

Design for Multiple devices in sencha touch 2

Situation will occur, where you need to use the same code base for both tablet as well as mobile devices and also different types of mobile devices (android, iphone, blackberry etc).

Sencha touch 2 allows you to get the currrent device information using Ext.os. Using this feature, you can implement device specific functionality using sencha touch 2.

In sencha touch 2, if you need to check the generic type of current device.

Here is the sample code

if(Ext.os.deviceType == 'Tablet' || Ext.os.deviceType == 'Desktop'){
  //tablet specific code
}else{
  //mobile specific code
}

Possible Values are :-
  • Tablet
  • Desktop
  • Mobile
Sencha Touch 2 also provides a provision to check the current device OS Name using Ext.os.is.

Here is the sample code

if(Ext.os.is.Android){
  //android specific code
}else if(Ext.os.is.iPhone){
  //iphone specific code
}else if(Ext.os.is.BlackBerry){
  //Blackberry specific code
}else if(Ext.os.is.Windows){
  //windows specific code
}

Possible Values are :-
  • iOS
  • iPad
  • iPhone
  • iPhone5 (also true for 4in iPods).
  • iPod
  • Android
  • WebOS
  • BlackBerry
  • Bada
  • MacOS
  • Windows
  • Linux
  • Other
Hope you enjoyed this post

Tuesday, 12 March 2013

How to Use Model Validation in Sencha Touch 2

In Sencha Touch 2, Models have strong support for validating its data. In Modal, Validation Configuration follows the same format as the Field Configuration. It expects the field name and type of validation. Following are the validation types available (as per Sencha documentation)

1) presence -  Ensures that the field has a value. Zero counts as a valid value but empty strings do not.

2) length  - Ensures that a string is between a minimum and maximum length. Both constraints are optional.

3) format - Ensures that a string matches a regular expression format. In the example above we ensure that the age field is four numbers followed by at least one letter.

4) inclusion - Ensures that a value is within a specific set of values (for example, ensuring gender is either male or female).

5) exclusion - Ensures that a value is not one of the specific set of values (for example, blacklisting usernames like 'admin').

6) email - Ensures that the filed value matches with the format of an email address.

To demonstrate this, we're going to build up a User Model with some Validations

Ext.define('App.model.User', {

    extend: 'Ext.data.Model',

    alias: 'model.User',

    config: {

        fields: [

            {
                name: 'Name'
           },
           {
                name: 'Age'
            }

        ],
        validations: [
            {
                type: 'presence',
                field: 'Name'
            },
            {
                type: 'presence',
                field: 'Age'
            },
            {
                type: 'length',
               field: 'Name',
                min: 6
            }
       ]
    }
});

Both Name and Age Fields are required and can't be empty. Name Field must have Min 6 characters. Lets create a User and validate it using validate().

Example 1:

var usr = Ext.create('App.model.User',{
     Name: 'Ravi'
});

var errs = usr.validate();
var msg = '';

if (!errs.isValid()) {
   errs.each(function (err) {
   msg += err.getField() + ' : ' + err.getMessage() + '<br/>';
   });
   Ext.Msg.alert('ERROR', msg);

} else {
    Ext.Msg.alert('SUCCESS', 'Looks like the model is valid');
}

Output: ERROR Alert Message - "Age : must be present && Name : is the wrong length".

Example 2:

var usr = Ext.create('App.model.User',{
     Name: 'A Suresh',
     Age: 26
});

var errs = usr.validate();
var msg = '';

if (!errs.isValid()) {
    errs.each(function (err) {
    msg += err.getField() + ' : ' + err.getMessage() + '<br/>';
    });
    Ext.Msg.alert('ERROR', msg);
} else {
   Ext.Msg.alert('SUCCESS', 'Looks like the model is valid');
}
Output: SUCCESS Alert Message - "Looks like the model is valid".

Hope, you enjoyed this Post.

Ext.isEmpty() in Sencha Touch 2 Explained

I am from PHP Background, Checking for variable empty in PHP is straight forward using empty() function. I am searching for similar function in Sencha Touch 2, finally i got it.

 Ext.isEmpty() returns true if the variable is empty, otherwise returns false. The variable is deemed to be empty if it is either:

 * null
 * undefined
 * zero-length array
 * zero-length string (Unless the allowEmptyString parameter is set to true)

 This method accept 2 parameters

 1) value : the value/variable to test
 2) allowEmptyString  : true to allow empty strings (defaults to false)

 Example 1: (Using null check)

 var data = null;
 if(Ext.isEmpty(data)){
    console.log('variable is empty');
 }else{
    console.log('variable is not empty');
 }

 Output: variable is empty

 Example 2: (Using zero-length array check)

var data = [];
 if(Ext.isEmpty(data)){
    console.log('variable is empty');
 }else{
    console.log('variable is not empty');
 }

 Output: variable is empty

Example 3: (Using zero-length string check)

var data = '';
 if(Ext.isEmpty(data)){
    console.log('variable is empty');
 }else{
    console.log('variable is not empty');
 }

 Output: variable is empty

 Hope, you enjoyed this Post.

Sunday, 10 March 2013

Understanding Local Storage Proxy in Sencha Touch 2


LocalStorageProxy is available from Sencha Touch 1. LocalStorageProxy uses the new HTML5 localStorage API to save Model data locally on the client browser. HTML5 localStorage API saves data in key and value pairs and doesn't support complex JSON objects.

LocalStorageProxy automatically serializes and deserializes data when saving and retrieving it.

Now, we are going to see how we can store User information in client Browser using HTML5 LocalStorageProxy.

First, lets create a model for User with fields Name, DateOfBirth and Age.

Ext.define('App.model.User', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            {
                name: 'Name'
            },
            {
                name: 'DateOfBirth'
            },
            {
                name: 'Age'
            }

        ]

    }

});


Then, we are going to create a store with Local Storage Proxy configuration and associate 'User' model to the Store.

Ext.define('App.store.User', {
    extend: 'Ext.data.Store',
    requires: [
        'App.model.User'
    ],
    config: {
        model: 'ListApp.model.User',
        storeId: 'UserStore',
        proxy: {
            type: 'localstorage',
            id: 'UserInfo'
       }
    }
});



Now, lets get the registered store by StoreId (defined above) using Ext.getStore().

var UserStore = Ext.getStore('UserStore');

Then, Load the existing data if available from the store using load().

UserStore.load();

Now we are going to add user records to the store Using add().This method will accept model instance as the parameter

UserStore.add({Name:'A Suresh',DateOfBirth:'21-07-1981',Age:'31'});

UserStore.add({Name:'A Suresh123',DateOfBirth:'21-04-1981',Age:'25'});

UserStore.add({Name:'A Suresh456',DateOfBirth:'01-04-1981',Age:'29'});

Finally, sync() method is used to save the records into local storage
UserStore.sync();

Below is the output, When i run the above code in Google Chrome.

You can view this output using Firebug, Click Resources Tab then select "Local Storage" in Left Column


Hope you enjoyed this Post.

Saturday, 9 March 2013

Dynamically add images to carousel in sencha touch 2

A Carousel is used for displaying multiple pages, but it will show only one of its pages at a time and allows you to swipe through with your finger.

Now lets see, how to add dynamic images to carousel component.

Before that, lets first create a carousel component using Ext.create() with configuration.

var carousel = Ext.create('Ext.Carousel',{
  fullscreen: true,
  itemId: 'carousel',
  id: 'carousel'
  });
Now 'carousel' variable will contains the reference of carousel component. image component can be added using Ext.Img. Now we will be adding 3 images to the carousel component using add() (3 times).

carousel.add({xtype:'image',src:'image URL'});
carousel.add({xtype:'image',src:'image URL'});
carousel.add({xtype:'image',src:'image URL'});

Carousel will display only one image at a time you can view furthur images by swipe with your fingers .
In order to display carousel on screen, we need to add it on Viewport.

Ext.Viewport.add(carousel);

Hope you enjoyed this Post.

Thursday, 7 March 2013

Recognize Vertical Swipe in Sencha Touch 2

 In Sencha Touch 2 , A event recogniser is used to recognise vertical swipe movements. This has been disabled by default in Sencha Touch and it has a performance impact when your application has vertical swipe.

If you wish to recognise vertical swipe movements in your application, below is the code you need to add inside Ext.Application();

Ext.application({

    eventPublishers: {
        touchGesture: {
            recognizers: {
                swipe: {
                    //this will include both vertical and horizontal swipe recognisers
                    xclass: 'Ext.event.recognizer.Swipe'
                }
            }
        }
    },
    name: 'AppName',
    launch: function() {
         Ext.create('AppName.view.Container', {fullscreen: true});

    }

});



 Hope you enjoyed this Post

call controller method from another controller in sencha touch 2


In Sencha Touch 2, if you need to call a controller method from another controller below is the code

this.getApplication().getController('controller name').functionname();

This way, you can avoid the code duplication across controllers. Hope you enjoy this Post.
Related Posts Plugin for WordPress, Blogger...