Posts on this Category



How to use ES6 (Very Simple Example)

Compiling Javascript ES6 Code with Babel
Compiling Javascript ES6 Code with Babel

This will be a very simple tutorial on how to use, the new and far more sophisticated version of Javascript, the ES6 (or ES2015 if you prefer). Much people say ES6 is the future of Javascript, but as everybody knows, our browsers cannot run code in this format yet. Web developers are already writing Javascript in ES6 format and using transpilers to transform it into ES5 code so the browsers can read it. For those who doesn’t know, a transpiler is kind of a compiler that converts a code written in one programming language to another similar programming language, in our case from ES6 to ES5.

The reason why I decided to make it simple is because I’ve already seen lots of authors writing more complex and long tutorials involving Grunt, Browserify, JSX, and so on. You would probably spend a reasonable amount of time going through these tutorials. As opposed to them, my goal here is to get you writing ES6 code as quickly as possible, without consuming much of your time.

So let’s get started, the first thing we need is a transpiler, for this tutorial I’m going to be using Babel, to install it just run the following command:

1
npm install babel-cli -g

Now, since Babel doesn’t come with any transformations enabled, we need to explicitly tell what kind of transformation to perform, to do that we also have to install ES2015 preset:

1
npm install babel-preset-es2015 -g

Perfect! Now we’re going to need to write some ES6 code to test if Babel is working, copy the following code into a js file:

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyFirstES6Class {
  constructor(message) {
    this._message = message;
  }
 
  get message() {
    return this.message;
  }
 
}
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Ok, now via terminal just navigate to your folder and run the following command to generate the compiled js:

1
babel --presets es2015 test.js --out-file compiled.js

That’s it!! If you did it right you should now have the compiled.js file containing the transformed code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { 
throw new TypeError("Cannot call a class as a function"); } }
 
var MyFirstES6Class = (function () {
  function MyFirstES6Class(message) {
    _classCallCheck(this, MyFirstES6Class);
 
    this._message = message;
  }
 
  _createClass(MyFirstES6Class, [{
    key: 'message',
    get: function get() {
      return this.message;
    }
  }]);
 
  return MyFirstES6Class;
})();
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Compiling JSX ReactJS code with Browserify and Reactify

This will be a very basic tutorial for those who are just getting to know React, by now you should have noticed that React uses JSX code, which is basically Javascript with some HTML elements. The problem here is that the browser cannot understand JSX, if you have already tried it you probably saw something like this on your firebug:

SyntaxError: expected expression, got ‘<'

In order to make it possible for the browser to interpret it we have convert the JSX into regular Javascript code, to achieve that we need to use tools like Browserify and Reactify.

Browserify, is a tool that let’s you use the function require(‘module’) in the front-end exactly like you do in the back-end with Node.js, then it compiles everything and generates a single JS file which will be referenced on your page. Reactify is pretty much the same thing, but it supports JSX code, Browserify alone wouldn’t be able to compile it.

Let’s take a look at an example, the first thing you need to do is to install both browserify and reactify:

1
2
3
4
5
//INSTALLS BROWSERIFY
npm install browserify
 
//INSTALLS REACTIFY
npm install reactify

Now, you probably have in you project a JSX file like this one (in my case it’s on the ‘src’ folder):

app.jsx

1
2
3
4
5
6
7
8
9
var ReactDOM = require('react-dom');
var React = require('react');
 
var HelloWorld = React.createClass({
 render: function() {
   return <div>Hello World!!</div>;
 }
});
ReactDOM.render(<HelloWorld />, document.getElementById('component'));

What you need to do now is to transform this into a JS file so the browser can read it, already with browserify and reactify installed just navigate to your project folder and type the following command:

1
browserify -t reactify src/app.jsx -o build/app.js

Perfect!! Now you have the app.js file in your ‘build’ folder, you can now use it in your HTML page like this:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
   <head>
	   <title>React DataTable</title>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
	   <script src="build/app.js"></script>
   </body>
</html>

That’s it!! Hope I helped you with this tutorial, till the next one!!

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

This is a very common error for people who are just getting started with Web Services, it’s really simple to solve but sometimes developers spend hours struggling to find a solution. It happens when you create a web service and tries to access it from a different application, it won’t work because you don’t have Cross-origin resource sharing (CORS) enabled, which means an application loaded in one domain cannot interact with resources from a different domain. All you have to do is to enable CORS.

How you can active it will depending on your scenario, in this tutorial I’m going to show how to enable CORS for a Java EE application running on Glassfish, I’m assuming you have an EJB RESTful web service similar to this one, and when other applications tries to consume it you see the Cross-Origin Request Blocked error on your firebug console, in this case all you have to do is to create a filter in your application, just create a class exactly like this one on your project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

Now you have to register the filter in your web.xml, copy the following code and replace “yourPackage” with your actual package name:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

That’s it! Now your application will allow its resources to be shared with other domains.

React.js Tutorial: Consuming JavaEE RESTful Web Services

In this post I’m going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I’ve already written a post showing how to create these web services with EJB 3, if you haven’t seen it yet just click on this link for more details, but if you’re already familiar with Java EE feel free to skip it and create your owm web service.

For this tutorial I’m going to use the following service (Which is almost the same as I created on the other post):

1
2
3
4
5
6
7
8
9
10
11
@Stateless
@Path("/test")
public class WebServiceTest {
 
    @GET
    @Produces("text/plain")
    public String test() {
        return "Web Service Test";
    }
 
}

This is as simple as it gets, just a method returning a string, simple as that! If you deploy the project you’ll be able to see the text “Web Service Test” on your browser by adding /test to the end of your URL:

Java EE REST Web Service Example
Java EE REST Web Service Example

Now let’s create the React.js project to consume this web service. Again, I already have a post about how to get started with React.js, click on the link to see it, though it doesn’t say anything about how to consume web services it can still be useful for those who are not familiar with react.

Since my goal here is to just show how to consume a web service, I’ll keep the react code very simple as well, just copy the following code into your index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>
 
        <script type="text/jsx">
            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/WebServiceEJB-war/test"
                    }).then(function(data) {
                        this.setState({text: data});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });
 
            React.render(<JavaEEWSTest />, document.getElementById('component'));
 
        </script>
    </body>
</html>

As you can see I have 3 functions here: getInitialState, componentDidMount and render. They do exactly what their names sugest, the first one sets all the initial values, the second executes when the component is mounted, and the last one is responsible for rendering the component. The most important for us is the componentDidMount, that’s where the web service is called, and after it receives the response it will be assigned to the variable ‘text’.

We’re almost done, now if you execute it you will probably see the following error (you need firebug installed):

Cross-Origin Request Blocke
Cross-Origin Request Blocke

To see more details about this error click here, to solve it just add the following filter to your Java EE project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

And in the web.xml:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Perfect!! Now if you refresh the page this will be the result:

Simple React.js application getting data from Java EE REST Web Service
Simple React.js application getting data from Java EE REST Web Service

It’s really simple, but the string ‘Web Service Test’ is coming from our web service.

Hope this tutorial was helpful for you, till next time!

Tutorial: ng-table with infinite scroll

I’ve already showed in this blog how to create a basic datatable with ng-table, for those who didn’t see it yet, just click on the link. This tutorial will just be a complement to the previous one, the difference is that instead of using pagination I’m going to use infinite scroll, and don’t worry, I’ll also keep the sorting and filtering features.

So before we start let’s just put the links to every script we need, your index.html should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html ng-app="ngTableTutorial">
    <head>
        <title>ng-table with infinite scroll</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
        <script src="https://raw.githubusercontent.com/BinaryMuse/ngInfiniteScroll/1.0.0/build/ng-infinite-scroll.min.js"></script>
        <link rel="stylesheet" href="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.css">
        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" media="screen">
 
        <script src="app/resources/js/app.js" type="text/javascript"></script>
        <link href="app/resources/css/style.css" rel="stylesheet" type="text/css"/>
    </head>
    <body style="padding: 50px">
        <div ng-controller="tableController">
        </div>
    </body>
</html>

As you can see I just put the links to: JQuery, Angular, bootstrap, ng-table and ngInfiniteScroll. There’s also the app.js and style.css, which I created to put my code on them.

Note that the body is still empty for now, let’s leave it like this and open our app.js, the first thing we need to do is to create our angular module and controller, just copy the following code to your app.js:

1
2
3
4
angular.module('ngTableTutorial', ['ngTable','infinite-scroll'])
        .controller('tableController', function ($scope, $filter, ngTableParams) {
        }
);

Don’t forget to declare the ngTable and infinite-scroll as dependencies, we’re going to use them later. This code is still very simple, I just created a module called ngTableTutorial, if you go back to the index.html code you’ll see that the ng-app=”ngTableTutorial” is already there in the html tag, and I also created a controller called tableController, again if go to the index.html there will be a div inside our body with the attribute ng-controller=”tableController”.

Now we need some data to be displayed to the table, I personally like mockaroo to generate random data, but feel free to generate it as you like, you’ll need about 1000 rows for this tutorial, after you generate it, just put it in a variable inside you controller, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$scope.users =
        [{
                "id": 1,
                "first_name": "Theresa",
                "last_name": "Morris",
                "email": "tmorris0@myspace.com",
                "country": "Indonesia",
                "ip_address": "143.220.154.199"
            }, {
                "id": 2,
                "first_name": "Steve",
                "last_name": "Gray",
                "email": "sgray1@nytimes.com",
                "country": "Norway",
                "ip_address": "163.199.165.94"
            }
           .
           .
           .
            {
                "id": 1000,
                "first_name": "Gloria",
                "last_name": "West",
                "email": "gwest2@go.com",
                "country": "China",
                "ip_address": "16.171.225.220"
            }
];

Now that we have the data we’re ready to create our table, copy the table bellow inside your div with the ng-controller attribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table infinite-scroll="getMoreData()" ng-table="tableParams" show-filter="true" class="table table-striped">
    <tr ng-repeat="user in data">
        <td data-title="'Id'" sortable="'id'">
            {{user.id}}
        </td>
        <td data-title="'First Name'" sortable="'first_name'" filter="{ 'first_name': 'text' }">
            {{user.first_name}}
        </td>
        <td data-title="'Last Name'" sortable="'last_name'" filter="{ 'last_name': 'text' }">
            {{user.last_name}}
        </td>    
        <td data-title="'e-mail'" sortable="'email'">
            {{user.email}}
        </td>    
        <td data-title="'Country'" sortable="'country'">
            {{user.country}}
        </td>    
        <td data-title="'IP'" sortable="'ip_address'">
            {{user.ip_address}}
        </td>    
    </tr>
</table>

Each column is displaying one attribute of our JSON, I put the attribute sortable and filter in some of them to add the sorting and filtering features to the datatable (to show the filter you also have to put show-filter=”true” in your table). But what is important here is the attributes ng-table=”tableParams” and infinite-scroll=”getMoreData()” from the table, the first is binding the table to the tableParams variable in our controller (I’m still going to create this variable), and the second attribute receives the method that will be called when the user reaches the bottom of the page, that’s the method that will make our infinite scroll work.

Now the only thing left for us to do is to create our tableParams and implement the getMoreData() method, copy the following code bellow our JSON in your controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$scope.tableParams = new ngTableParams({
    page: 1,
    count: $scope.users.length
}, {
    counts: [],
    total: 1,
    getData: function ($defer, params) {
        $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
        $scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
        $scope.data = $scope.data.slice(0, 20);
        $defer.resolve($scope.data);
    }
});
 
$scope.getMoreData = function () {
    $scope.data = $scope.users.slice(0, $scope.data.length + 20);
}

In this code we are instantiating the ngTableParams, the fist object it receives as a parameter is just defining that the current page is 1 and setting the row count, but what really matters here is the function getData, it will be called on the table initialization and also every time we sort or filter it, the lines 8 and 9 contains the logic to sort and filter the data, note that in line 10 I’m getting only the first 20 rows of our data, I’m doing this because every time this method is called, or the user will be filtering the data or he’ll be sorting it, both actions require him to be on the top of the page, thus I don’t need to show more than 20 rows.

Ok, now we just need to load more rows when he reaches the bottom of the pages, take a look at line 16, it’s just adding 20 more rows to our data, note that I’m using 2 variables here: $scope.data and $scope.users. The last one contains our original data, we cannot modify it, otherwise we’ll lose the data, that’s why we need an auxiliary variable, just to manipulate the data.

That’s it, now if you run your project you should see the following result:

ngTable with Infinite scroll
ng-Table with infinite scroll

As you scroll down you’ll see that the scroll bar will get smaller and smaller.

Tutorial: Custom ListView with ImageViews and TextViews

There is no doubt that the ListView is one of the most used Android UI components, in most cases developers find themselves in a situation where they need to customize this component, instead of just showing a list of Strings on the screen they also need to show more information, an ImageView, or even a Button.

In this tutorial I’m going to show how easy it is to customize a ListView, I’ll create a Contact List app with a customized ListView that will display the contacts, instead of just showing the name it’ll also show the phone number and the picture, the result will be like the customized ListView in the image bellow:

Customized ListView
Standard ListView x Customized ListView

As you can see in the image, we’re going to use 2 TextViews and 1 ImageView in this list, so let’s start by creating our ListView component, when we create the Android project it already comes with an activity_main.xml file, that’s where we’re going to add our ListView code.

1
2
3
4
5
6
7
8
9
10
11
12
13
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
 
    <ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
    </ListView>
</RelativeLayout>

There’s really nothing special here, we’ve just created the ListView and gave the id “list” to it, you could give any id you want, but you should remember it, we are going to use it later.

The next step is to create another xml file that will be our custom layout, let’s call it contactlist.xml, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <ImageView
        android:src="@drawable/person"
        android:layout_width="@dimen/picture_width"
        android:layout_height="@dimen/picture_height" />
 
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/contactName"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
 
        <TextView
            android:id="@+id/contactPhone"
            android:layout_marginLeft="@dimen/margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="5dp"/>
    </LinearLayout>
</LinearLayout>

It’s just like the first one, but with a few more things, this is the layout that is going to be used to display each of ListView items, you can add as many components as you want to this file, but in this example I’ll keep it simple and use just an ImageView and two TextViews like I said before. Don’t forget to give an id to each component. You’ll also need an image to be displayed on the ImageView, pick one of your preference and put it on the drawable folder, them you should be able reference it in the ImageView src attribute.

Now that our views are done, we can go on and start writing some Java code, the first class we need to create is the Contact.java, it’ll only contain the name and phone attributes.

1
2
3
4
5
6
7
8
9
10
11
12
public class Contact {
 
    private String name;
    private String phone;
 
    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
 
    //GETTERS AND SETTERS
}

Really simple, there’s not much to explain here, all of you should already be familiar with Java.

Now we’re going to create our Adapter, this will be the class responsible for getting the data from our List and putting it into our UI components, let’s call it “ContactsAdapter”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class ContactsAdapter extends ArrayAdapter<Contact>{
 
    int resource;
    String response;
    Context context;
 
    public ContactsAdapter(Context context, int resource, List<Contact> items) {
        super(context, resource, items);
        this.resource=resource;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LinearLayout contactsView;
        Contact contact = getItem(position);
        if(convertView==null) {
            contactsView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(resource, contactsView, true);
        } else {
            contactsView = (LinearLayout) convertView;
        }
        TextView contactName =(TextView)contactsView.findViewById(R.id.contactName);
        contactName.setTypeface(null, Typeface.BOLD);
        contactName.setTextSize(TypedValue.COMPLEX_UNIT_PX,18);
        TextView contactPhone = (TextView)contactsView.findViewById(R.id.contactPhone);
        contactPhone.setTextSize(TypedValue.COMPLEX_UNIT_PX,14);
        contactName.setText(contact.getName());
        contactPhone.setText(contact.getPhone());
        return contactsView;
    }
}

This is a little bit more complicated, there’s quite a lot of things happening here, first note that I’m extending the class ArrayAdapter, we must do this, otherwise our application won’t recognize it as an adapter. Now let’s take a look at the getView method, in the lines 26 and 29 we’re getting the two TextViews from the contactlist.xml by its ids, at this moment we can modify every attribute of these components, as an example I modified the textSize in the lines 28 and 30 and also the typeface in the line 27. But the most important thing in this method is happening on the lines 31 and 32, that’s where I got the values “name” and “phone” from my Contact and passed them to my TextView objects.

Ok, now that we have an Adapter we should be able to write the code that will tie everything together, let’s open our MainActivity.java, we’re only going to modify the onCreate method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    ListView listView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        List<Contact> contacts = new ArrayList<Contact>();
        contacts.add(new Contact("Gloria Miller","86-(216)605-9056"));
        contacts.add(new Contact("Teresa Garrett","86-(131)666-7051"));
        contacts.add(new Contact("Jeremy Diaz","370-(899)196-6943"));
        contacts.add(new Contact("Rose Henry","420-(240)605-2163"));
        contacts.add(new Contact("Maria Kelly","62-(488)190-3222"));
 
        listView = (ListView) findViewById(R.id.list);
        ContactsAdapter adapter = new ContactsAdapter(this,
                R.layout.contactlist, contacts);
        listView.setAdapter(adapter);
    }

In this method I’m creating the contact list and adding each item to it, in this case I’ve hard-coded the data in this class, but in a real scenario it would have come from a database or a web service. Next we need to get our ListView, we’re going to get it by its id, exactly like we did before with the TextViews, and the last step is to instantiate our Adater, its constructor will receive our contactlist.xml and the data as parameters.

That’s it! Now if you run your app the result should be exactly like the image in the beginning of the post.

How to Deal with Technology Shifts

It isn’t new that we live in a constantly changing world, especially when it comes to technology, every day new frameworks, applications and APIs comes up, making it really hard for developers to keep up with the market and all its emerging technologies, so what can we do to not be left behind in this ever-changing world?

Certainly, we cannot turn our back on new technology, one of the solutions adopted by many developers is to jump headfirst into every new framework that gets enough friction, that’s because they don’t want to be an outdated professional, they know their current job may not last forever, and also that there may be better ones out there, for this reasons they choose to be prepared for the market and every opportunity it holds, but the problem is that they put a lot of time and effort studying and learning new technology, when they finally get to an advanced level, something new emerges, and everything they just learned falls into disuse, consequently they have to learn everything again, and this cycle goes on forever.

People will argue that this is how it’s supposed to be, technology changes overtime and if you are a software developer you’ll have to find a way to change and evolve with it.

I totally agree, but the question is: How can developers deal better with change? How to smartly invest time and money learning something that will probably be out of the market in a few years?

Unfortunately there is no easy answer for that, undoubtedly you’ll go crazy if you try to be the guy who knows everything about every new framework, it’s simply too much to learn and the market won’t give you enough time. A better solution might be not to dive very deep into it, at least at first. Let’s say a new framework just came into the market, you shouldn’t get obsessed and spend all of your precious time learning it, at this moment you are not trying to be an expert yet. You can start by simply just being familiar with its main features, know how and when to use them, basically what you need is to have a good grasp of the main concepts and ideas, just enough for you to be able to show a great understanding about it, nothing too advanced for now.

After you reach that level you can stop spending time on it for the moment, keep this new framework on your pocket and go explore some others, when you come across an opportunity to use it (e.g., a new project or a new job offer) you will easily be able to do so, from that moment forward your hard work will start to pay off, then you can safely invest more time, go much deeper, get some experience and become an expert on that specific framework.

By doing that with every new framework that comes into view, or at least a great portion of them, you’ll not only be aware of everything that is happening but you’ll also have a great overview of what’s in the market. Each framework has its own advantages and disadvantages, and because you went over lots of them you’ll be capable of effectively picking the most convenient when starting a new project, of course there will be some that you’ll never going to use, probably because they didn’t fit on any of your projects, therefore you’ll never get to an advanced level at those, but that’s ok, you didn’t spend too much time on them anyway, the great thing is that most of your time was spent in those that were actually useful to you.

The truth is, one cannot be an expert in everything that comes up, more sophisticated frameworks are being created all the time, and newer ones will be even before you have a chance to learn the old ones. As we all know, technology moves fast, you must wisely choose what you’re going to learn, and once you do, if you effectively manage your time spending most of it on what really matter, I ensure you that you’ll be prepared for everything the market can throw at you.

https://plus.google.com/u/0/106915634326132202910

Managing Database Connections with Wildfly

Today’s tutorial will be about how to manage database connections on the application server, there are people who prefer to do it on the application, but I personally think it’s much better to delegate this task to the application server, that’s because you don’t need to modify and redeploy your applications every time you update your db connection info, since this information is on the server you can modify it as much as you want without touching and interrupting your applications.

The video bellow explains how to create connection pools in Wildfly, it’s from Claudio Barbosa’s Youtube channel, a new and very promising channel that’s still on it’s early days, its goal is to provide a great variety of video tutorials covering lots of well known web development tools, frameworks and APIs. You should check it out, there will be lots of videos coming up on the next days!

An Alternative to Amazon EC2

digital_ocean
DigitalOcean Homepage

Before I begin, I just want to make it clear that I’m not trying to say that DigitalOcean is better than AWS, I know that its API is nowhere near Amazon, but I realized that there is a lot of AWS users that don’t use most of its features, sometimes not even 10% of what they offer, for this reason I decided to write this post and present this alternative that may be a better option for a lot of people.

It has been a few months now since I started using DigitalOcean, at first when I was deciding which service to use my intention was to use AWS, since it is a major cloud computing services provider having a great variety of services I thought it would be the best option for me, but then I had some problems with it (with the technical support more specifically), for this reason I started looking for some alternatives, after searching a little bit I found several options, but one that caught my attention was DigitalOcean, firstly because of its simplicity, it’s really very easy and fast to set up a server(it takes less than a minute), and secondly because of the prices, they show the monthly price instead of hourly, and some of the plans are cheaper than its Amazon EC2 equivalents (Depending on the region), and you even get $10 free credit when you sign up. Of course it doesn’t offer as many features as AWS does, but since you’re not running extremely large and heavy applications you should probably be ok, you won’t need these advanced features.

DigitalOcean uses only SSD hard drives drastically increasing its performance, it also has data centers all over the world, and it offers you the possibility to choose the location that suits you the most, you can also transfer your droplet from one location to another if you like. One of the its best advantages is scalability, at first you can start with the most basic and cheap plan, then as your demand increases you can easily upgrade your plan to meet your new demands.

During these first few months I can say that my server was available more than 99% of the time, there were only two occasions when it was down for maintenance, but it was really quick, and they sent me an e-mail notifying me about it.

Overall DigitalOcean is an excellent server, I’ve seen a lot of people saying the same thing, if you read some reviews you see that the great majority of them are good, so if you are looking for a server to host your applications I thing DigitalOcean really deserves a shot.

For more information visit the DigitalOcean Official Site.

Getting Started with Facebook’s React and Flux

reactjs flux
ReactJS Homepage

React and Flux are two of the most promising technologies of the present days, both are constantly showing up on trending technologies lists, quickly gaining market and becoming popular among developers. The first one defines itself as an open source javascript library for building user interfaces, it is an excellent tool for developers to create highly dynamic UI components, as the second is a brand new application architecture for client-side web apps designed to work together with React by using unidirectional data flow.

Let’s start by talking a little bit more about React with an example, and later on I’ll give more details about Flux and apply it to the first example.

Creating our first Application with React

The example bellow is a classic Hello World example using react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
   <head>
	   <title>React Flux</title>
   	   <script src="https://fb.me/react-0.13.3.js"></script>
  	   <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
 
 	   <script type="text/jsx">
		   var HelloWorld = React.createClass({
		     render: function() {
		       return <div>Hello World!!</div>;
		     }
		   });
 
		   React.render(<HelloWorld />, document.getElementById('component'));
 
	   </script>
   </body>
</html>

If you carefully analyze the code, the first different thing you should notice is the new script type text/jsx, which is basically Javascript with some HTML elements.

You can also see that I had to add three scripts to my page, the first and the second are the React and JSX scripts respectively, and the third one is jQuery, I’ll explain in a moment why we need it.

Now let’s analyze the code and see how it works, take a look at the declaration of HelloWorld var, this is the variable that will actually hold our new component. In React we always have to create the specification of our components through the function React.createClass, it receives an object as a parameter containing a render function, this function will process and return the component’s HTML code the way it’ll be displayed on the browser, in this example I’m just returning a div with a text within it, nothing dynamic for now.

After implementing our component we need just one more line of code to make it appear on the page, to show it we have to call React.render (line 19 of the example), this function receives two parameters, the first one is the component that will be displayed and the second one is where we want to display it, this is where JQuery will come into action, note that right after the body declaration we have a div with the id=component, I’m using JQuery’s getElementById to get this div and render my HelloWorld component on its place. Now if you run this application you should see ‘Hello World!!’ on your page.

Using Flux Architecture

flux architecture
Flux Homepage

As I said before Flux is a new architecture used by Facebook that complements React components by using unidirectional data flow, it is divided in four parts: the dispatcher, stores, views and controller-views. Every action, no matter where it comes from, is received by the dispatcher which will be responsible for changing the state of the appropriate store, after the state is modified it will notify the controller-view that will retrieve the new data and update all its child views.

Here is as brief explanation for each one of the components:

Dispacher – Is the central component that manages the data flow within the application, it distribute the actions to the appropriate stores.
Store – Components that contains the logic and state of the application.
View – The components that represent the user interface.
Controller-view – The type o view the listens to events coming from the stores.

It may be hard to understand at first but once you see an example it will get easier. To illustrate how this architecture works I’m going to use the same preview example but slightly modified just enough to demonstrate how Flux works, so instead of just showing ‘Hello World!!’ on the page we’re going to render a button that will trigger an action and show the hello world message, the difference is that now we have an action involved.

First we’re going to move our react code to another file that, it’ll be called HelloWorld.jsx, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
var React = require('react');
var HelloWorldAction = require('../Actions/HelloWorldAction.js');
 
var HelloWorld = React.createClass({
	showMessage:function(){
		HelloWorldAction.showMessage('Hello World!!');
	},
	render: function() {
		return <a onClick={this.showMessage}>Click Here</a>;
	}
});
 
module.exports = HelloWorld;

I’ve already made the changes, now I’m rendering a link that when clicked will trigger the showMessage function and pass our message to HelloWorldAction, which will be responsible to delivery it to the dispatcher, here is the HelloWorldAction code:

1
2
3
4
5
6
7
8
9
10
11
12
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
 
var HelloWorldAction = {
	showMessage:function(message){
		Dispatcher.handleViewAction({
			actionType:'SHOW_MESSAGE',
			message:message
		});
	}
}
 
module.exports = HelloWorldAction;

Here I’m just wrapping my message that in this case will be my payload, and I’m also assigning an actionType to it, then I’m passing this action to the dispatcher:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');
 
var AppDispatcher = assign(new Dispatcher(),{
	handleViewAction:function(action){
		this.dispatch({
			source:'VIEW_ACTION',
			action:action
		});
	}
});
 
module.exports = AppDispatcher;

This is the dispatcher code, here we have the implementation of the handleViewAction function that is receiving the payload from the HelloWorldAction, the purpose of this is to broadcast it to the stores, then the appropriate store can perform the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
 
var AppStore = assign({},EventEmitter.prototype,{
	emitChange:function(){
		this.emit('change');
	}
});
 
AppDispatcher.register(function(payload){
	alert(payload);
});
 
module.exports = AppStore;

Lastly we have our store, here I’m implementing and registering in the dispatcher the method that will actually show the message.

That’s it, now before you run it, since we used jsx code, you have to use browserify and reactify to compile it.

I know I didn’t give too much details on this tutorial, this application is so simple that it’s kind of weird to write that much code just to show a hello world message, I’m looking forward to write another post with a more complex application, this way we can explore react and flux a little further.