DataGridView

The DataGridView is a control designed to be bound to database tables. You will find the DataGridView in the Data group on your Toolbox. In this section, we will use the DataGridView to build a SQL interface for the Northwind Trader database. This application is surprisingly simple using the classes provided by ADO.NET.

Figure 15.5

Image:Figure15_5.jpg
To create the user interface, place a TextBox on the form and set its Multiline property to true. Then, add two buttons, setting their Text properties to Query and Update. Finally, place a DataGridView component on the form. Your form might look something like the one in Figure 15.5.
Since we are going to connect to a Microsoft Access database, we need to use the OleDb classes. At the top of the file, you should add the following using statement to gain access to the System.Data.OleDb namespace.
using System.Data.OleDb;
The Form’s Load event should create an OleDbConnection object, an OleDbCommand object, and a DataSet object. Each of these objects should be stored as members of your Form class.
private void Form1_Load(object sender, EventArgs e) {
   // connect to the database
   string conString =
      @"Provider=Microsoft.JET.OLEDB.4.0;"
      + @"data source=c:\data\Northwind.mdb";
 
   // create an open the connection          
   conn = new OleDbConnection(conString);
   command = conn.CreateCommand();
 
   // create the DataSet
   DataSet ds = new DataSet();
   }
Next, you need to implement the select button’s Click handler. The method should start by clearing the DataSource property of the DataViewGrid and creating a fresh DataSet. Then, it should reopen the connection. Set the Command object’s CommandText property to the Text from the TextBox control. Then, create an adapter with the command and fill the new DataSet. Finally, set the DataGridView’s DataSource property to the first table in the DataSet’s Table collection.
private void button1_Click(object sender, EventArgs e) {
   // clear the grids data source
   dataGridView1.DataSource = null;
 
   // create a new DataSet
   ds = new DataSet();
 
   // open the connection
   conn.Open();
 
   // run the query
   command.CommandText = textBox1.Text;
   adapter = new OleDbDataAdapter(command);
   adapter.Fill(ds);
    
   // close the connection
   conn.Close();
 
   // set the grid's data source
   dataGridView1.DataSource = ds.Tables[0];
   }
The last step is to implement the Click event handler for the Update button.
private void button2_Click(object sender, EventArgs e) {
   // clear the grids data source
   dataGridView1.DataSource = null;
 
   // open the connection
   conn.Open();
 
   // run the query
   command.CommandText = textBox1.Text;
 
   int affected = command.ExecuteNonQuery();
   MessageBox.Show ("There were " + affected + " rows affected");
 
   // close the connection
   conn.Close();
   }
The update button sets the DataGridView’s DataSource property to null to clear the grid. Then, it reopens the connection and sets the command object’s CommandText property to whatever text is in the TextBox. This time the command is executed by the ExecuteNonQuery method. The ExecuteNonQuery method runs a command that updates or deletes records. It returns the number of rows affected by the command. Finally, the method displays a message box showing the number of rows affected and then closes the connection. Figure 15.6 shows a SELECT statement being executed on the database.

Figure 15.6

Image:Figure15_6.jpg
Figure 15.7 shows the update button being used to change the ContactTitle from Guru to Fool.

Figure 15.7

Image:Figure15_7.jpg
To verify that our update actually worked, we can run the query again.

Figure 15.8

Image:Figure15_8.jpg

Java Word Count

Word Count Example in Java

This example illustrates how to count the number of lines, number of words and number of characters in the specified file. Program takes the file name as parameter and it counts the number of words and lines present in the file. Parameter is optional and if you simply run the program without mentioning the file name then you will have to input some strings and program will count the number of characters and number of words for your given strings. This topic is related to the I/O (input/output) of java.io package.
In this example we are using FileReader class of java.io package. The File class is an abstract representation of file and directory pathnames.

Explanation
This program counts the number of lines, number of words and number of characters in the specified file. We will be declaring two functions called wordcount and linecount in the program. The function linecount has been overloaded according to the passing argument. If you input contents through the file then linecount function will be called (If specified file exists) otherwise main function counts the number of characters and number of lines (always, the number of line will be only 1 in this condition) itself but for the counting of the number of words by using the wordcount function.

wordcount(String line)
The function wordcount(String line) takes either the content of the specified file or arguments passed with the run command for a java program as parameter 'String line'. The wordcount() function is using arrayname.charAt(index) to find position of space in the string.  A counter variable 'numWords' is used to count the number of words.

linecount(String fileName);
The function linecount(String fileName) takes the specified file name as a string parameter and create a instance for the FileReader class to buffering then the file or string and it is passed to the function linecount(String fName, BufferedReader in).

linecount(String fileName, BufferedReader);
The function linecount(String fName, BufferedReader in) takes the specified file name and created instance in for the BufferedReader class by calling function linecount(String fileName) and assign the content of the buffer in a string variable line. And then the function linecount(String fileName, BufferedReader) counts and print the number of characters, number of lines. To count the number of words call the wordcount(String line) function.

Code of the Program : 
import java.io.*;

public class  WordCount{
  private static void linecount(String fName, BufferedReader in) 
  throws 
IOException{
  long numChar = 0;
  long numLine=0;
  long numWords = 0;
  String line;
    do{
      line = in.readLine();
      if (line != null){
        numChar += line.length();
        numWords += wordcount(line);
        numLine++;
      }
    }while(line != null);
    System.out.println("File Name: " + fName);
    System.out.println("Number of characters: " + numChar);
    System.out.println("Number of words: " + numWords);
    System.out.println("Number of Lines: " + numLine);
  }
  private static void linecount(String fileName){
    BufferedReader in = null;
    try{
      FileReader fileReader = new FileReader(fileName);
      in = new BufferedReader(fileReader);
      linecount(fileName,in);
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }
  private static long wordcount(String line){
    long numWords = 0;
    int index = 0;
    boolean prevWhiteSpace = true;
    while(index < line.length()){
      char c = line.charAt(index++);
      boolean currWhiteSpace = Character.isWhitespace(c);
      if(prevWhiteSpace && !currWhiteSpace){
        numWords++;
      }
      prevWhiteSpace = currWhiteSpace;
    }
    return numWords;
  }
  public static void main(String[] args){
    long numChar = 0;
    long numLine=0;
    String line;
    try{
      if (args.length == 0)
      {
        BufferedReader in =
        new BufferedReader(new InputStreamReader(System.in));
        line = in.readLine();
        numChar = line.length();
        if (numChar != 0){
          numLine=1;
        }
        System.out.println("Number of characters: " + numChar);
        System.out.println("Number of words: " + wordcount(line));
        System.out.println("Number of lines: " + numLine);
      }else{
        for(int i = 0; i < args.length; i++){
          linecount(args[i]);
        }
      }
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }
}

The Complete Reference 4.0


Flash Builder 4.5 – Mobile Highlights

Now that Flash Builder 4.5 and Flex 4.5 have been announced and will be available to the public soon, I’ve put together a list of some mobile highlights to show off more of what you can expect to do with this release. A bunch of new samples based around these releases are coming soon to Tour de Flex and Adobe AIR Launchpad!
Note: The Adobe AIR Launchpad is a great place to start with generating a mobile Flex project you can use as a wrapper for your application. The current version of Adobe AIR Launchpad available is based on Flash Builder Burrito but an updated version will be released when Flash Builder 4.5 and Flex 4.5 SDK are officially available to the public in a couple of weeks.

Mobile UI

  • Flex 4.5 includes new Spark Application types for mobile including the ViewNavigatorApplication and the TabbedViewNavigatorApplication. The TabbedViewNavigatorApplication would be used for more complex applications that might need several ‘sets’ or stacks of views, each managed by a tab that can be navigated through separately. Note: the naming of these root application tags has changed from the Flash Builder Burrito Preview, from MobileApplication and TabbedMobileApplication.
  • A mobile application includes an ActionBar and one or more Views or collections of views.
  • In a TabbedViewNavigatorApplication, each set of views will have its own ActionBar and only the tab bar is global to the application as a whole.
Here is an example of my RunTracker application which contains 3 tabs coded as ViewNavigator objects in MXML containing the firstView property set to the view to be shown first when the tab is clicked:
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
<?xml version="1.0" encoding="utf-8"?>
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                                  xmlns:s="library://ns.adobe.com/flex/spark" applicationComplete="init()">
    <fx:Declarations>
        <s:ArrayCollection id="runsAC"/>
    </fx:Declarations>
 
    <fx:Script>
        <![CDATA[
            import com.devgirl.runtracker.events.RunListResultEvent;
            import com.devgirl.runtracker.service.DBService;
            import com.devgirl.runtracker.dao.DatabaseHelper;
 
            protected var dbService:DBService;
 
            protected function init():void
            {
                DatabaseHelper.openDatabase(File.documentsDirectory.resolvePath("RunTracker.db"));
            }
        ]]>
    </fx:Script>
    <s:ViewNavigator id="milesTab" label="Miles" width="100%" height="100%" firstView="com.devgirl.runtracker.views.MilesView" firstViewData="{runsAC}"/>
    <s:ViewNavigator id="historyTab" label="History" width="100%" height="100%" firstView="com.devgirl.runtracker.views.HistoryView" firstViewData="{runsAC}"/>
    <s:ViewNavigator id="trendsTab" label="Trends" width="100%" height="100%" firstView="com.devgirl.runtracker.views.TrendsView" firstViewData="{runsAC}"/>
</s:TabbedViewNavigatorApplication>
The tab bar is created at the bottom of the application as shown in the following screenshot:

For a ViewNavigatorApplication, you will have one set of views, with the firstView property set on the root application tag as follows:
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.SimpleViewAppHomeView">
 
</s:ViewNavigatorApplication>
The ActionBar is created at the top of any type of mobile application and can contain navigational controls, a title and an action area. In the following Tour de Mobile Flex sample by James Ward, you can see there are many different areas of the mobile app that can be used. In this screenshot, the bar with the home icon, the title and Exit button are all considered part of the ActionBar. The icon is the navigationContent, followed by the titleContent, and the Exit button is considered the actionContent.

The code for the ActionBar would look something like the following:
1
2
3
4
5
6
<s:navigationContent>
    <s:Button icon="@Embed('assets/launchpad_home.png')" click="navigator.popToFirstView()"/>
</s:navigationContent>
<s:actionContent>
    <s:Button id="btn" label="Exit" click="onExit(event)"/>
</s:actionContent>
You can also specify titleContent with a tag similar to the above for the navigationContent and actionContent, but typically that is set using the title property from the view. Note: If these tags are put in the root application MXML they will be used globally in the application, however they can be overridden at the view level.

Navigation

One thing that may be somewhat confusing to developers new to this Flex mobile development is understanding the concept of the navigator property implicit to the ViewNavigatorApplication. A ViewNavigator object is already a property on the ViewNavigatorApplication and is used to navigate between views via the pushView() and popView() methods. For instance, if you view the ActionScript class for ViewNavigatorApplication.as you will see the property listed in it such as below:
1
2
3
4
5
/**
     *  The main view navigator for the application.  This component is
     *  responsible for managing the view navigation model for the application.
     */
    public var navigator:ViewNavigator;
You could then use the following to navigate to a view using the navigator property in your application such as:
1
navigator.pushView(viewsMyView,myData);
The TabbedViewNavigatorApplication includes a tabbedNavigator property as well as a navigators property with a type of Vector that you can use to determine the currently active ViewNavigator. I encourage you to look through the source code for these various classes to help you understand the relationships.

Mobile Menus

There is a new Spark ViewMenu component that is implicitly created at runtime when you hit the Menu button on the device. For devices without a Menu button, you can programmatically open it by setting the viewMenuOpen property to true on the main application. It will close when you click outside of the menu, otherwise you can set the viewMenuOpen property to false to close it as well. I have built a sample for this to include in AIR Launchpad and Tour de Flex that will be available soon. The only code you add for this menu is the array of ViewMenuItems, such as:
1
2
3
4
5
6
7
<s:viewMenuItems>
     <s:ViewMenuItem label="Add" click="onAdd(event)"/>
     <s:ViewMenuItem label="Cancel" click="onCancel(event)"/>
     <s:ViewMenuItem label="Delete" click="onDelete(event)"/>
     <s:ViewMenuItem label="Edit" click="onEdit(event)"/>
     <s:ViewMenuItem label="Search" click="onSearch(event)"/>
</s:viewMenuItems>

The menu is then shown at the bottom of the application and is also skinnable.

BusyIndicator

There is a new Spark BusyIndicator which is a spinning graphic with spokes and has a customizable symbolColor and rotationInterval property. Below is a screenshot of it in a sample coming soon to AIR Launchpad and Tour de Flex!

View Transitions

There are 4 types of view transitions that are currently available for use in your mobile application:
1) FlipViewTransition – performs a flip of the view as indicated by the FlipViewTransitionMode value (card or cube mode; see API docs for details)….
2) ZoomViewTransition – zooms out existing view or zooms in the new view based on the ZoomViewTransitionMode value (in or out).
3) SlideViewTransition – slides the new view or previous view as indicated by the SlideViewTransitionMode value (push, cover, uncover mode; see API docs for details)….
4) CrossFadeViewTransition – fades out to reveal new view
The default is SlideViewTransition. Note that these are different than the traditional Flex transitions associated with states, and are only used when changing views. You can specify a defaultPushTransition and defaultPopTransition property on the ViewNavigator object, or you can specify a transition to use when you are changing views using them as parameters in the pushView(), popView() methods.
Here is an example of how you might specify a default to use for all transition changes from the root application on a navigator:
1
2
3
4
...
navigator.defaultPopTransition = new FlipTransition();
navigator.defaultPushTransition = new CrossFadeTransition();
...
Or you might pass it on the navigator.pushView() method itself such as:
1
navigator.pushView(views.SampleView,myData,fadeTrans);
You can also set typical transition properties such as direction, duration as well as easing functions on the above transitions to create different effects.
Handling Resolution
  • Flex 4.5 includes a lot of features to help you manage resolution and DPI for your application to target or scale for different devices (phone versus tablet etc).
  • You can set an applicationDPI or determine and use the runtimeDPI with new properties available.
  • You can select different styles, bitmap image sources and skins to use now based on DPI. Samples of how to do this are coming soon in Tour de Flex, Tour de Mobile Flex and Adobe AIR Launchpad!
CSS Media Queries
You can now use @media rules in your style sheets to filter CSS rules based on the device’s DPI classification. There are two properties you can filter on currently, os-platform and application-dpi. Here’s an example of filtering on them to set a button font for instance (from Adobe’s prerelease docs):
1
2
3
4
@media (os-platform: "Android") and (application-dpi: 240) {
s|Button {
     fontSize: 10;
}

Persisting Data

  • Persisting of data can occur in-memory during the life cycle of your application or between application executions using session persistence.
  • Use in-memory persistence to save data when switching views using the data property on a View and passing your data as a parameter to the pushView() method.
    1
    navigator.pushView(views.SampleView,list.selectedItem);
    Note: The data property could be a value object or a model class etc.
  • Use session persistence to save data between application execution by setting the persistNavigatorState property to true on the ViewNavigatorApplication root (or TabbedViewNavigatorApplication root). The data is automatically saved to a local shared object with the name FxAppCache.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?xml version="1.0" encoding="utf-8"?>
    <s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
        firstView="views.MyMobileApp1Home"
        splashScreenImage="@Embed('assets/launchpad_title.png')" splashScreenScaleMode="letterbox"
        persistNavigatorState="true" initialize="onInitialize()"
        applicationComplete="onApplicationComplete()">
    ...
  • There are custom persistence options that can be used when you have custom classes to be serialized but that is beyond the scope of this article.

General Important Notes

  • The Flash Builder 4.5/Flex 4.5 releases announced today will initially include support for android-based devices (including tablets). However, iOS and Blackberry tablet support will be released in June (rumor has it ;) ).
  • Doing a release build export from Flash Builder of a mobile app will not output a .air file, but instead builds a native installer package (.apk for Android for instance). The beauty of this is that the packagers look and act the same was as a native application it terms of distribution and installation.
  • When you install the exported release package to an Android mobile device, if AIR is not installed, the user will be prompted to download it. Note: applications built with an iOS target have the AIR runtime included in the package and therefore there is no need to prompt the user for download when it runs. For Blackberry Playbook targets, the AIR runtime is already integrated into the Blackberry Tablet OS.
  • When you are reading documentation, soft keyboard refers to the keyboard that pops up on your mobile device when you click into a control that takes input. It’s important to note that you can programmatically set properties to enable or disable it, as well as handle how the application is resized etc when it pops up. Samples around this to come…
  • Scrollbars are hidden in favor of screen space until a mouseDown occurs where a component supports scrolling.
  • Favor FXG Graphics in your mobile applications rather than MXML Graphics and use ActionScript skins versus MXML skins.
  • Use non-TLF controls for text display, such as TextArea or TextInput over Label. You can use them to display text as you would with a Label and just set editable or selectable to false as desired.
  • if you need your application to run on web, desktop and mobile platforms, the recommended approach would be to design a separate user interface targeting the resolution and DPI, but share the same data model between platforms.
Additional Resources
Flex Mobile on Adobe Labs
Introducing Flex 4.5
Mobile Development with Flash Builder 4.5
What’s New in Flash Builder 4.5
Flex-Based iPad Trader App
Adobe TV – What’s New in Flash Builder 4.5