Shortlink

Classes in JavaScript

JavaScript is a functional Object-Oriented language. The language’s first class citizens are functions. Functions can be assigned as literals to variables as shown below.

var workOut = function(calories){
    document.write("Burning " + calories + " calories);
}
workOut(100);

Functions can also be invoked with a new keyword. This feature in JavaScript paves way for writing some traditional Object-Oriented code.
Say you want to create a class with variables and methods in JavaScript, instantiate it just like you do in C#/Java. Let’s create a class Person with name and age attributes and eat method.

  function Person(theName,theAge){
     this.name = theName; //public variable
     this.age = theAge;
     this.eat = function(){
        document.write(this.name + " is eating");
     }
  }

If you want to now create an object of Person and invoke it’s eat method you can use the new keyword similar to other OO languages.

   var p1 = new Person("Sam",23);
   p1.eat();

So what’s going on behind the screens?. We will discuss more about them later.

Shortlink

Dive into Android development – V

Let’s try to connect to a server resource from an Android application and display the data. I have created a very simple JSP page ‘server.jsp’ that returns the server date and time. This date and time will be displayed in our Android application in a simple TextView component.
The server.jsp has the following code
                <%@page import=“java.util.Date”%>
                <%= new Date()%>

In the onCreate method of the Activity, you will use the normal Java approach to connect to a server and fetch data, i.e, using the java.net and java.io package. The code for connecting to the server.jsp is given below.
        TextView dateText = (TextView)findViewById(R.id.dataText);
        String address = http://YourAddress/server.jsp;
        try {
                     URL url = new URL(address);
                     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                     if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                         InputStream inputStream = urlConnection.getInputStream();
                         BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                         String line = null;
                         while ((line = br.readLine()) != null) {
                               dateText.setText(line);
                         }
                        br.close();
                       }
           } catch (Exception e) {
                    Log.e(“Error fetching data “, e.getMessage());
            }

When you run this code, you will get an error logged into to your LogCat as shown below.
You have to add a permission attribute in the Android Manifest file for your application to be able to connect to the internet. Add the following line in AndroidManifest.xml file. 
               <uses-permission android:name=“android.permission.INTERNET”/>

You can play with the manifest file using the design wizard instead of manually editing it.
So all set and done, your app connects to the server resource, loads the data from the server and displays it in the TextView component.

Shortlink

arguments in JavaScript

Ext JS 4 involves calling this.callParent(arguments) from the initComponent method of a view component. For quite some time I was thinking that arguments is a pre-defined variable in Ext JS 4 before I started reading  the book  JavaScript: The Good Parts”.   Very interesting book for those who want to start taking JavaScript as a serious programming language. 
arguments is  a built-in parameter available in a function in JavaScript. It’s an array that is used to access the parameter list of the function, which basically says you don’t really have to formally declare arguments for a function, but still access the values passed, using the ‘arguments’.
Say you have a method to concatenate all the values passed to a method in JavaScript. You can write it like below: 

function concat(){
   var result = “”; 
   for(var i=0;i<arguments.length;i++){
        result += arguments[i] + ” “;
   }
   return result;
}
document.write(concat(“This”,”is”,”cool”)); //Output is This is cool

You can see that arguments is a built-in array parameter that can be used to access the parameters passed when the function is invoked. In case you want to avoid concatenating anything other than a string, reflection can be tossed in.

  if(typeof arguments[i] == ‘string’)
       result += arguments[i] + ” “;
But what is strange is that the ‘arguments’ is really not an Array instance in the true sense. It doesn’t have methods like slice, push, pop associated with the Array class. So need to be a bit careful while using ‘arguments’.

Shortlink

extraParams in Ext JS 4

A Store instance in Ext JS4 uses a Proxy object to connect to the server. If you want to pass parameters to the proxy dynamically you can make use of the extraParams property. Let’s discuss a simple example to see the use of extraParams property.
Let’s say you have two list boxes ‘country’ and ‘city’. Based on the value selected from the country list box, the city list box has to be populated. The city list will be loaded from the server, through a cityStore that we have configured. When the country value changes you will pass the country as a parameter to the cityStore and load the cities in the listbox.
The code for the cityStore is given below.

var cityStore = Ext.create(“Ext.data.Store”,{
fields : [“name”],
autoLoad : false,
proxy : {
type : “ajax”,
url : “citiesServlet”,
reader : {  type : “json”}
}
}});
The cityStore is populated by sending a request to a ‘citiesServlet’. The city combo box can be mapped to the cityStore. The country and city combo boxes are declared as shown below.

                                           {
           xtype : “combo”,
        displayField : “name”,
        fieldLabel : “Country”,
        store : {
        fields : [“name”],
        data : [
                {name:”India”},{name:”UK”},{name:”USA”}
              ]
        },
          listeners : {
        change : function(source,newValue,oldValue){
        cityStore.proxy.extraParams = {“country” : newValue};
        cityStore.load();
        },
        }
        },
        {
        xtype : “combo”,
        store : cityStore,
        displayField : “name”,
        fieldLabel : “City”
        }

 You can notice that in the change event listener of the country combo box , the selected value  is passed as a parameter to the cityStore’s proxy object using the extraParams property and load method is invoked. Since the cityStore is mapped to the city combo box, the combo box gets automatically populated with the data fetched from the server.
Shortlink

Dive into Android Development – IV

Like many other native applications, Android applications are also single threaded.  There is only one thread ie., the UI thread in the application. So for performing a continuous activity, you need to create a separate worker thread and run it. But you cannot update the UI components from that worker thread you have created. UI components have to be played upon only from the UI thread, failing to do so will lead to unpleasant user experience.
Android provides a number of ways to update UI components from a different worker thread. One of them is using the runOnUiThread method on Activity class, which accepts the Runnable object.
Say you want to display the current date and time in a TextView object from a separate thread. This is how you can do it.
   
    final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
    this.runOnUiThread(new Runnable(){
        public void run(){
                      dateTxt.setText(new Date().toString());
        }
    });
dateTxtView is a TextView component. This code starts a separate thread but accesses the dateTxt component from the UI thread only.
What if you want to update the time every one second, let’s use a java.util.Timer class for this purpose. The Timer will run for 1000 milliseconds. The code is shown below.
   
    final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
             public void run() {
                 runOnUiThread(new Runnable(){
                    public void run() {
                       dateTxt.setText(new Date().toString());
                    }
                 });
            }
    }, 0, 1000);

The Timer class’ schedule method accepts a TimerTask instance that starts a thread, after a delay of 0 seconds, and runs every 1000 milliseconds . This thread encapsulates another worker thread that updates the dateTxt with the latest time.