Sencha Touch 2 DataView Example using Java Servlet and MySQL

Sencha Touch Ext.DataView is the backbone of components such as Ext.dataview.List which helps the user to display a lot of repetitive data in a scrolling list. In this example we are going to learn how to use the DataView itself to display a List as well as some header information for that content using Xtemplate. The store data in JSON format comes from the MySQL database with the help of Java Servet using AJAX. This tutorial displays a list of countries and when the user clicks on a specific country it gets detailed information about it along with the list of cities.

POJO for City Information - City.java

package com.as400samplecode.util;

public class City {
 
 String name = null;
 String district = null;
 int population = 0;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getDistrict() {
  return district;
 }
 public void setDistrict(String district) {
  this.district = district;
 }
 public int getPopulation() {
  return population;
 }
 public void setPopulation(int population) {
  this.population = population;
 }
 
} 

POJO for Country Detail Information - CountryDetailObj.java

package com.as400samplecode.util;

import java.util.ArrayList;

public class CountryDetailObj {
 
 boolean success = false;
 String code = null;
 String name = null;
 String continent = null;
 String region = null;
 Double lifeExpectancy = null;
 Double gnp = null;
 ArrayList<City> cityList = null;
 
 public boolean isSuccess() {
  return success;
 }
 public void setSuccess(boolean success) {
  this.success = success;
 }
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }
 public Double getLifeExpectancy() {
  return lifeExpectancy;
 }
 public void setLifeExpectancy(Double lifeExpectancy) {
  this.lifeExpectancy = lifeExpectancy;
 }
 public Double getGnp() {
  return gnp;
 }
 public void setGnp(Double gnp) {
  this.gnp = gnp;
 }
 public ArrayList<City> getCityList() {
  return cityList;
 }
 public void setCityList(ArrayList<City> cityList) {
  this.cityList = cityList;
 }
 
} 

Java Servlet for our AJAX Request - CountryDetail.java

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.as400samplecode.util.City;
import com.as400samplecode.util.CountryDetailObj;
import com.google.gson.Gson;

public class CountryDetail extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public CountryDetail() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException {
  doPost(request,response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) 
 throws ServletException, IOException {

  String countryCode = request.getParameter("countryCode");
  
  PrintWriter out = response.getWriter();
  response.setContentType("text/html");
  
  CountryDetailObj country = getCountry(countryCode);
  
  Gson gson = new Gson();
  out.println(gson.toJson(country));
  out.close();


 }
 
 private CountryDetailObj getCountry(String countryCode) {  
  
  Connection conn = null;             
  PreparedStatement stmt = null;      
  String sql = null;
  
  CountryDetailObj country = new CountryDetailObj();
  ArrayList<City> cityList = new ArrayList<City>();    
  
  try {       
   Context ctx = (Context) new InitialContext().lookup("java:comp/env");
   conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); 

   //get the cities for the given country
   sql = "Select * from city where countryCode = ? order by name"; 
   stmt = conn.prepareStatement(sql);
   stmt.setString(1, countryCode.trim()); 
   
   ResultSet rs = stmt.executeQuery();  
   
   while(rs.next()){ 
    City city = new City();
    city.setName(rs.getString("name").trim());
    city.setDistrict(rs.getString("district").trim());
    city.setPopulation(rs.getInt("population"));
    cityList.add(city);
   }                                                                          

   rs.close();                                                                
   stmt.close();                                                              
   stmt = null;     
   
   //get the country information
   sql = "Select * from country where code = ?"; 
   stmt = conn.prepareStatement(sql);
   stmt.setString(1, countryCode.trim()); 
   
   rs = stmt.executeQuery();  
   
   if(rs.next()){ 
    country.setCode(rs.getString("code").trim());
    country.setName(rs.getString("name").trim());
    country.setContinent(rs.getString("continent").trim());
    country.setRegion(rs.getString("region").trim());
    country.setLifeExpectancy(
     rs.getString("lifeExpectancy") == null ? 
     new Double(0) : 
     Double.parseDouble(rs.getString("lifeExpectancy")
       .trim()));
    country.setGnp(
     rs.getString("gnp") == null ? 
     new Double(0)  : 
     Double.parseDouble(rs.getString("gnp").trim()));
    country.setSuccess(true);
    country.setCityList(cityList);
   }                                                                          

   rs.close();                                                                
   stmt.close();                                                              
   stmt = null;                                                               

   conn.close();                                                              
   conn = null;                                                    

  }                                                                
  catch(Exception e){System.out.println(e);}                       

  finally {                                                        
   
   if (stmt != null) {                                             
    try {                                                          
     stmt.close();                                                 
    } catch (SQLException sqlex) {                                 
     // ignore -- as we can't do anything about it here            
    }                                                              

    stmt = null;                                             
   }                                                         

   if (conn != null) {                                       
    try {                                                    
     conn.close();                                           
    } catch (SQLException sqlex) {                           
     // ignore -- as we can't do anything about it here      
    }                                                        

    conn = null;                                             
   }                                                         
  }               

  return country;

 }   

}

Application HTML file - index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow"/>
<title>Programmers sample guide, help is on the way</title>
<link rel="stylesheet" href="/sencha-touch/resources/css-debug/sencha-touch.css" type="text/css">
<link rel="stylesheet" href="/resources/themes/app-master.css" type="text/css" />
<link rel="stylesheet"
 href="/sencha-touch/resources/css-debug/sencha-touch.css"
 type="text/css">
<style>
    .headerInfo{
        margin: 5px;
    }
    .detailInfo{
        margin: 5px;
    }
    .cityInfo{
        padding: 5px;
        border-bottom-style:solid;
  border-bottom-width:1px;
    }
</style>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript" src="/sencha-touch/sencha-touch-all-debug.js"></script>
<script type="text/javascript" src="../resources/scripts/dataView.js"></script>
</head>

<body>
</body>
</html>

Application Javascript file - dataView.js

Ext.Loader.setConfig({ 
 enabled: true 
});

Ext.application({
    
 name: 'MyApp',
 appFolder: '/Sencha_Touch/app/dataView',
 
 requires: [
               'MyApp.view.MainPanel',
               ], 
               
    views : ['MainPanel'],           
    controllers: ['DataViewDemo'],
    
    launch: function() {
     console.log('Application launch');
     Ext.create('Ext.Container', {
      fullscreen: true,
      layout: 'vbox',
         items: [{
          flex: 1,
          xtype: 'mainPanel'
            }]
     });
    }
    
});

Application Navigation View - MainPanel.js

Ext.define('MyApp.view.MainPanel', {
 extend: 'Ext.navigation.View',
    alias : 'widget.mainPanel',
    
    requires: ['MyApp.view.CountryList',
               'MyApp.view.CountryInfo'],
               
   config: {
       
       scrollable: false,
       
       items: [{
           xtype: 'countryList',
           title: 'Countries'
       }]
   }
});

View for List of Countries - CountryList.js

Ext.define('MyApp.view.CountryList', {
    extend: 'Ext.dataview.List',
    alias : 'widget.countryList',
    
    config: {
     store: {
            fields: ['name','code'],
            data: [
                {name: 'United States of America', code: 'USA'},
                {name: 'Canada', code: 'CAN'},
                {name: 'Brazil', code: 'BRA'},
                {name: 'China', code: 'CHN'}
            ]
        },

        onItemDisclosure : true,
     itemTpl: '<div class="myContent">'+ 
        '<div>Country Code: <b>{code}</b></div>' +
        '<div>Name: <b>{name}</b></div>' +
        '</div>'
    
    } 
});

DataView for our Country Detail Information - CountryInfo.js

Ext.define('MyApp.view.CountryInfo', {
    extend: 'Ext.dataview.List',
    alias : 'widget.countryInfo',
    
    config: {
     
     loadingText: null,
     scrollable: {
            direction: 'vertical',
            directionLock: true
         },
         
           
        style: 'background-color:#eee9e9',   
        store: {
           autoLoad: false,
           fields: ['code',
                    'name',
                    'continent',
                    'region',
                    'lifeExpectancy',
                    'gnp',
                    'cityList'],
           
           proxy: {
                type: 'ajax',
                url: '../CountryDetail',
           
                reader: {
                    type: 'json'
                }
           }
        },
           
        itemTpl: 
           '<div class="countryInfo" >' +
           '<div class="headerInfo" >' +
           'Country is <b>{name} ({code})</b><br/>' +
           'Continent is {continent}<br/>' + 
           'Region is {region}<br/>' + 
           'Life Expentancy is {lifeExpectancy}' + 
           '</div>' +
           '<div class="detailInfo" >' +
           '<tpl if="cityList.length &gt; 0">' +
       '<u><b>List of Cities in {name}</b></u>' + 
       '<tpl for="cityList">' +
        '<div class="cityInfo" >' +
        '<p><b>{name}</b><br/>District is {district}<br/>Population is {population}</p>' + 
        '</div>' +
       '</tpl>' +
     '</tpl>' +
           '</div>'
    }
});

Application Controller - DataViewDemo.js

Ext.define('MyApp.controller.DataViewDemo', {
 extend : 'Ext.app.Controller',
 
 config: {
  
  profile: Ext.os.deviceType.toLowerCase(),
  refs: {
   myNavigationView: 'mainPanel',
   myCountryInfo: 'countryInfo',
  },
        control: {
   'countryList': {
             activate: 'onActivate',
             itemtap: 'onItemTap',
             disclose: 'onItemDisclosure'
           }
        }  
  
    },
    
 onActivate: function() {
     //console.log('Main container is active');
    },
   
    onItemTap: function(list, index, target, record, event) {
     //console.log('Item was tapped on the Data View');
     //console.log(list, index, target, record, event);
     this.loadCountry(record.get('code'));
    },
    
    onItemDisclosure: function(list, record, target, index, event) {
     //console.log('Disclosure Icon was tapped on the Data View');
     //console.log(list, index, target, record, event);
     this.loadCountry(record.get('code'));
    },
    
    loadCountry: function(code){
     console.log('Display the Country Information'); 
     var navigationView = this.getMyNavigationView();
        var countryInfo = Ext.widget('countryInfo',{
         title: 'Country Info'
        });
       
        
        navigationView.setDefaultBackButtonText('Countries');
        navigationView.push(countryInfo);
        
        this.getMyCountryInfo().getStore().removeAll();
        this.getMyCountryInfo().getStore().load({
            params: {
                'countryCode': code
            }
        });  
    }
   
});

References


3 comments :

  1. Gratefulness touches deeply the tenderness fifa 14 coins of my heart, rendering me ever-profound perception cheap fifa 14 coins as well as ever-soft emotion. It is like the soft melody of “ kiss the rain”, so tender, so emotional fifa 14 coins and so fascinating, leaving me out of all the worldly troubles.

    ReplyDelete