Monday, October 01, 2012

Most Presentation Stink!

Saturday, August 11, 2012

Difference Between Primary key and Unique key


Primary key and Unique key constraints are important feature in database system. They have some key identity which is important to know.

Unique Key constraints:
Unique key constraint will provide you a constraint like the column values should retain uniqueness.
It will allow null value in the column.
It will create non-clustered index by default
Any number of unique constraints can be added to a table.

Primary Key Constraint:
Primary key will create column data uniqueness in the table.
Primary key will create clustered index by default
Only one Primary key can be created for a table
Multiple columns can be consolidated to form a single primary key
It won't allow null values.

Monday, August 06, 2012

Learn GitHub - Introduction To Git

GitHub is a web-based hosting service for software development project that use the Git revision control system.
It will seems very difficult to co-operate with GitHub with novice people. But after using it, it will seems to you like magic. I hope you know why we will use GitHub!
If you are new to GitHub then below video will help you to start properly.
You can start from book also. There have several book but I will prefer you to start with this book Pro Git.
I hope this video and book will help you.

Wednesday, July 11, 2012

Exception "android.os.NetworkOnMainThreadException" !


This is common in android to get error on http or networking connection with this message "android.os.NetworkOnMainThreadException" . 
This exception is thrown when an application attempts to perform a networking operation on its main thread .
Run your code in AsyncTask that will solve your problem:

Hints: 
           Thread msgThread = new Thread(){
            
            public void run(){
                  
                        http.httpConnectionMsg(nvp,is,msgurl);
            }   
}

msgThread.start();

Thursday, July 05, 2012

Access localhost/Server on Android device over wifi


Recently in one of my android project I have used XAMPP for database. For accessing  database/localhost/server from my application I have use ip address 10.0.2.2 . That is the way for getting  localhost from android device. But when I have installed that application in my real device that was unable to get the server  . How that will get the server? I have use 10.0.2.2 for http connection . So, getting the server we have to make a connection between android device and our server location. We can do it by connecting with connectify software that will help us to communication device with our server. And in this time have to use in this time the ip address create by WIFI connection as we are creating connection with the server by using wifi.

In this situation I have used cracked "Connectify" so that my android device have the access of my laptop
local network access. In the lite version of connectify you won't get the options for allowing "Local Network Access " .




After establishing connection have to go command prompt . Write "ipconfig" to get the ipv4 address.
In the command prompt which ip address is given , you have you use that ip address in your application for getting the server. (Below red marked line : you have to use that ip address)



Before editing your code you can also check from your android device is it working or not . For that you have to go browser then write the ip address in the url then we will get the localhost.

















Set up ADB/Drivers for android Device and Some important Commands


Most people won’t have to use ADB (Android Debug Bridge) ever, but if you want to learn how or want to get a little more technical with your Android phone, here’s how to get it set up.
I. Setting Up The SDK
1. Download the Latest Android SDK from Google
Android SDK (Select the exe version)
2. Once downloaded, double click the exe file to open it. (MAKE SURE you change the directory that it is installing everything to to c:\android-sdk\)
3. Click on the SDK Manager and it will ask you to install packages. Select the following and leave all others unchecked:
Android SDK Tools
Android SDK Platform Tools
Google USB Driver Package, Revision XX (XX being the highest number available)
4. Then click continue and follow the on screen prompts until all of the packages are installed and it finishes.
5a. On your phone, click Settings > Applications > Development and make sure USB Debugging is on.
5b. If using Ice Cream Sandwich (Android 4.0), click on Settings > Developer Options and make sure USB Debugging is on.
6. Plug your phone into your computer via USB cable (it needs to be on). It should say installing drivers if using Windows.
7. Open Windows File Explorer and look for the android-sdk folder inside of the C drive. Then open the platform-tools folder inside that. Now, hold the shift key down on your keyboard and right click in any blank area inside that folder. This will give you the option to open a command window here. Select that and a command prompt will open saying c:\android-sdk\platform-tools\      *if using windows XP, this won’t work. So instead open command prompt first by going to Start > Run > then typing in cmd and hitting enter. Then type cd c:\android-sdk\platform-tools\ and hit enter, then continue.
8. Type the following into the command prompt window (hitting enter at the end of every line):
adb devices
You should see a serial number pop up, it’s the serial number of your phone. This means you are all set!
If you do NOT see a serial number, then we need to reinstall the drivers manually in Section II below.
II. IF DRIVERS JUST WON’T AUTOMATICALLY INSTALL, DO IT MANUALLY HERE
1. A program called PDANet (used normally to allow you to wired tether your phone’s internet to your computer) can be used to install the ADB drivers for a lot of phones. Download it and follow it’s instructions to install it then go back to step 8 in Section I above and see if that gets you the serial number (if you do, you are all done). If not, then use one of the device specific programs below in step 2.
2. Download your phone’s driver’s below then goto your Device Manager on your computer, look for the phone and click on it. Then click Properties > Update Driver > Browse > Let me pick > Computer > Have Disk > Browse > Then select the driver you downloaded below:
Universal Motorola Drivers (unzip the file once you download it, and run the program inside to install the drivers)(Updated 09.27.10)
Motorola Droid Drivers (unzip the file once you download it).
Motorola Milestone Drivers (follow the instructions on the page).
Motorola CLIQ Drivers (follow the instructions on the page).
Samsung Behold 2 Drivers (unzip the file, run the setup.exe) (If you have Windows 64Bit, you CANNOT install the Behold Drivers. Find someone with a 32Bit system to to any Behold 2 procedures involving ADB).
Samsung Galaxy Drivers (unzip the file, do NOT run setup.exe. Instead follow step 1 in Section II and install manually.)
If using a Samsung device, try downloading Samsung Kies and installing that then plugging in your device and trying again.
V. Some Common ADB/Fastboot Commands
ADB Commands
adb devices – lists which devices are currently attached to your computer
adb install <packagename.apk> – lets you install an Android application on your phone
adb remount – Remounts your system in write mode – this lets you alter system files on your phone using ADB
adb push <localfile> <location on your phone> – lets you upload files to your phones filesystem
adb pull <location on your phone> <localfile> – lets you download files off your phones filesystem
adb logcat – starts dumping debugging information from your handset to the console – useful for debugging your apps
adb shell <command> – drops you into a basic linux command shell on your phone with no parameters, or lets you run commands directly
adb devices – lists which devices are currently attached to your computer
adb install <packagename.apk> – lets you install an Android application on your phone
adb remount – Remounts your system in write mode – this lets you alter system files on your phone using ADB
adb push <localfile> <location on your phone> – lets you upload files to your phones filesystem
adb pull <location on your phone> <localfile> – lets you download files off your phones filesystem
adb logcat – starts dumping debugging information from your handset to the console – useful for debugging your apps
adb shell <command> – drops you into a basic linux command shell on your phone with no parameters, or lets you run commands directly
Fastboot Commands
fastboot devices – lists which devices in fastboot mode are currently attached to your computer
fastboot boot <filename> – boots a rom stored on your pc specified by the filename
fastboot flash <partition> <filename> – flashes a rom stored on your pc, partition can be one of 
{boot, recovery, system, userdata}

For farther information you can visit Android Debug Bridge.

Tuesday, July 03, 2012

Using Placeholder or parameter markers for preventing sql injection in PHP


public static function getMembers($startRow,$numRows,$order){
$sql = “SELECT SQL_CALC_FOUND_ROWS * FROM “ . TBL_MEMBERS . “ ORDER BY $order LIMIT :startRow, :numRows”;
}

Here in the above statement SQL_CALC_FOUND_ROWS is a special MySQL keyword that computes the total number of rows that would be returned by query , assuming  the LIMIT clause wasn't applied. So if the query would return 20 records, but the LIMIT clause limits the returned rows five, SQL_CAL_FOUND_ROWS return a value of 20. This is useful because it enables you to display the records several pages, as you see in a moment.

:startRow and :numRows are called placeholders or parameter markers.
They serve two purposes.
First of all, they let you prepare — that is, get MySQL to parse — a query once, then run it multiple
times with different values. If you need to run the same query many times using different input
values -- when inserting many rows of data, for instance -- prepared statement can really speed up execution.
Secondly, they reduce the risk of so-called SQL injection attacks. For example, an alternative to using
placeholders might be to write:


$sql = “SELECT SQL_CALC_FOUND_ROWS * FROM “ . TBL_MEMBERS . “ ORDER BY $order LIMIT $startRow, $numRows”;


However, imagine that, due to insufficient checking of user input, a malicious user managed to set
$numRows to “1; DELETE FROM members”.

This would run the query as intended, but it would also run the second statement, which would delete all records from your members table!

When you use placeholders, you pass data to the query via PDO (as you see shortly), not directly into
your query string. This allows PDO to check the passed data to ensure that it only contains what it’s supposed to contain(integers in this case).


Next, the two :startRow and :numRow placeholders you created earlier are populated with the actual data from the $startRow and $numRow variables:

$st->bindValue( “:startRow”, $startRow, PDO::PARAM_INT );
$st->bindValue( “:numRows”, $numRows, PDO::PARAM_INT );

The PDOStatement::bindValue() method takes three arguments:

the name of the placeholder to bind,
the value to use instead of the placeholder,
and the data type of the value (PDO::PARAM_INT, or integer, in this case).

By specifying the data type, PDO can ensure that the correct type of data is passed to MySQL. In addition, PDO automatically escapes any quote marks and other special characters in the data.(Failing to escape special characters is another common cause of SQL injection vulnerabilities.)

Some other common data types that you can use include:

PDO::PARAM_BOOL — A Boolean data type
PDO::PARAM_NULL — The NULL data type
PDO::PARAM_STR — A string data type. (This is the default if you don’t specify a type.)
PDO::PARAM_LOB — A LOB data type, such as BLOB or LONGBLOB

Why use LIKE instate of using loop in PHP ?


We know LIMIT counts from the first row of the results. However, by including two numbers after the
LIMIT keyword, separated by a comma, you can specify both the row from which to start returning
results, as well as the number of results to return:

mysql> SELECT id, username FROM members LIMIT 1, 2;

| id | username |
-------------------
 2    ron
 3    anjan

Notice that the start row counts from zero, so 1 is actually the second row (ron).

You might be wondering what the point of LIMIT is, because you can always just loop through the result set in PHP to extract only the rows you’re interested in. The main reason to use LIMIT is that it reduces the amount of data that has to flow between MySQL and your PHP script.

Imagine that you want to retrieve the first 100 rows of a million-row table of users. If you use LIMIT
100, only 100 rows are sent to your PHP script. However, if you don’t use a LIMIT clause (and your
query also contains no WHERE clause), all 1,000,000 rows of data will be sent to your PHP script, where they will need to be stored inside a PDOStatement object until you loop through them to extract the first 100. Storing the details of a million users in your script will quickly bring the script to a halt, due to the large amount of memory required to do so.
LIMIT is particularly useful when you’re building a paged search function in your PHP application. For example, if the user requests the second page of search results, and you display 10 results per page, you can use SELECT ... LIMIT 10, 10 to retrieve the second page of results.

Some Important Attributes in Mysql

There have some most important attributes in mysql which can solve/get the solution of our faced scenery. So, we should keep in mind that those we can do by using default attribute of mysql.


BINARY Attribute

All character data types have a collation that is used to determine how characters in the field are
compared. By default, a character field’s collation is case insensitive. This means that, when you sort the column alphabetically (which you learn to do shortly), “a” comes before both “b” and “B”. It also means that queries looking for the text “banana” will match the field values “banana” and “Banana”.

However, by adding the BINARY attribute after the data type definition, you switch the field to a binary collation, which is case sensitive; when sorting, “a” comes before “b”, but “B” comes before “a” (because, generally speaking, uppercase letters come before lowercase letters in a character set). Furthermore, this means that matches are case sensitive too; “banana” will only match “banana”, not “Banana”. In this case, you created the username field of the members table with the BINARY attribute, making it case sensitive:

username VARCHAR(30) BINARY NOT NULL UNIQUE,

This ensures that there’s no ambiguity over the case of the letters in each user ’s username; for example,
“shaon” is a different username than “Shaon”. This is important because many people choose usernames where the case of the username’s characters is significant to them. If they created their account with a username of “shaon”, and later found out they could also login using “Shaon”, they might wonder if they were working with one account or two!

ENUM Data Type

Enumeration columns is a  type of string column where only predefined string values are allowed in the field .
Suppose we want user can input only 'm' or 'f' for their gender then we have to use:

gender ENUM ('m', 'f'),

or their favorite subject to read:

subject ENUM( 'JAVA','PHP','CEH'),


TIMESTAMP Data Type

Another most important data type is TIMESTAMP data type which can get the result exactly what you need. It is a bit different from the other date/time types in that it can automatically record the time that certain event occur. For example, when you add a new row to a table containing a TIMESTAMP column, the field stores the time that the insertion took place. Similarly, whenever a row is updated, the TIMESTAMP field is automatically updated with the time of the update.

The other point to remember about TIMESTAMP fields is that they store the date and time in the UTC
(Universal Coordinated Time) time zone, which is essentially the same as the GMT time zone. This
probably won’t affect you much, because MySQL automatically converts TIMESTAMP values between UTC and your server ’s time zone as required. However, bear in mind that if you store a TIMESTAMP value in a table, and you later change the server ’s time zone, the value that you get back from the TIMESTAMP field will be different.

A TIMESTAMP field is great for tracking things such as when a record was last created or updated,
because you don’t have to worry about setting or changing its value; it happens automatically. In this
example, you created a TIMESTAMP field in the accessLog table to track when the last access was made:

lastAccess TIMESTAMP NOT NULL,


Saturday, June 16, 2012

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

I have faced this problem when I have exported my work-space from Windows 7 x64 jvm7 x64 and Imported that project in eclipse on my Ubuntu 12.04.

ERROR:  " Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties"

Solution of this problem is to set project compatibility to java 5.0 to java6.0.
You can do that in two way:

1. right-click on your project and select "Android-Tools -> Fix Project Properties " [If this solution doesn't work then apply second options ]

2. right-click on your project and select "Properties->Java Compiler " , Check "Enable project specific settings " and select 1.5 or 1.6 from "Compiler compliance settings" select box.

My problem solved by following the first options. Hope you will get your solution from here.



Sunday, May 27, 2012

INSTALL_FAILED_INSUFFICIENT_STORAGE error solution



This error you will get from the "logcat" of eclipse. The main reason of this error is the storage of emulator. So, if there have shortage of space in emulator you will get this error. 


To solve this problem you have to increase the storage of emulator. So, here the way to do that.


1.  Right click the root of your Android Project, go to "Run As" then go to "Run Configurations..." locate the "Android Application" node in the tree at the left, then select your project and go to the "Target" tab on the right side of the window look down for the "Additional Emulator Command Line Options" field (sometimes you'll need to make the window larger) and finally paste "-partition-size 1024" there. Click Apply and then Run to use your emulator.


2. Go to Eclipse's Preferences, then Select “Launch” Add “-partition-size 1024” on the “Default emulator option” field, then click “Apply” and use your emulator as usual.


3. Emulator -avd "Emulator Name" -partition-size 500


4. You can also free up memory by removing unwanted apps go to settings->application->manageapplication then uninstall the apps which is useless.


5.  Also you can resolve by having android:installLocation="preferExternal" for <manifest> tag of manifest file.


Saturday, May 26, 2012

Camera Intent In Android

In android there have several application where you need to work with Camera Intent. There have two ways to complete your task :

1. Use the default camera intent to your application  or
2. Customize your own camera intent .

I have worked with android default camera where capture the Image of user and sent that picture to the server and detect the mood from the image of user. After sending image to the server I need to delete the Image from the Phone Memory. Otherwise, application would take the maximum storage of phone memory and that Image is not necessary for the Users.

So lets start coding. Here is the cameraActivity.java which will do the task.


public class cameraActivity extends MainActivity{

private static final int CAMERA_REQUEST_CODE = 100;
boolean _taken;

public void startCameraActivity() {

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult( cameraIntent , CAMERA_REQUEST_CODE);

}//end of startCameraActivity()

/**
* onActivityResult for capturing image
* reqestCode is the CAMERA_REQUEST_CODE
* resultCode is the result of camera
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if(requestCode == CAMERA_REQUEST_CODE) {
if(resultCode == RESULT_OK) {

onPhotoTaken(intent);

}else {

Toast.makeText(getApplicationContext(), "Camera request rejected!", Toast.LENGTH_LONG).show();

      }//end of if else condition
}//end of if condition
   
}//end of onActivityResult


/**
 * In this method what will do after capturing image
 * @param i is the image sending from camera intent
 */
public void onPhotoTaken(Intent i) {

_taken = true;
serverActivity server = new serverActivity();

Bitmap bitmap = (Bitmap) i.getExtras().get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 0, bos);
byte[] imageData = bos.toByteArray();
server.insertImageIntoServer(imageData); //passing image to save image into server

}//end of onPhotoTaken()

/**
* Last Image will be delete from the Image Gallery after Sending Image to the Server
*/
   public void deleteLastImageFromGallery() {
   
    int i=0;    
    String[] projection = {MediaStore.Images.Media.DATA};
       Cursor cursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
     
       ArrayList<String> imagePath = new ArrayList<String>();
     
       while(cursor.moveToNext()) {
     
        imagePath.add(cursor.getString(0));
        i++;
       
       }//end of while loop
     
       cursor.close();
       i--;
     
       File file = new File(imagePath.get(i));
       file.delete();
       Toast.makeText(getApplicationContext(), "Last image has been deleted!", Toast.LENGTH_LONG).show();
       
   }//end of deleteLastImageFromGallery()

}//end of main class


I hope you have got the point how it is working. Let start to code yourself after getting the main theme of using camera intent . In coding time you will face different problem after that you will learn. If you won't  face any bugs/errors then you will not be able to learn because after solving bugs we will learn to solve bugs. And I think this is the best way to learn by solving errors.

This below link will help you to learn in depth of camera intent :
Camera Intent Android Developer

Android and mySql Interaction

Recently I am working on interacting android with Mysql where I have to save every message of user into the mysql server form android.
So I need to connect mySql database with android activity. Though it is so easy to establish connection with mysql. But for the first time it will take time for the novice programmer.
Because of time saving I am here writing the method how to connect mysql and android perfectly and in proper way.
Remember I am just trying to inform you the method how to do it. I am not writing all the code.Sorry for the code formatting it is the problem of writing in blog that is doesn't if you get your solution.

You have sent message any simple message from edittext field from main activity to this class
// serverActivity.java

public class serverActivity extends MainActivity{

static InputStream inputStream;
static ArrayList<NameValuePair> nameValuePairs;
/**
* Sent message to the server
* @param msg
*/
public static void insertMsgIntoServer(String msg) {

try {
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UserMessage", msg)); //Passing user message with Index Value "UserMessage"

httpClient.httpConnection(nameValuePairs,inputStream);    //Calling httpConnection passing arrayList and InputStream
Log.d("<<<-Inside insertMsgToServer->>>", "Success in saving msg into server");

}catch(Exception ex) {
Log.d("<<<-Inside insertMsgToServer->>>", "Error in saving msg into server");
}//end of exception handling
}//end of insertMsg()
}//end of main class

httpClient.java here you have to sent the nameValuePair arrayList and inputStream for sending data into the mysql.

//httpClient.java

public class httpClient {
/**
* @param nameValuePairs passing arraylist with all information added
* @param inputStream passing inputStream from user request
*/
public static void httpConnection(ArrayList<NameValuePair> nameValuePairs,java.io.InputStream inputStream){
try{
HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost("http://10.0.2.2/android/msg.php");  
//when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computeres loopback interface. From the emulators perspective, localhost (127.0.0.1) refers to its own loopback interface.So localhost or 127.0.0.1 will not work here.

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //Passing nameValuePairs ArrayList to the server


HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
Log.d("<<<-http_log_tag->>>","Succes in Http Connection");

}catch(Exception e){

Log.e("<<<-http_log_tag->>>","Error in Http Connection" + e.toString());

}//end of exception handling

}//end of httpConnection()

}//end of main class

So here is the end of android portion. Now you have to get this message from "http://10.0.2.2/android/msg.php" . So here is the code how will do that to insert the message into your mysql database.

//msg.php
<?php
$ms=$_REQUEST["UserMessage"];

mysql_connect("localhost","root","");
mysql_select_db("android");

$query = mysql_query("insert into msg (message)values('$ms')");

if($query>0){
echo "Data Inserted Seccesfully";
}else{
echo "Error Occured.";
        }
?>

If you have done all the things above then start your xampp server then run your AVD emulator. After writing any message in edittext box  and pressing the button to chat that will execute event which will sent message to the serverActivity.java class. After processing here message will sent to perform the activity of httpClient which will connect with the server and execute the msg.php . Server will insert your message to your database. Check your database you will get your message into database.

Thanks everyone. If have any problem just comment your problem hope you will get your solution as soon as possible.
Happy Coding.

Friday, May 25, 2012

Top Ten Errors Java Programmers Make

I read an article on “Top Ten Errors Java Programmers Make“. The author has mentioned the errors which even the most programmers often commit or the New to Java programmers may commit in the future. Not only has he listed the errors but also given the possible solution for the same. I found the article really informative.

By David Reilly

Whether you program regularly in Java, and know it like the back of your hand, or whether you're new to the language or a casual programmer, you'll make mistakes. It's natural, it's human, and guess what? You'll more than likely make the same mistakes that others do, over and over again. Here's my top ten list of errors that we all seem to make at one time or another,  how to spot them, and how to fix them.

10. Accessing non-static member variables from static methods (such as main)

Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don't need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-
MyApplication.main ( command_line_args );
This means, however, that there isn't an instance of MyApplication - it doesn't have any member variables to access! Take for example the following application, which will generate a compiler error message.
public class StaticDemo
{
        public String my_member_variable = "somedata";
        public static void main (String args[])
        {
  // Access a non-static member from static method
                System.out.println ("This generates a compiler error" +
   my_member_variable );
        }
}
If you want to access its member variables from a non-static method (like main), you must create an instance of the object. Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.
public class NonStaticDemo
{
        public String my_member_variable = "somedata";

        public static void main (String args[])
        {
                NonStaticDemo demo = new NonStaticDemo();

  // Access member variable of demo
                System.out.println ("This WON'T generate an error" +
                        demo.my_member_variable );
        }
}

9. Mistyping the name of a method when overriding

Overriding allows programmers to replace a method's implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you'll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.
public class MyWindowListener extends WindowAdapter {
 // This should be WindowClosed
 public void WindowClose(WindowEvent e) {
  // Exit when user closes window
  System.exit(0);
 }
});
Compilers won't pick up on this one, and the problem can be quite frustrating to detect. In the past, I've looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn't being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn't being called, then it's likely you've mistyped the name.

8. Comparison assignment (  = rather than == )

This is an easy error to make. If you're used other languages before, such as Pascal, you'll realize just how poor a choice this was by the language's designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.
Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.
Here's the correct way to compare two strings.
String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
{
    ......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
   .....
}

6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.
When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.
When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type.  So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.
On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

5. Writing blank exception handlers

I know it's very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven't written any error messages, it becomes almost impossible to find out the cause of the error. Even the simplest exception handler can be of benefit. For example, put a try { .. } catch Exception around your code, to catch ANY type of exception, and print out the message. You don't need to write a custom handler for every exception (though this is still good programming practice). Don't ever leave it blank, or you won't know what's happening.
For example
public static void main(String args[])
{
    try {
 // Your code goes here..
    }
    catch (Exception e)
    {
 System.out.println ("Err - " + e );
    }
}

4. Forgetting that Java is zero-indexed

If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0. Confused? Let's look at a quick example.
// Create an array of three strings
String[] strArray = new String[3];

// First element's index is actually 0
strArray[0] = "First string";

// Second element's index is actually 1
strArray[1] = "Second string";

// Final element's index is actually 2
strArray[2] = "Third and final string";
In this example, we have an array of three strings, but to access elements of the array we actually subtract one. Now, if we were to try and access strArray[3], we'd be accessing the fourth element. This will case an ArrayOutOfBoundsException to be thrown - the most obvious sign of forgetting the zero-indexing rule.
Other areas where zero-indexing can get you into trouble is with strings. Suppose you wanted to get a character at a particular offset within a string. Using the String.charAt(int) function you can look this information up - but under Java, the String class is also zero-indexed. That means than the first character is at offset 0, and second at offset 1. You can run into some very frustrating problems unless you are aware of this - particularly if you write applications with heavy string processing. You can be working on the wrong character, and also throw exceptions at run-time. Just like the ArrayOutOfBoundsException, there is a string equivalent. Accessing beyond the bounds of a String will cause a StringIndexOutOfBoundsException to be thrown, as demonstrated by this example.
public class StrDemo
{
 public static void main (String args[])
 {
        String abc = "abc";

        System.out.println ("Char at offset 0 : " + abc.charAt(0) );
        System.out.println ("Char at offset 1 : " + abc.charAt(1) );
        System.out.println ("Char at offset 2 : " + abc.charAt(2) );

 // This line should throw a StringIndexOutOfBoundsException
        System.out.println ("Char at offset 3 : " + abc.charAt(3) );
 }
}
Note too, that zero-indexing doesn't just apply to arrays, or to Strings. Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application.
import java.util.Date;
import java.util.Calendar;

public class ZeroIndexedDate
{
        public static void main (String args[])
        {
                // Get today's date
                Date today = new Date();
 
  // Print return value of getMonth
  System.out.println ("Date.getMonth() returns : " +
    today.getMonth());

  // Get today's date using a Calendar
  Calendar rightNow = Calendar.getInstance();

  // Print return value of get ( Calendar.MONTH )
  System.out.println ("Calendar.get (month) returns : " +
   rightNow.get ( Calendar.MONTH ));
        }
}
Zero-indexing is only a problem if you don't realize that its occurring. If you think you're running into a problem, always consult your API documentation.

3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.
Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.
How can this problem be solved? The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.
public class MyCounter
{
 private int count = 0; // count starts at zero

 public synchronized void setCount(int amount)
 { 
  count = amount;
 }
 
 public synchronized int getCount()
 {
  return count;
 }
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don't spot the lack of capitalization.
While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-
  • all methods and member variables in the Java API begin with lowercase letters
  • all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()
If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you'll make. It may take a while, but it can save some serious head scratching in the future.

(drum roll)

And the number one error that Java programmers make !!!!!


1. Null pointers!

Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.
When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.
Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!
Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.
public static void main(String args[])
{
 // Accept up to 3 parameters
 String[] list = new String[3];

 int index = 0;

 while ( (index < args.length) && ( index < 3 ) )
 {
  list[index++] = args[index];
 }

 // Check all the parameters 
 for (int i = 0; i < list.length; i++)
 {
  if (list[i].equals "-help")
  {
   // .........
  }
  else
  if (list[i].equals "-cp")
  {
   // .........
  }
  // else .....
 } 
}
This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Summary

These errors represent but some of the many that we all make. Though it is impossible to completely eliminate errors from the coding process, with care and practice you can avoid repeating the same ones. Rest assured, however, that all Java programmers encounter the same sorts of problems. It's comforting to know, that while you work late into the night tracking down an error, someone, somewhere, sometime, will make the same mistake!

Thanks to David Reilly

Thursday, May 03, 2012

Decision Learning Tree Problem


Problem :



     Mr. Apple is a CSE student who listens to music almost everywhere he goes. He often has homework due for his modules and many of them involve programming. We have sampled his choice of music genre over several points in time.

    Using information gain, compute the decision tree for the following observations of Apple. Show all work. The following mathematical formulas may be useful for your computation.




TimeOfDay
HomeworkDue
Programming
Music Type?
Morning
Yes
No
Classical
Morning
No
No
Pop
Morning
No
Yes
Classical
Morning
Yes
No
Classical
Afternoon
Yes
Yes
Pop
Afternoon
No
No
Pop
Evening
No
Yes
Pop
Evening
Yes
Yes
Classical