Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Android Studio in Ubuntu Linux ? Why not ?

Recently, I tried to replace the Eclipse Android Development Environment in my computers with the Android Studio Developed by Google. But, unfortunately ended up getting so many errors on Linux Ubuntu.

After some digging on the internet and many failed attempts to change permissions in directories of the Operating System, I finally managed to get things working and thought that I could write this down in the Notes, So, that in the  future there won't be any inconveniences. 




First I downloaded Android Studio from the official developer Web Site here.


After downloading the .zip file. I extracted the whole thing By Just Right Click-> Extract Here.

Inside the Extracted android-studio/bin Directory there's 'studio.sh' which is the 'Self Extracting Archive' is the file to be executed, to do that I just launched my terminal. (Ctrl + T)


$ cd Downloads/android-studio/bin
$ ./studio.h



It took a quite a bit of time and ended up, showing an error for the versions. That was completely annoying and it kept coming. 

So, initially, what I thought was that It could be a problem with the Java versions and I tried to understand which version of it that had at the moment.


$ java -version
$ dpkg --list | grep -i jdk


It showed me that I had OpenJDK 6. So, I decided to Update the Java Version. 

$ sudo apt-get update   
[ To Download the package lists from repositories. ]
$ sudo add-apt-repository ppa:webupd8team/java 
[ Add the Repositories if it doesn't exist ]
$ sudo apt-get update && sudo apt-get install oracle-jdk7-installer
$ update-alternatives --display java

At the end of this line, I had to opt the Required version and I typed #3 which was the required OpenJDK1.7.0. And I tried running the './studio.h' again and guess what I ended with the, Error message saying "tools.jar is not in android studio class path Please ensure JAVA_HOME points to JDK rather than JRE". 

As usual when it comes to settings related to default paths, what comes to our mind usually is, '.bashrc'. So I ran the following commands.

$ cd ~
$ vi .bashrc


I added the following lines at the end of the '.bashrc' having typed the comments for future references. Comments are shown after '#' in shell scripting.


# comment : the .bashrc is eddited to add java_home by Harsha
JAVA_HOME="/usr/lib/jvm/java-7-openjdk-i386"
export JAVA_HOME
PATH=$PATH:$JAVA_HOME

I Saved the file, and ran, 


$ source ~/.bashrc
$ echo $JAVA_HOME



Above is to test that it echoes the Java path. Then , I tried run the '/studio.h'. Still I kept getting the Error "tools.jar is not in  android studio class path Please ensure JAVA_HOME points to JDK rather than JRE". 

After digging the Internet for around 10 minutes, I found out the way of doing this. So, Here's the whole thing. Exporting the JDK path in the '~/.bashrc' won't give us the right answer. So do the following.


$ sudo apt-get install openjdk-7-jdk  [ If you don't have it ]
$ sudo vi /etc/environment



Add the line. 

JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-i386 


Save & Close. You probably would require a reboot of the System. After the Reboot is made, run the '/.studio.h' and you'd love using Android Studio which is a better application by the way.



Thank You.

Adding Look and Feel for Swing Based UI ?

After quite a while, I thought of writing a Blog post based on Java Swing Development and I thought of writing something cool as well as simple. Improving Look and Feel in a Java Swing based UI could be a simple but necessary thing because it could improve the quality of your application inside and out. 

In order to do this, the best thing to do is to download and add Java Synthetica Addons, because they're easy to apply on the current working project of yours. But, there's this little problem of Synthetica Addon is not to be distributed for free.

But, there's a good news and a bad news. The good news is that there's a lot of Free download links to download these Synthetica Jar Archives, yet the bad news is that they're older and most often doesn't work with the newer versions of java.

Then, how to download the newest cool improved version of Synthetica Addons and often at the same time make them not to show Watermarks like they usually do. Let's explore the Clear step wise explanation of Adding New Synthetica to the Java Swing UI.

I'm using Net beans as my Integrated Development Environment in order to perform this task. No matter what you use as your IDE, you can follow the steps as follows.

Step 01

First, create a new Project as of 'Some Name'. In my case, it's UI.


Step 02

Add a JFrame of your Liking and write the following Piece of Code inside the main static method of the 'Project Name'.java's 'Project Name' class.

            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                LookAndFeel look;
                try
                {
                    look = new SyntheticaStandardLookAndFeel();
                    UIManager.setLookAndFeel(look); //calls setLookAndFeel static method
                    new First().setVisible(true); // First is the JFrame that I've created
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                
            }});


I'd like to explain few of the Self evident factors regarding this piece of code that I've given above. The Frame contains an UI thread, but the invokelater method of the EventQueue Class of the Java abstract window toolkit (awt)  package updates the Frame's UI thread. Runnable is an Interface which includes a run method, but the declaration and implementation of the run() method, the run method of the original interface is overridden. Inside it, an object of the LookandFeel class of swing package is stored with an instance of the SyntheticaStandardLookAndFeel class. In the next line, a Static method has been called without creating an object from UIManager Class as  creating objects is unnecessary when it comes to calling static methods. Surrounding, it with a TryCatch is important as there should be a way of Catching Exceptions.



Step 03

In order to avoid the references problems you've to download, the Synthetica Packages from the jyloo.You can then unzip the Downloaded Zip file & then try to add the Jars as libraries into the Project by right clicking in the Project Explorers Library Folder and add Jar Option. You've add Synthetica.jar.


Step 04



When running the Project, it seems that the Synthetica has been applied with the Water Mark stating that 'Synthetica' is an "Unregistered Evaluation Copy". Then, the problem is how to remove this watermark. I've included the steps of doing that.

Step 05

Download and unzip the 'rej' which enables us to edit the Synthetica.jar and make the Synthetica Unregistered Evaluation Copy Message Disappear. Then, run rej.jar by double clicking it. Open the Synthetica.jar inside the Project folder.


Then, Select the 'de/javasoft/plaf/synthetica'.



Then, select 'SyntheticaRootPaneUI.class' and double click it and open it.



Step 06

Then press Ctrl+F to find the Method 'isEvalCopy' method.


After finding the relevant Method as shown in the Image itself, right click on 'iconst_1 1' and click insert after. Then in the coming dialog box choose 'iconst_0 0'. 



Now, remove 'iconst_1 1' and save the changes made to .jar.





Step 07

Finally, take the search tab and Search for the term 'invalid' by typing it in the search bar.



Pick the 4th From the Top Search result which is 'Instruction : de.javasoft.plaf.synthetica.SyntheticaLookAndFeel$1.showDialog .....' , and double click on it.


Step 08

You'll find the showDialog() method and remove the whole content inside it, but make sure that the method has only 'return' statement in it.


That's all. Now, you can rebuild the Project and Run it. You'll find the Synthetica applied to the Swing application without 'The Water mark'. That's something.

Image Upload & Display : Java/ MySQL ?

This was an interesting topic for most of the people including myself, during the times when, there was a desperation finding code to perform the very action, 'Upload & Display' images with the Java application.

I thought to note it down, so that somebody else won't necessarily have to be desperate anymore reading a zillion articles and websites.

01. In order to this, first create a simple database.

use test;

create table img_Upload(
 nic varchar(10) not null,
        image BLOB,
        constraint pk_img_Upload primary key(nic)
);

Important: There are 2 ways to store images of your application. One is storing the file path & the other, storing image as a blob. I prefer blob here. Because, I've got less number of images & blob helps not to worry about moving the application around without caring about file paths.

02. Now, You can start creating your Java application using any IDE or manual coding. But, you've to include Database Connection class no matter what.

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

public class Connect {

    Connection con = null;
    String sourceURL = null;

    public Connect(){

        try {
            Class.forName("com.mysql.jdbc.Driver");
            sourceURL = "jdbc:mysql://localhost:3306/test";

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection connect(){

        try {
            con = DriverManager.getConnection(sourceURL,"user","mepassword"); // your user name password 

        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    public void close(Connection con){

        if(con!=null){

            try {
                con.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

03. Then, create a jFrame with a 2 labels, button and a text box. (Add extra jFrame to display image from db)


       03.1. Write jLabel mouse clicked event to display JFileChooser & select the image, so that the selected image will be shown in the jLabel.


    private void jlbl_imageMouseClicked(java.awt.event.MouseEvent evt) {


        JFileChooser ch = new JFileChooser();
        ch.showOpenDialog(null);
        try {
            f1 = ch.getSelectedFile(); // create f1 as: static File f1 class variable so that it's accessible in other private methods
            try {
                Image img = ImageIO.read(f1);
                Image newimg = img.getScaledInstance(jlbl_image.getWidth(),jlbl_image.getHeight(), java.awt.Image.SCALE_SMOOTH);
                ImageIcon ik = new ImageIcon(newimg);
                jlbl_image.setIcon(ik);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        
    }

    03.2.  Write button action performed event like follows.

   
private void jbtn_submitActionPerformed(java.awt.event.ActionEvent evt) {

        Connection con = null;
        Connect dbConn = new Connect();
        try {
            con = dbConn.connect();
            FileInputStream fis = null;
            PreparedStatement ps = null;
            con.setAutoCommit(false);
            fis = new FileInputStream(f1);
            ps = (PreparedStatement) con.prepareStatement("insert into img_Upload values(?,?)");
            ps.setString(1,jtxt_usernic.getText().toString());
            ps.setBinaryStream(2,fis,f1.length());
            int stat = ps.executeUpdate();
            con.commit();
            if(stat==1){
                Display(jtxt_usernic.getText().toString()); // this displays image from db
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Hope you've got everything alright. Test run the project. Here's a screen shot of my own output.



Thanks for coming. Have Your Comments.

Database Connectivity with Java ?

For those who already know a database connectivity in Java, this post will be boring. But, for people who're yet to know, this will be resourceful and simple to understand.

I use Netbeans as my IDE, So that, I just have to think about, all important coding part.

1 . First, take a new project in Netbeans & create a new Java Frame.


2.  Go to Pallet & Take a button from Swing Controls.



3.  Then, create an event for the Button & write the following code in the event.




 
try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname","username","password");
            JOptionPane.showMessageDialog(null,"Succesfully Connected !");
            
        } catch (Exception e) {
            System.out.println(e);
        } 
      

In this example, if your connection is successful a java swing 'JOptionPane' message dialog will be shown. 

But, connecting to a database inside a click event (private method) is unacceptable.Because , the database connectivity will be required in multiple occasions in a program. So, we can create a separate class for this & call it, whenever we need it, using object oriented concepts.

Here's a class for database connectivity.



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

public class Connect{

 public Connection connect(){

            Connection con = null;
  try
  {
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdbname","username","password");
  } catch(Exception ex){
   ex.printStackTrace();
  }
  return con;
 }

 public void conClose(Connection c){

  try{
   c.close();
  }catch(Exception ex){
   ex.printStackTrace();
  }
 }
}

Here's an example of dynamically calling the connect() & conClose() methods of the Connect class that we've finished writing.

Before the java code make sure you execute following MYSQL script to create database & table.

create database yourdbname;

use yourdbname;

create table test_table(
 name varchar(50) not null
);

insert into test_table values('Harsha Wansooriya');

You have to add a swing text field 'jtxt_test' to your Frame. Then add the following method to the Frame Class & call inside the constructor so that it'd execute.

    public void load_name(){

        Connection con = null;

        try {
            con = new Connect().connect();
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT name from yourdbname.test_table WHERE name LIKE 'Harsha Wansooriya'");

            while(rs.next())
            {
                String name = rs.getString(1);
                jtxt_test.setText(name);
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Enjoy ! Create Things & Test !

Parametrized IReport in Your Java Project ?

This is a very important post I've to make during this series about IReports which is to enlighten somebody who reads this to add Parametrized IReport into the Java Project.

The whole post in steps which will surely be comforting to most of the readers, so that it'll be easy to follow this.

1. First, Step is to finalize your IReport. Hope You've got your IReport Application Opened. Then, click on the Parameter You've defined on the Report Inspector. 





 2. Go to Properties window at the right bottom of your application window.








3. Make sure, you tick off 'Use as a prompt'. Compile the IReport & Close IReport Application.

4. Then, open up your Java Project Create a Package as repObj (any name) .



5. Store your IReport files & import *.jasper & image files relating to your IReport in to the package.






6. Create another package 'report' & make a java class as ReportView & copy the following code inside it.


package report;

import DBConnect.Connect;
import java.awt.Container;
import java.sql.Connection;
import java.util.HashMap;
import javax.swing.*;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.swing.JRViewer;

public class ReportView extends JFrame
{
    public ReportView(String fileName)
    {
        this(fileName, null);
    }
    public ReportView(String fileName, HashMap para)
    {
        super("Set Your Application name in the Super Class");

        Connect dba = new Connect();
        Connection con = dba.connect();

        try
        {
            JasperPrint print = JasperFillManager.fillReport(fileName, para, con);
            JRViewer viewer = new JRViewer(print);
            Container c = getContentPane();
            c.add(viewer);            
        } 
        catch (Exception Exception)
        {
            System.out.println("ERRORS IN JASPER REPORT "+Exception);
        }
        setBounds(10, 10, 900, 700);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
}



7. Now, create a button in the frame to fire up your IReport & a text box to pass the parameters.

8. Go inside the Button & copy the following Code.

        HashMap para = new HashMap();
        para.put("Order_No",jtxt_Order_No.getText());
        ReportView rv = new ReportView("..\\iControl\\src\\repObj\\Order.jasper",para);
        rv.setVisible(true);




 You may need to import HashMap class & report.ReportView class( you've created) in your frame *.java file. 

As parameter of put method you've to pass IReport Parameter Name & Text Box Value. ReportView Parametrized Constructor should be given Relative *.jasper path Passed, make sure you do that.

9. Now, you've to import the IReport Libraries in to the Java Project.







Import the  IReport Libraries in the Image below. You can find them in your IReport Installation. In default they'll be "C:\Program Files\Jaspersoft\iReport-4.5.1\ireport\modules\ext".




10. Now, run your file. Type a value into the Text box & Check whether it's working. Most probably it would.


Enjoy !

Remove Unnecessary Events in NetBeans IDE ?

Hi!

I thought to write this post & the rest of the post associated with the Cloud tag 'Net Beans' to avoid getting so many phone calls during the day for simple problems that occur when using Netbeans IDE, our most reliable Java IDE. (integrated development environment)

So, from now on with my posts I hope to give solutions for simple problems, that will sure be helpful to you.

 To begin with I picked 'Removing Unnecessary Events with NetBeans IDE ?

You'll sometimes experience when dragging a java swing button, text box or Etc you'll get events that you'll have by accidentally double clicking on the particular item & your code is filled with unnecessary events that you don't need to have.

You'll be seeing events like following when you right click and go to events.


Please follow the steps given below.

1. Right Click on the Button & go to Properties.


 2. You'll be seeing Property Window and Click Events Tab.



3. Then, you'll see the event list. Pick your event that you need to remove by clicking on the button besides the drop down. ('...' as the value)






Now, you remove the event from the menu by clicking Remove Button.




4. Then, click ok & you'll see, that you've already got rid of the unwanted event.


Enjoy !

MySQL database backup/restore with Java Program ?



Hi!

This article is about creating a java program to backup/restore a MySQL database. The article is in two basic parts, namely Backup  & Restore.

1. Backup - Basically, the MYSQL command to backup database looks like follows.

mysqldump -u [username] -p[password] -B [dbname] -r [MYSQL file Path]

The following Code is for the java program.


public class Main{


 public void restoreDB(String path){

    String executeCmd = "C:/xampp/mysql/bin/mysqldump -u xyz -pxxyyzz -B myDB -r " + path;

    System.out.println(executeCmd);

    Process runtimeProcess;

    try
    {
       runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });

       int processComplete = runtimeProcess.waitFor();

       System.out.println(processComplete);

       if(processComplete == 0)
       {
          System.out.println("Backup Created Successfully !");
       }
       else
       {
          System.out.println("Couldn't Create the backup !");
       }
    }
    catch(Exception ex)
    {
       ex.printStackTrace();
    }

   }

      public static void main(String[]args){

         new Main().restoreDB("C:/File.sql");
      }

}


2. Restore - Basically, the MYSQL command to restore database looks like follows.

mysql -u [username] -p[password] [databasename]<[MYSQL file Path]


In the query,

-u [username]    - is where you should type your username to access databases.

-p[password]      - is where you should type your password to the databases.

Then, you should type the name of the database which you need to backup tables to.

mysql -u xyz -pxxyyzz myDatabase<C:/file.sql

Then,Here's a java code to test run this MYSQL command.

public class Main{


 public void restoreDB(String path){

  String executeCmd = "C:/xampp/mysql/bin/mysql -u xyz -pxxyyzz myDB <" + path;

  System.out.println(executeCmd);

  Process runtimeProcess;

  try
  {
   runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });

   int processComplete = runtimeProcess.waitFor();

   System.out.println(processComplete);

   if(processComplete == 0)
   {
    System.out.println("Restored the Backup !");
   }
   else
   {
    System.out.println("Couldn't Restore the backup !");
   }
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
  }

 }

 public static void main(String[]args){

  new Main().restoreDB("C:/File.sql");
 }

}
Ah, one more thing, You can set path to MYSQL in windows & adjust line 6 as follows.

String executeCmd = "mysql -u xyz -pxxyyzz myDB <" + path;

And, You need to have Process Class invoked to run cmd.exe & execute MYSQL command in line with Command Prompt.

Interactive Programs With Java ?


Hey! This is a first of a long series of notes about Java.

I tried to start this amazing journey with a very fundamental and kind of confidence creating lesson among java newbies .

Interactive ? What is interactive ? According to its linguistic meaning it is:

allowing a two-way flow of information between a computer and a computer-user; responding to a user’s input:

According to the meaning, interactivity gets few major stream lines.
  1. Output ( Monitor)
  2. Input (Keyboard)
Let's take a look at these topics in Java.

  1. Output ( Monitor) - How to write a program to display something in monitor. It's very simple , in fact that's kind of like the  first program we wrote in the first day of our java lecture.


                  public class outputDemo {

                                 public static void main(String[]args){

                                             System.out.println("Hello World !");

                                 }

                    }
       
      2. Input (Keyboard) - But How to give keyboard inputs to a java program. There are 3 ways.

        • Command Line Arguments
        • BufferedReader
        • Scanner
    • Now, let's see how Command Line Arguments work in java. An Example is given below.

            public class Ex01{
    
                public static void main(String[]args){
    
                    System.out.println(args[0]);
    
                    System.out.println(args[1]);
    
                }
    
            }
    



                           Your arguments should be given as  follows with space in between each Argument. They're in default gets String  data type.


    • Then, It's BufferedReader.
    •  
        import java.io.BufferedReader;
    
        import java.io.IOException;
    
        import java.io.InputStreamReader;
    
        public class Ex02 {
    
            private static String name;
    
            public static void main(String[]args) throws IOException
    
            {
    
                BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    
                System.out.println("Please Enter Your Name !");
    
                name = bf.readLine();
    
                System.out.println(name);
    
            }
    
        }
    
       

    This time it requires to import BufferedReader, IOException & InputStreamReader  classes of io package. You could use type conversion if necessary.

    InputStreamReader(System.in)  - Stands for collecting input of the keyboard byte by byte and converting them in to characters.


    BufferedReader() - Stands for collecting characters and creating a line (String Data Type).


    •  Then, let's move to Scanner . There's an example given below.
            import java.util.Scanner;
    
            public class Ex03 {
    
                public static void main(String []args)
    
                {
    
                    Scanner sc = new Scanner(System.in);
    
                          System.out.println("Please Enter a number !") ;
    
                    double number = sc.nextDouble(); 
    
                    System.out.println(number);
    
                }
    
            }
     

     The program needs to be imported Scanner Class of util package. Type conversion isn't necessary as it can be directly stored in double variable number using nextDouble() method of Scanner class.