Friday, 14 February 2014

Java: Add click listener to a Button

Following example adds a listener to the button:

private void addListenerToButton()
{
JButton button = new JButton("OK");
button.addActionListener(new ActionListener()
{

@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("You have clicked OK button");
                                // perform any other operations here
}
});
}

Another example:

private void addListenerToButton()
{
JButton button = new JButton("OK");
button.addActionListener(new OkButtonListener());
}

public class  OkButtonListener implements ActionListener
{
                     
                    @Override
public void actionPerformed(ActionEvent e)
{
System.out.println("You have clicked OK button");
                                // perform any other operations here
}
}

Java: Check if a string contains only digits

Following methods checks if the string contains only numbers

private boolean parseInt(String str)
{

try
{
Integer.parseInt(str);
                                return true
}
catch (Exception e)
{
new MessageDialog("Error", "Numeric fields should contain digits", JOptionPane.ERROR_MESSAGE);
                               return false;
}

}


Following method checks if the string contains numbers then returns a number otherwise returns 0


private int parseInt(String str)
{
int number = 0;
try
{
number = Integer.parseInt(str);
}
catch (Exception e)
{
new MessageDialog("Error", "Numeric fields should contain digits: " + str, JOptionPane.ERROR_MESSAGE);
}
return number;
}


Another simple way of checking if a string contains only digits is using regular expression

String regex = "\\d+";
Where the + means "one or more" and \d stands for "digit".
Note: the "double slash" gives only one slash. "\\d" gives you: \d
private boolean isDigit(String data)
{
boolean isDigit = false;
String regex = "\\d+";
isDigit = data.matches(regex);
return isDigit;
}

Thursday, 13 February 2014

Java: Converting util:Date to sql.Date

Sometimes it is needed to convert java.util.Date to java.sql.Date. An example of this scenario is getting input from user for date of birth through GUI. The date inserted by user will be stored in the database where sql.Date will be required.

Here is one method ho to convert util.Date to sql.Date

java.sql.Date utilDatetoSQL(Date utilDate)
{
           if(utilDate == null)
                   return null;
         
           java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
           System.out.println("Util Date: " + utilDate);
           System.out.println("SQL Date: " + sqlDdate);

           return sqlDate;
}

Another method is by using the Calendar

java.sql.Date utilDatetoSQL(Date utilDate)
{
           java.util.Calendar cal = Calendar.getInstance();

cal.setTime(utilDate);

java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

               return sqlDate;
}



Wednesday, 12 February 2014

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

The error occurs because we do not have the MySQL Connector/j in the Project build path. To get rid of this error check if you have


Connecting Java and MySQL in Eclipse

In order to Connect to a database, java needs an interface. Therefore, JDBC (Java database connectivity) serves the purpose of establishing a connection between the database and Java.


Once this is set, we can create a class that will provide us with the database connection:


package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection
{
private static String driver = "com.mysql.jdbc.Driver";

private static String url = "jdbc:mysql://localhost:3306/";

private static String dbname = "myDBName";

private static DBConnection instance = null;

private static Connection conn = null;

private DBConnection()
{
}

public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}

public Connection getConnection()
{
if (conn != null) return conn;
try
{
Class.forName(driver).newInstance();
}
catch (java.lang.ClassNotFoundException e)
{
System.out.println("ClassNotFoundException: " + e.getMessage());
e.printStackTrace();
}
catch (InstantiationException e)
{
System.out.println("InstantiationException: " + e.getMessage());
e.printStackTrace();
}
catch (IllegalAccessException e)
{
System.out.println("IllegalAccessException: " + e.getMessage());
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
try
{
conn = DriverManager.getConnection(url + dbname, "root", "root");
}
catch (SQLException ex)
{
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
if (conn != null)
{
System.out.println("connection established");
}
else
{
System.out.println("Failed to make database connection!");
}
return conn;
}

}


Write a driver to test the DBConnection class:


public class DBConnectionDriver 
{

public void DBConnectionDriver()
{
DBConnection dbConn = DBConnection.getInstance();
Connection conn = dbConn.getConnection();
try
{
if (conn != null) conn.close(); // Perform any task
}
catch (SQLException e1)
{
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
}
}

}


Eclipse: Adding Jars to project build path

Follow the steps in order to add a jar to the project build path in Eclipse.

  • Right click the project 
  • Go to Build Path
  • Select Configure Build Path
A project properties window pops up in Eclipse


from this window click the Libraries tab.
  • Click Add External Jars and select the Jars you want to add to your project build path.
  • Click OK and your are done 

Download driver for connecting MySQL to Java

In order to connect Java to MySQL we need Connector/j. Connector/j is the MySQL JDBC driver.
It can be downloaded from MySQL website LINK.

After downloading the file extract it to your MySQL folder. The download contains a JAR file.


Monday, 10 February 2014

MySQL create table query and Example

Database information is saved in a table. In order to create a table execute following query:

mysql> CREATE TABLE TABLE_NAME (
FIELD1 INT NOT NULL PRIMARY KEY,
FIELD2 CHAR2(25),
FIELD3 INT(9));

Explanation:
  • The INT in the field1 shows that this field will contain only integers
  • NOT NULL makes sure that this field is not left empty
  • PRIMARY KEY keyword in the query makes the FIELD1 as the primary key of the table. The values in the primary key field should be unique.
  • The CHAR(25) and INT(9) commands allow character type data in FIELD2 and integer type data in FIELD3 respectively. The numbers in the parenthesis are the maxium number of ints or chars in the fields.

Example:

CREATE TABLE CUSTOMER (
account_number int  NOT NULL PRIMARY KEY,
date DATE,
name VARCHAR(20) NOT NULL,
address VARCHAR(60) NOT NULL,
advance INT,
nic_number VARCHAR(20)
);

This query creates a table named "customer" with the primary key "account_number" of type int.
Other fields created in the table are:

  •  'date' of data type date, 
  • "name" field of datatype varchar with a size 20 characters max. It also declares that name cannot be null
  • "address" field of datatype varchar with a size 60 characters max. It also declares that address cannot be null
  • "advance" field of datatype int 
  • "nice_number" field of datatype varchar with a size 20 characters max
In order to make sure that the table is created and has everything right, check the existing table in the database by

mysql>show tables;

mysql>explain customer;


MySQL select or use a database query

From the mysql command line execute the following query:

mysql> use databasename;

for example to use a database "test" type the query;

mysql> use test;

in order to check if your selected database is in use, execute the query:

mysql> select database();

we have to use the database() function.

MySQL Create Database Query Example

Go to Start Menu and find and run mysql:

on the mysql prompt first check if a database with the same name already exit.


  • mysql> SHOW DATABASES;

If your database is not in the provided list then run the following query to create a database:

CREATE DATABASE <DATABASENAME>;

Replace the  <DATABASENAME> with your database name.

For example to create a database with the name test:

  • mysql> CREATE DATABASE test;
In order to check if your database is created then run the show databases query again.


  • Commands do not have to be entered in the upper case.
  • All MySQL queries must end with the semicolon ";"







Thursday, 6 February 2014

Java: How to get the size of the screen

private Dimension getScreenSize(String title)
       {
             Toolkit toolkit = getToolkit();
             Dimension screensize = toolkit.getScreenSize();
             return screensize;
       }

If this size is meant to be used for the frame that can be achieved as follows:

private void configureFrameWindow(String title)
       {
             setTitle(title);
             setDefaultLookAndFeelDecorated(true);
             Dimension screensize = getScreenSize();
             setPreferredSize(screensize);
             setMinimumSize(screensize);
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/ icon.png"));
             if (icon != null) setIconImage(icon.getImage());
             setResizable(false);

       }

Friday, 31 January 2014

Update ADT


  1. Open Eclipse and go to the Help menu
  2. Install New Software
  3. Add Location: https://dl-ssl.google.com/android/eclipse/
  4. after loading you should get Developer Tools and NDK Plugins
  5. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  6. click Next
  7. click Finish

Thursday, 23 January 2014

Using Subclipse with Eclipse and configuring for Google Code

Assuming that you have installed and are using Eclipse.

  1. Go to Eclipse Help menu and click on "Install New Software"
  2. Install Subclipse:
    Add the following site for subclipse
    http://subclipse.tigris.org/update_1.10.x/
  3. Select both "Subclipse" and "SVNKit" from the names which appear after adding the subclipse link
  4. Click Next, accept conditions and let eclipse download and install subclipse
  5. Now restart Eclipse after the installation
    Subclipse will be ready to use now
  6. Go to "preferences" under the windows menu
  7. Go to "Team" in the left menu and then select "SVN" sub-menu
  8. In the "General SVN Setting" select Team and "SVN" sub-menu
    Select SVNKit (Pure Java)--- in the "SVN interface" drop-down menu
Next step is to connect subclipse with google code

First we have to create a project. Instructions for creating a project can be found on
Creating Project on Google Code

Once a project has been created on the Google Code, Subclipse has to be connected to the project.


  1. Go to Eclipse, Click on "Windows" menu, "Show View" and select "Other"
  2. Select "SVN' and "SVN Repositories" and click OK.
  3. Right Click in the "SVN Repositories" tab and choose "New" - "Repository Location"
  4. "Add SVN Repository" window opens.
  5. Go to the Source tab and under Checkout you will find your svn checkout URL
  6. For the Location URL, give your URL which should be like  https://your_url.googlecode.com/svn/trunk
  7. In my case the URL is "https://agent-desktop.googlecode.com/svn/trunk" for the project which was created in Creating Project on Google Code post. Click Finish after providing the URL
  8. After Finishing you will be asked for the username and the password
    this password can be found on project home page under the SVN tab. Search for the link googlecode.com password
  9. Under the Source -> Checkout, Click the link (googlecode.com password) and save the generated password.
  10. Now the Subclipse is connected to the Google code
Next Step is to Commit your project code 

Follow instructions for committing code on Google Code project repository. 





Committing your Eclipse project to Google Code hosting

We are assuming that:

  1. Link ->You have created a project on Google Code
  2. And you have connected Subclipse with Google Code

If you have just created the project on Google code and connected Subclipse. Visit your "Source" tab (on Google Code your project home page) and then "Browse". Yet there is nothing. In order to send the project from your computer to Google Code repository it has to be committed. 

If this is the first time you are going to commit your code to the repository then
  1. Go to Package explorer in Eclipse
  2. Right click your project and select "Team" and "Share Project"

3. Select SVN and click Next

4. Check "Use existing repository location", select the repository that you have created and click Next
5. Press Next Next and on asking for password provide the password which is under "Source" tab of your project repository. Click googlecode.com password 
It will take you to the window where you can see your user name and password.

NOTE: Remember to change the username as well. Provide the one that is written in the repository (Maybe your email ID)

After the above first time (one time) process, follow these steps to commit your code to the repository:
  1. Go to Package explorer in Eclipse
  2. Right click your project and select "Team" and "Commit"
  3. A Commit window opens. Add a comment e.g added feature bla bla
  4. In the same Commit window the changes portion in the bottom shows the files that have been changed in your project since the last commit. If its the first time then everything will be displayed.
  5. Select or deselect whatever you want to send / not sent to the repository.
  6. One can choose not to commit the bin files
  7. Press OK
  8. Now go to the repository on the Google code project. Browse the source and your project will be uploaded

Creating and Hosting project on Google Code

Google provides free hosting for open source projects. Following are the steps to get started with the Google code project hosting:

  1. Go to Project Hosting Main Page
    Sign in with your Gmail account

  2. Here one can search through different projects which are already running and some can be joined as well. (one can use this if interested in working with a project which is already there). We will create our own project
  3. Go to Create New Project Page
  4. Provide Project name. In my case it is Agent Desktop
    Provide a name with lower case characters. Project name becomes the part of your project's URL
  5. Provide Summary and Description
  6. Choose "Subversion" for version control system
  7. For guidelines on how to choose licence and version control system visit
    http://opensource.org/licenses/category
    https://code.google.com/p/support/wiki/ChoosingAVersionControlSystem
  8. Further instructions can be found on
    https://code.google.com/p/support/wiki/GettingStarted
  9. Click "Create Project" and your project is created.
  10. Go to project and select the source tab. Here a link is mentioned for SVN checkout which should be like http://your-project-name.googlecode.com/svn/trunk

Sunday, 12 January 2014

Android: Display a list dialog box

Following program will display a dialog box containing a list of items.
Different operations can be performed on the items present in the list by implementing the onClick section.

private void showListDialog(ArrayList<String> list)
{
int l = list.size();
final CharSequence[] items = new String[l]; // not a good way
for (int i = 0; i < l; i++)
items[i] = list.get(i);

final AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);
builder.setTitle("List Dialog");

builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
// perform some function on item being clicked
}
});

AlertDialog alert = builder.create();
alert.show();
}





Android: Changing application name in eclipse

Change the "Android:label" field in the application node in AndroidManifest.xml.

'android:label="@string/app_name"' can be found in
/res/values/strings.xml

Definition for string app_name:
<string name="app_name">APP NAME</string>

Saturday, 11 January 2014

Android: Using SQLite Manager plugin in Eclipse

If SQLite is used while developing Android applications, database structure and data can be checked within Eclipse.

Follow these steps:

  1. Go to DDMS perspective
  2. Select -> data-> data-> package name-> databases (the table and data cannot be seen without the plugin)
  3. Download the jar file from here into eclipse/dropins folder
  4. Restart Eclipse
SQLite managers window opens by clicking the icon pointed by the arrow.


The structure of the database can be viewed in DataBase Structure tab and the data can be viewed in the browse data tab.

Android: Get boolean value from the database

Kindly read about SQLite datatypes.
Here is how can we retrieve boolean value

           try
{
String query = "Select 'check_in_time', 'total_hours', 'active' from hours where job_title = '" + taskName + "'";
cursor = adtDB.rawQuery(query, null);
while (cursor.moveToNext())
{
long checkInTime = cursor.getLong(0);
long totalHours = cursor.getLong(1);
boolean active = cursor.getString(2).equalsIgnoreCase("TRUE");
}
}
catch (Exception e)
{
Utils.println(e.getMessage());
}
finally
{
if (cursor != null) cursor.close();
close();

Thursday, 9 January 2014

Android: ListView Example

package com.adt.app;

import adapters.HoursListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import database.ADTDBHelper;

public class HoursListActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{ // TODO
super.onCreate(savedInstanceState);
setContentView(R.layout.hours_list);
ADTDBHelper db = new ADTDBHelper(this);
HoursListAdapter adapter = new HoursListAdapter(this, db.getHours());
ListView listView = (ListView) findViewById(R.id.hours_lv);
listView.setAdapter(adapter);

ImageButton homeBtn = (ImageButton) findViewById(R.id.header_home);
homeBtn.setOnClickListener(this);
}

@Override
public void onClick(View v)
{
if (v.getId() == R.id.header_home)
{
Intent i = new Intent(this, ADT.class);
startActivity(i);
}
}
}

Imran Khan in my View .... A Situation before Election.




Situation is getting worse day by day and everyone is not only worried about the ever increasing prices of electricity, petrol, gas but also mourn about unavailability. The situation is panic . Pakistan is  losing its integrity all over world due to memo case and many other such events ……. Everyone is now looking towardAlmighty Allah to help them come out of this situation and send a MASEEHA to help all get out of chaotic situation.
Meanwhile Imran Khan comes up with great JALSA in Lahore and had become in flashlight. Media is giving coverage of every second and boasting Imran as the only HOPE of the nation. We can easily get an insight about the popularity of Great Cricketer-come-Politician by simply watching around us, in markets, schools, colleges, universities, bus stands. Everyone is discussing about politics and taking Imran as the only Hope of dying nation as people of  Pakistan have tested all faces twice or thrice and are now fed up of all they want change and Imran have come up as a strong candidate for CHAIR. Youth is showing their confidence and enthusiasm and is active to support him. And the graph of popularity is going up day by day.
Earlier we have seen Imran struggling over the years to establish him in nations politics and had support from youth, the youth who has seen him holding the world cup for them and bringing pride to Pakistan, but he could not get any break through, we have also seen him committing some mistakes and hurting his supporters but that is PAST.
Well Imran was in discussion from the time when he has came out to make Shoukat Khanum Cancer hospital and people from every age of life supported him . But no one knew that one day he will again unite this nation and will drive them.
After coming to politics he struggled a lot in last 15 years, he fought bravely stood before others and tried to put his point of view, but was not that successful as he just had the support of youth that has nothing to do with politics at that time. But now the youth is seemed to be in main stream and time will show what change they can bring in national politics.
Politics in Pakistan is I will say a family politics …. There are just few faces with 2, 3 parties and come after one another….so v could not see any change until any dictator comes and take charge. All faces are now exposed all the nation have tried and tested them all one by one, all were desperate about ongoing situation.
After giving an entry with tsunami in Lahore Imran khan has increased enthusiasm of public in politics and has become an increasing threat for existing parties who don’t even bother to think about him as a politician. All were busy confirming their positions in establishment for next elections. But all of the sudden whole scenario has change after Lahore tsunami. Politicians and establishments are restless not only by increasing popularity of Tehreek-e-Insaaf but also about their key party members leaving them and joining hands with Imran Khan.
Long after Zulfiqar Ali Bhutto Imran have brought out educated people who have never voted and was not interested in politics any more. Now people from all walks of life are out to support Imran as he is only Hope for Nation now. He has a charisma in his personality that what he decides people follow him blindly. This is a big success for him as half the work is done.Now we are waiting to see if he can stir the minds and hearts of people in Quetta and have a bewitching effect on them that they blindly follow him and support him in coming elections.
After hearing him I looked on him as a serious and cool minded Politian as he does not shows much enthusiasm in his speeches as we are familiar with. He has put forward himself as a strong personality over the years and man of determination and the way he have brought political rivals under one umbrella shows his sense of politics. He is a visionary man. Now he is here to eradicate plague of corruption from society and provide INSAAF on every door step.
International media is claiming that IK have caught sight and fame of people due to the failure of Zardari’s policies...and also attracted people with his opinion against America and drone attacks.
Let us hope we will have a fair election because it is the only way that will show clear picture what people of Pakistan are thinking and feeling now, and wait to see what happens in next elections because we also have seen that number in rallies does not actually confirms your position in establishment but keeping in view the media reports he is most favorite candidate for next elections as most of the Pakistani living in or abroad are fully supporting him.
Let’s see who will come next and with what…..whether he will stick to his promises with public or deviate and deceive nation as its common practice since ages.
It will be a great Challenge for Revolutionary Leader to bring change and keep up with hope of people as the situation in Pakistan is far worst then anyone can imagine.

Monday, 15 April 2013

Java: Insert values into table using prepared statement Derby


Following method adds a record to the database table:
  
public void addPerson(Person p) {
        if (p == null || p.getName().equals("")) {
            return;
        }

        String name = p.getName();
        String address = p.getAddress();
        String phone = p.getPhone();

        Connection con = null;
        try {
            con = getConnection();
            if (con != null) {

                String sql = "INSERT INTO APP.ADDRESS_BOOK("
                        + "NAME,"
                        + "ADDRESS,"
                        + "PHONE) "
                        + "VALUES(?,?,?)";

                PreparedStatement pStmt = con.prepareStatement(sql);

                // Set the values
                pStmt.setString(1, name);
                pStmt.setString(2, address);
                pStmt.setString(3, phone);

                // Insert
                pStmt.executeUpdate();
            }
        } catch (SQLException ex) {
            Logger.getLogger(PersonDAO.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.getMessage());
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(PersonDAO.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println(ex.getMessage());
                }
            }
        }
    }

Java: how to check in servlet which html button was pressed


We can define two buttons in the html page:

<input type="submit" value="Add" name="addbutton">
<input type="submit" value="Search" name="addbutton">



Then in the servlet in the get or post method get the values for the buttons. Button pressed will have a value and the one not pressed will be null:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String add = request.getParameter("addbutton");
        String search = request.getParameter("searchbutton");

        if (add != null) {
            response.sendRedirect("addperson.html");
        } else if (search != null) {
            response.sendRedirect("searchperson.html");
        }
    }

Java: Connect to Database (Derby)


public class PersonDAO {

//AddressBookDB is the database name to which we want to connect
    private final String url = "jdbc:derby://localhost/C:/Users/Administrator/.netbeans-derby/AddressBookDB";

    PersonDAO() {
    }

    private Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            con = DriverManager.getConnection(url, "test", "test"); // test, test are the //user name and password for the database.
        } catch (Exception e) {
            System.out.println("Exception occured while connecting to the database: " + e.getMessage());
            e.printStackTrace();
        }
        return con;
    }
}

Thursday, 20 December 2012

Written Numerous Times but Still Not Believed:



Written Numerous Times but Still Not Believed:
Having competed years of democracy and “truly” democratic system, people have-not yet been convinced it’s the best system available. The simple answer is the study of this government’s performance on vital matters like economy, governance, peace and development. Surely the results are not much encouraging.

The history has shaped numerous systems and the great Empires have been built and declined in the vicissitudes of time. What is commonly concluded that the better systems prevail, like today’s democracy and democratic systems have developed the limits to control the world. Undoubtedly it has become a benchmark and every other country is trying to imitate, in the suitable way it can.

Pakistan as a case study has done same it has been democratized repeatedly to move forward and even the anti-democratic agents have used the democratic skin to accumulate the rationale for their rule. In today’s time the countrymen have fought and won the democratic system for them, but with a capital “BUT”. Democracy is not an end in itself but it’s only a platform to acquire development, equity, justice and so on. The capital “BUT” suggests that this system didn’t help us at all to develop anyway. The proponents argue the continuity of system to deliver etc. but practically speaking the state of matters has not even stabled on the point where “non-truly” democratic system was wrapped. It has gone far worse and dejection prevails the horizons.

The purpose here is not to scream out political criticisms or hurl acquisitions, but to gauge some reason of situation. In my view all systems developed over time thoughtfully have enough good reasons to deliver but systems are not self start or automatically run. The people if are dishonest or disloyal, the system would collapse, this is exactly what happened to the Romans, the Bezentinians and Muslims to say. The ball is in our court. The exact time for us to separate ourselves from blind race of materialism. Honesty is hard earned wealth, truth pays late but worth’s believing. Satisfaction is the bride for those who choose tough ways to lead their lives. Our system is too good to believe, we have huge machinery to implement our policies and develop. What we need is only to be vigilant against what we should not do while walking on road, travelling, dealing with the family of God (the people around).

Usman Akhlaq
white.snowpeaks@gmail.com