Saturday, 28 December 2013

Post 8: PC and Android database communication

Android PC communication Project

In this post I'll show you how an Android device can query information from a Database (DB), that is on the PC, and the PC responds back with the requested results.

The communication between Android and PC is realized via Sockets. The protocol is TCP. The DB is MySQL. As IDE I'm using NetBeans.

This project consists of three parts. I'll show you how to implement each of these parts:

First, we need to set up a Database that contains the table and information that our Android App will later retrieve respectively the Java App (on the PC) will send to the Android App.

Second, we will implement a Java Application that runs the PC. The Java App is a Proxy that accepts the request from the Android App, turns it into a SQL query and then communicates with the Database to retrieve the information requested from the App.

Last but not least we will build an Android App, so the user can type in the requests. 

Here I'll publish all of my code to this project. You can just copy and paste and it will work. If you encounter any problems along the way, don't hesitate to contact me. :) I try my best to get back to you as soon as possible.

Set up Database

We will set up a simple MySQL Database containing two tables: "test" and "list". The list-table has a foreign-key to the test-table.The structure of the two tables are as follows:

The content of the test-table is as follows:

The content of the list-table is as follows:


Java Application (on PC)

This Application is structured in MVC (Model View Controller). It uses five classes.


The View

The View only represents the Widgets, like Buttons, TexViews, etc. but no logic whatsoever. This form only contains a button to open a Socket on the Server (PC).

 

The code is just as simple: 

package socket_tcpserver_reference;

import java.awt.event.ActionListener;
import javax.swing.*;

/**
 *
 * @author pad
 */
public class serverView extends JFrame{
    private JButton bStart;
   
    public serverView(){
        super("Database Proxy");
       
        JPanel panelField=new JPanel();
        bStart=new JButton("Start");
        panelField.add(bStart);
        add(panelField);
    }
   
    void addStartButtonListener(ActionListener ListenForButton){
        bStart.addActionListener(ListenForButton);
    }
   
    public void setEnableStartButton(boolean b){
        bStart.setEnabled(b);
    }
}
 

The Model

The Model contains the so called "Business Logic". In our case it connects to the Database (DB) and gets the results from it.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socket_tcpserver_reference;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;

/**
 *
 * @author pad
 */
public class serverModel {
    private String url = "jdbc:mysql://localhost:3306/";
    private String dbName = "androidpcdb";
    private String driver = "com.mysql.jdbc.Driver";// add library "MySQL JDBC Driver" in Folder "Library"
    private String userName = "root"; 
    private String password = "";
    
    private String resultDB="";

    public String getDBResults(String query){
        //calling mServer in the controller
        //here only getting "resultDB"
        Statement stmt=null;
        ResultSet rs=null;
        Connection conn=null;
        try{
            //this.query=query;
            Class.forName(driver).newInstance();
            conn=(Connection) DriverManager.getConnection(url+dbName, userName, password);
            stmt=(Statement) conn.createStatement();
            rs=stmt.executeQuery(query);
            
            ResultSetMetaData meta=(ResultSetMetaData) rs.getMetaData();
            int numberOfColumns=meta.getColumnCount();
            Object[] rowData=new Object[numberOfColumns];
            resultDB="";
            while(rs.next()){
                for (int i=0; i< rowData.length;++i){
                    resultDB+=String.valueOf(rs.getObject(i+1));
                    resultDB+="*";
                }
            }
            conn.close();
        }catch(Exception ex){
            ex.printStackTrace();
            
        }finally{
            try{
                rs.close();
                stmt.close();
                conn.close();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
        //mServer.sendMessage(resultDB);
        return resultDB;
    }
}



In order for the DB connection to work, you have to add the MySQL JDBC Driver. Here's how it's done: Right click on the "Libraries" folder. Then select "MySQL JDBC Driver" and it should like this after it's done correctly:


The Controller

The Controller contains the logic of the View, e.g. whenever a button on the View is clicked the Controller executes an action. In our case, when the button is clicked the controller starts the TCP-Server. When the TCP-Server gets a message, the Model will be called. He, the model, will get the results from the DB and sends it back to the Controller. The controller then will forward the results to the TCP-Server. The TCP-Server will then send the results to the TCP-Client.


package socket_tcpserver_reference;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author pad
 */
public class serverController {
    private serverModel myServerModel;
    private serverView myServerView;
    private TCPServer mServer;
    
    public serverController(serverModel myServerModel, serverView myServerView){
        this.myServerModel=myServerModel;
        this.myServerView=myServerView;
        
        this.myServerView.addStartButtonListener(new startConnection());
    }
    
    class startConnection implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            //disable Start Button
            myServerView.setEnableStartButton(false);
            
            //creates the object OnMessageReceived asked by the TCPServer constructor
            mServer =new TCPServer(new TCPServer.OnMessageReceived() {

                @Override
                //this method declared in the interface from TCPServer class is implemented here
                //this method is actually a callback method, because it will run every time when it will be called from
                //TCPServer class (at the while loop)
                public void messageReceived(String message) {
                    //get the Results from DB and sends it back to the Caller (Client)
                    mServer.sendMessage(myServerModel.getDBResults(message));
                }
            });
            mServer.start();
        }
    }
}

TCP Server

The TCP Server opens a socket and is responsible for getting the message, send from the Client. The TCP Server then "translates" this message into an SQL query and sends it the Controller (see "The Controller). 

package socket_tcpserver_reference;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;     //For sending messages over the network
import java.net.ServerSocket;   //Socket for Server
import java.net.Socket;         //Socket for Client

/**
 *
 * @author pad
 */
public class TCPServer extends Thread{
    public static final int SERVERPORT=4444;
    private boolean running=false;
    private PrintWriter mOut;
    
    private OnMessageReceived messageListener;
    
    private String query;
    
    //constructor
    public TCPServer(OnMessageReceived messageListener){
        this.messageListener=messageListener;
    }
    
    public void sendMessage(String message){
        if(mOut!=null && !mOut.checkError()){
            mOut.println(message);
            mOut.flush();
        }
    }
    
    @Override
    public void run(){
        super.run();
        running=true;
        try{
            System.out.println("Server: Connecting....");
            //This is the Socket for the Server
            //it waits until a client contacts the server.
            ServerSocket serverSocket=new ServerSocket(SERVERPORT);
            
            //This is the Socket for the Client
            //the method "accept()" of the Server Socket listens 
            //for a request for connection.
            Socket client =serverSocket.accept();
            System.out.println("Server: Connection accepted");
            
            try{
                //sends message to the client
                mOut=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
                
                //reads meassage received from the client
                BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
                        
                //this infinite while loop listens 
                //for incming messages from the Client
                while(running){
                    //incoming message
                    String message=in.readLine();
                    //we need to extract the message and turn it into a SQL query
                    //So we have to split the message to it's "component"
                    String[] extractedMessage=message.split("\\*", -1);
                    
                    String extractedId=extractedMessage[0];
                    String extractedName=extractedMessage[1];
                    
                    if (message!=null&&messageListener!=null){
                        String queryStart;
                        String queryMiddle;
                        String queryEnd;
                        
                        query="";
                        queryStart="SELECT t.id, t.name, t.value,t.description, COUNT(*) FROM test t, list l WHERE l.test_id=t.id ";
                        queryMiddle="";
                        queryEnd="GROUP BY t.id;";
                        
                        if(!extractedId.equals(""))
                            queryMiddle+="AND t.id ='"+extractedId+"' ";
                        if(!extractedName.equals(""))
                            //search for strings
                            queryMiddle+="AND t.name LIKE '%"+extractedName+"%'";
                        
                        query=queryStart+queryMiddle+queryEnd;
                        //message received from the client
                        messageListener.messageReceived(query);
                    }
                }
            }catch(Exception ex){
                ex.printStackTrace();
                System.out.println("Server: Error");
            }finally{
                client.close();
                System.out.println("Server: Client Socket closed.");
            }
        }catch(Exception ex){
            ex.printStackTrace();
            System.out.println("Server: Error");
        }
    }
    
    //Declare the interface. The method messageReceived(String message) 
    //will must be implemented in the ServerBoard
    //class at on startServer button click
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

Main

In order for all of our classes to run, we need a main method. This main method is in a separate class:

package socket_tcpserver_reference;

/**
 *
 * @author pad
 */
public class Socket_TCPServer_reference {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        serverView myServerView=new serverView();
        serverModel myServerModel=new serverModel();
        
        serverController myServerController=new serverController(myServerModel, myServerView);
        myServerView.setVisible(true);
        myServerView.setSize(200, 200);
        
        
    }
}

Android App

The Android App uses only two classes.But as we will later see we need in addition to these classes also xml files, because contrary to Java Application Android uses XML files to define the appearance of the software.


Android User Interface

The user interface on our Android will look like this:
In the first two EditText you can type in the attributes you want to search for. With button "Search" you start querying the Database. After clicking the button the content of the EditTexts will be deleted. The results of the query will be displayed in the table below the aforementioned widgets.

MainActivity

package com.example.socket_tcpclient_reference;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

 private TCPClient mTcpClient;
 
 //The content of the Table will be in an array
 //each column gets an array
 private Object[] colId={"ID"};
 private Object[] colName={"Name"};
 private Object[] colValue={"Value"};
 private Object[] colDescription={"Description"};
 private Object[] colAmount={"Amount"};
 
 
 @Override
 //Called when the activity is first created.
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  
  final EditText et_id=(EditText)findViewById(R.id.editText_id);
  final EditText et_name=(EditText)findViewById(R.id.editText_name);
  
  Button send=(Button)findViewById(R.id.button_search);
  
  new connectTask().execute("");
  fillTable();
  
  send.setOnClickListener(new View.OnClickListener(){
   
   public void onClick(View arg0){
    String message_id=et_id.getText().toString();
    String message_name=et_name.getText().toString();
    
    //message that will be sent to Server:
    //the "*" is to mark the later split
    String message=message_id+"*"+message_name;
    
    //sends message to the server
    if(mTcpClient!=null){
     mTcpClient.sendMessage(message);
    }
    et_id.setText("");
    et_name.setText("");
    
   }
  });
 }
 
 public class connectTask extends AsyncTask< String, String, TCPClient>{

  @Override
  protected TCPClient doInBackground(String... message) {
   //create a TCPClient object
   mTcpClient=new TCPClient(new TCPClient.OnMessageReceived(){

    @Override
    //here the messageReceived method is implemented!!!!
    public void messageReceived(String message) {
     publishProgress(message);
    }
   });
   mTcpClient.run();
   return null;
  }
  
  protected void onProgressUpdate(String... values){
   super.onProgressUpdate(values);
   
   String[] resultDB=values[0].split("\\*",-1);
   int rowCount=resultDB.length/5;
   
   //initialize string objects for table columns
   colId=new Object[rowCount];
   colName=new Object[rowCount];
   colValue=new Object[rowCount];
   colDescription=new Object[rowCount];
   colAmount=new Object[rowCount];
   
   // this is the index we need to go through the received object
   int index=0;
   for (int row=0; row< rowCount; row++){
    //column<5 data-blogger-escaped-0:="" data-blogger-escaped-1:="" data-blogger-escaped-2:="" data-blogger-escaped-3:="" data-blogger-escaped-4:="" data-blogger-escaped-5="" data-blogger-escaped-5th="" data-blogger-escaped-after="" data-blogger-escaped-because="" data-blogger-escaped-break="" data-blogger-escaped-case="" data-blogger-escaped-colamount="" data-blogger-escaped-coldescription="" data-blogger-escaped-colid="" data-blogger-escaped-colname="" data-blogger-escaped-column="" data-blogger-escaped-columns="" data-blogger-escaped-colvalue="" data-blogger-escaped-default:="" data-blogger-escaped-filltable="" data-blogger-escaped-for="" data-blogger-escaped-ill="" data-blogger-escaped-index="" data-blogger-escaped-int="" data-blogger-escaped-justify="" data-blogger-escaped-know="" data-blogger-escaped-line="" data-blogger-escaped-log.d="" data-blogger-escaped-mod="" data-blogger-escaped-public="" data-blogger-escaped-receive="" data-blogger-escaped-resultdb="" data-blogger-escaped-row="" data-blogger-escaped-rowcount="+rowCount);
  TableLayout table=(TableLayout)this.findViewById(R.id.tableLayout);
  //clears the table before new input comes in
  table.removeAllViews();
  
  for (int i=0; i< rowCount;i++){
   //fills the table with content
   fillRow(table, i);
  }
 }
 
 //fills the row with the values in the Object[]-Arrays
 public void fillRow(TableLayout table, int rowNumber){
  LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View fullRow=inflater.inflate(R.layout.row, null, false);
  
  TextView tvId=(TextView) fullRow.findViewById(R.id.rowId);
  tvId.setText(String.valueOf(colId[rowNumber]));
  
  TextView tvName=(TextView) fullRow.findViewById(R.id.rowName);
  tvName.setText(String.valueOf(colName[rowNumber]));
  
  TextView tvValue=(TextView) fullRow.findViewById(R.id.rowValue);
  tvValue.setText(String.valueOf(colValue[rowNumber]));
  
  TextView tvDescription=(TextView) fullRow.findViewById(R.id.rowDescription);
  tvDescription.setText(String.valueOf(colDescription[rowNumber]));
  
  TextView tvAmount=(TextView) fullRow.findViewById(R.id.rowAmount);
  tvAmount.setText(String.valueOf(colAmount[rowNumber]));
  
  table.addView(fullRow);
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}


TCP Client


package com.example.socket_tcpclient_reference;


//you just could "import java.io.*" or "import java.net.*"
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.util.Log;

public class TCPClient {
 private String serverMessage;
 public static final String SERVERIP="192.168.173.1";// to be replaced with your IP-address
 public static final int SERVERPORT=4444;
 private OnMessageReceived mMessageListener=null;
 private boolean mRun=false;
 PrintWriter out;
 BufferedReader in;
 
 //constructor
 public TCPClient(OnMessageReceived listener){
  mMessageListener=listener;
 }
 
 public void sendMessage(String message){
  if(out!=null && !out.checkError()){
   out.println(message);
   out.flush();
  }
 }
 
 public void stopClient(){
  mRun=false;
 }
 
 public void run(){
  mRun=true;
  try{
   InetAddress serverAddr=InetAddress.getByName(SERVERIP);
   Log.e("TCP Client", "Client: Connecting....");
   Socket socket=new Socket(serverAddr, SERVERPORT);
   try{
    out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    
    Log.e("TCP Client", "Client: Sent.");
    Log.e("TCP Client", "Client: Done.");
    
    in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
    
    while(mRun){
     serverMessage=in.readLine();
     if(serverMessage!=null && mMessageListener!=null){
      mMessageListener.messageReceived(serverMessage);
     }
     serverMessage=null;
    }
    Log.e("RESPONSE FROM SERVER", "Server: Received message: '"+serverMessage+"'");
   }catch(Exception ex){
    Log.e("TCP", "Client: Error",ex);
   }finally{
    //Closing the socket is important!!!
    socket.close();
   }
  }catch(Exception ex){
   Log.e("TCP", "Client: Error",ex);
  }
 }
 
 public interface OnMessageReceived{
  public void messageReceived(String message);
 }
}
As you could see we used the IP-address "192.168.173.1". The IP-address may differ on your computer. To find out your IP-address, go to the windows start button and type in "cmd". Start the cmd (also called "Command Prompt").


After the Command Prompt is open, type in this line:
ipconfig
 At "IPv4" you'll see your IP-address. Copy it and replace it with yours.

For our App's appearance, we need to define three XML-files.

activity_main



    
    
        
        
      
       
       
    
   
      
          
          
       
           
       
      
      
           
       
     
   

row


     
     
     
     
     
     
     

list_item


 
 
    
 
Last but not least we have to add this line in our "AndroidManifest.xml"-file. You can find the manifest file here.
The line of code you should enter is below "uses-sdk", in order for your App to connect with the server via TCP.
    

    

Start Network

In order to start the network, go to the start button in Windows and type in "cmd". Right click on the icon and run it as an Administrato:



If you've done this the Command Prompt should be open. Then type these lines in:

netsh wlan set hostednetwork mode=allow ssid=test02 key=jjjjjjjj

Then press enter and type this in. After that press enter. 

netsh wlan start hostednetwork

The network should start. This means that we create a network called "test02". The password for connecting into this network is in this case "jjjjjjjj". You should see something similar to this:

 In order to connect your Android device to this network, go to "Settings"-> "Wi-Fi" and then select the network we just created in the Command Prompt and type in the password "jjjjjjjj". Now you are good to go. I'll post video that will demonstrate how it works:

Here's a more detailed Screen cast of the same procedure:


Source Code:
The Source code can be found here:
Server
Client

Sunday, 22 December 2013

Post 7: Algorithms

Today, I'll show you something about Data Structures and Algorithm

[This post is not finished yet. I'll keep you posted: I'll upload a software that has implemented all of the alogrithm mentioned., so you can play with it to get a better understanding of these sort algorithm.


Further conents are:
Big O notation
Stacks
Queue
Heap ]

Bubble Sort

This algorithm goes through the unsorted list from left to right and compares two neighboring elements. If the left member is bigger than the right one, then the algorithm swap their position. It will repeat this until it reaches the end. Then it wll starts from the beginning and repeats the mentioned procedure. But this time it will not go to the very end of the whole list, because the last element is already the biggest element, but the next to last one.


[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]
    public void bubbleSort(){
        for (int i= arraySize-1; i >=0; i--){
            for (int j=0; j < i; j++){               
                if ( Integer.valueOf((String) myModel.getValueAt(j, 1)) > Integer.valueOf((String) myModel.getValueAt(j+1,1))){
                    swap(j,j+1);
                }
            }
        }
    }

Selection Sort 

Selection sort goes through the unsorted list and selects the smallest member of the unsorted list and puts it at the end of the sorted list. After that it repeats the process: It selects the smallest member out of the unsorted list and append this member at the sorted list of the first smallest member that he found. The algorithm repeats this process until there are no members to be found in the unsorted list but all of them are in the sorted list. This algorithm is not very efficient but very easy to implement.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]
    public void selectionSort(){
        for (int i=0; i < arraySize; i++){
            int indexOfMinValue=i;
            for (int j=i; j < arraySize; j++){
                if (Integer.valueOf((String) myModel.getValueAt(j, 1)) < Integer.valueOf((String) myModel.getValueAt(indexOfMinValue,1))){
                    indexOfMinValue=j;
                }
            }
            if (indexOfMinValue!=i)
                swap(i, indexOfMinValue);
        }
    }

Insertion Sort 

Insertion sort takes the first member of the unsorted list and goes from behind the sorted list and puts it right after the first element that is smaller than him. Because the Insertion sort checks the first member of the unsorted list it finishes when it has reached the end of the unsorted list.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]
    public void insertionSort(){
        // you start with the 2nd index (i.e. index number "1")
        for (int i=1; i < arraySize; i++){
            //get the first one of the sorted list and compare it to the member
            //at the end of the sorted list.  
            //int j=i;
            int j=i;
            String firstMemberInUnsortedList=(String) myModel.getValueAt(j, 1);

            while(j>0 && Integer.valueOf((String) myModel.getValueAt(j-1, 1)) > Integer.valueOf(firstMemberInUnsortedList)){
                //replace the member in j-1 with it's descendend in j
                myModel.setValueAt(myModel.getValueAt(j-1, 1), j, 1);
                j--;
                printOutArray();
            }   
            myModel.setValueAt(firstMemberInUnsortedList, j, 1);
        }
    }

Bucket Sort

The Bucket sorting algorithm is not really a sorting algorithm. Instead it's rather a prozcess to improve sorting efficiency and is Usually used  in conjuction with another sorting algorithm, like insertion sort.

1. In cojunction with other sorting algorithms:
The aim is to apply a sorting algorithm not to an entire list but to smaller lists. That's why in Bucket sort the elements in the big list are put into to smaller consecutive lists. E.g. if the list contains numbers that ranges from 0 to 10, then there will be several smaller lists (=buckets) let's say 3. Then the first bucket can hold numbers from 0 to 3. The second bucket from 4 to 6. And the third 7 to 10 buckets.
Now, within each of this list one of the aforementioned sorting algortihm,  e.g. selction sort or insertion sort can be applied to sort the the elements within the buckets. After that all of buckets are merged into a big list again.

2. Bucket sort alone:
With Bucket sort alone you create for a large list smaller lists - exactly the same as in the example above. After that you again create smaller buckets within each buckets, until there's only one element in this bucket. These created buckets are set in order already, so when there's only  one element in the bucket, you merge the buckets into a large list and get a list that is sorted.

This technique reqires recursion which in turn is costly in terms of  ressources and time.


[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]
    public void selectionSort(){
        for (int i=0; i< arraySize; i++){
            int indexOfMinValue=i;
            for (int j=i; j < arraySize; j++){
                if (Integer.valueOf((String) myModel.getValueAt(j, 1)) < Integer.valueOf((String) myModel.getValueAt(indexOfMinValue,1))){
                    indexOfMinValue=j;
                }
            }
            if (indexOfMinValue!=i)
                swap(i, indexOfMinValue);
        }
    }

Radix Sort

This sorting algorithm efficient especially for larger arrays. It's applied for non-comaritive integer sorting algortihm. There are two ways of doing it:  Least Significan Digit (LSD), Most Significant Digit (MSD). This only means where to start sorting. LSD means in this context that we start with the far right digit. E.g. the far right digit of number 123 is the position where number 3 is. MSD means we start at the position where number 1 is. In the following example the focus is on LSD. We have 10 buckets. Each carries one of the values from 0 to 9. We will go through the list from left to right. Given we have 3 digit numbers, then we first look at the value of the number's first digit (since it's LSD) and put these numbers in the buckets  with the same value.
E.g. The number 123 has got 3 as a first digit will be put into a bucket with the value 3. The number 456 has got 6 as a first digit and will be put into bucket 6 and so on. According to this first sort we get a new order of our list. In the next step we will look at the value of the number's second digit and put them in to the buckets with the same value.
E.g. the number 123 has got 2 as the second digt and will be put into the bucket with the value 2. The number 456 has 5 as the second digit and will be put into bucket 5 and so on. After that we get a list that again has a reordered. But we aren't done yet. In the third and last step (it's the last step because we agreed on having 3 digit numbers), we look at the 3rd digit of the numbers and will put them into the according bucket. Now after this step we get a list that is finally ordered.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]
private ArrayList< String > SortRadix(int digit, ArrayList< String> arr){     
         ArrayList< String> bucket_sorted = new ArrayList< String>();
            
         if (digit==0)
            return arr;
         else{
            ArrayList< String> bucket_0 = new ArrayList< String>();
            ArrayList< String> bucket_1 = new ArrayList< String>();
            ArrayList< String> bucket_2 = new ArrayList< String>();
            ArrayList< String> bucket_3 = new ArrayList< String>(); 
            ArrayList< String> bucket_4 = new ArrayList< String>();
            ArrayList< String> bucket_5 = new ArrayList< String>();
            ArrayList< String> bucket_6 = new ArrayList< String>();
            ArrayList< String> bucket_7 = new ArrayList< String>(); 
            ArrayList< String> bucket_8 = new ArrayList< String>();
            ArrayList< String> bucket_9 = new ArrayList< String>();

            
            // goes throught the transferred array "arr" 
            // and checks all of it's members
            for (int i=0; i< arr.size(); i++){

                //"radix" contains the digits of the current number 
                String[] radix=(arr.get(i).split(""));
                int digi=numberOfDigit!=radix.length-1?digit-(numberOfDigit-(radix.length-1)):digit;
                
                String nthDigit;
                try{
                    nthDigit=radix[digi].equals("")?"0": String.valueOf(radix[digi]);
                }catch(Exception ex){
                    nthDigit="0";
                }
                
                //check the nth Digit
                switch(nthDigit){
                    //transfer it into the table
                    case "":
                    case "0":
                        bucket_0.add(arr.get(i));
                        break;
                    case "1":
                        bucket_1.add(arr.get(i));
                        break;
                    case "2":
                        bucket_2.add(arr.get(i));
                        break;
                    case "3":
                        bucket_3.add(arr.get(i));
                        break;
                    case "4":
                        bucket_4.add(arr.get(i));
                        break;
                    case "5":
                        bucket_5.add(arr.get(i));
                        break;
                    case "6":
                        bucket_6.add(arr.get(i));
                        break;
                    case "7":
                        bucket_7.add(arr.get(i));
                        break;
                    case "8":
                        bucket_8.add(arr.get(i));
                        break;
                    case "9":
                        bucket_9.add(arr.get(i));
                        break;
                    default:
                        System.out.println("case doesn't exist");
                                
                        break;
                }
            }
            //merge into one array, which is "bucket_sorted"
            bucket_sorted.addAll(bucket_0);
            bucket_sorted.addAll(bucket_1);
            bucket_sorted.addAll(bucket_2);
            bucket_sorted.addAll(bucket_3);
            bucket_sorted.addAll(bucket_4);
            bucket_sorted.addAll(bucket_5);
            bucket_sorted.addAll(bucket_6);
            bucket_sorted.addAll(bucket_7);
            bucket_sorted.addAll(bucket_8);
            bucket_sorted.addAll(bucket_9);
            return SortRadix(digit-1, bucket_sorted);
         }
     }
     
    public void radixSort(){
        
        numberOfDigit=3;
        //translate tableModel into array
        String[] bucket_sorted_array=(SortRadix(numberOfDigit, tableModelIntoArrayList())).toArray(new String[myModel.getRowCount()]);
        
        //merge array into table model
        merge(bucket_sorted_array);        
    }

// Helper function
// transfers tableModel to array
    private ArrayList< String> tableModelIntoArrayList(){
        ArrayList< String> a=new ArrayList< String>();
        for (int i=0; i< myModel.getRowCount(); i++){
            a.add((String)myModel.getValueAt(i,1));
        }
        
        return a;
    }
    
// transfers arrays back to tableModel
    private void merge(String... args){
        
        int m=0;
        for(String arg: args){
            myModel.setValueAt(arg, m, 1);
            m++;
        }
    }


Quicksort

In Quicksort you select one element in the list and partion the list into two sets: One that only conains slements that are larger than the pivot and one that only contains elements smaller than the pivot. In order to do so, we start with a two pointers: One at the very beginning and one at the very end of the list. We move the pointer at the beginning one step up to the other end until it reaches a value that is larger than or equal the pivot. Then we move the pointer at the end one step down to the other end until it reaches a value that is smaller than or equal the pivot. When we have on the left side a value that is larger than or equal the pivot, and on the right side a value that is smaller than or equal the pivot swap the position of these elements. Then we select another element that is larger than or equal resp. smaller than and equal the pivot and swap position. This process will be repeated until both pointers will point to the same element - the pivot. At this point the pivot is in the correct position, Now, we have two sets: One that contains elements smaller than the pivot and one that contains elements that that are larger than the pivot. These two steps will be partioned like we did with the orignal list, until we get lists that are either containing zero or one element and are therefor sorted. In the last step these list, with only one (or zero) elements are rejoined into one big list containing sorted elements.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]

Merge Sort

Merge sort uses a similar concept to bucket sort. The big unsorted list is divided into list containining only one item. Then you compare the elements within these two lists and put it in another list. The element that is smaller will be put into the new list first. The larger element, will be put in second. You repeat the process for all other single element lists. Now, you don't have lists containing single elements but lists containing two elements (because the aforementioned list contained only one element) that are ordered. These lists are now compared to each other in a similar manner: First you select two list. In this two lists, then you select the first element of each of these lists and compare them to each other. The one that's smaller will be put in first into a new list. Then in the list that the item was just put into the new list, we select the next element and compare it with the currently selected element in the other list. Again we compare both elements and put it into the new list. We repeat this process until we only got one big list of sorted elements.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm]

Heap Sort

First we have to order the unsorted list into a heap. The heap can be presented as a binary tree. But it is saved in an array. This is how you calculate the parents and the children at one point of the array:
Parent x==> child1: 2x+1; child2: 2x+2
Child y==> parent: (y-1)/2
The Heap has by definition the largest number as a root. So, in order to sort our list, we put the root element into the last place of the list. After that a new root has to be selected. We want the last Heap element to be the root. of course we have to check whether this suffice the definition of a heap, because the heap has to be the largest element. If it is not, then we will swap it with the largest child until the heap becomes consistent. From there we now have the largest element of the remaining list as a root. This element we will put into the next to last part. We will repeat this until all the heap doesn't contain any elements.

[pictures that illustrates the important steps]
[java code that implements the sorting algorithm] 

The video of the software can be seen in this post.

If you think the algorithm aren't correcty described, please say so. I'd appreciate any improvement suggestions. Thank you in advance. :-)

Sunday, 15 December 2013

Post 6: Arduino Ultrasonic sensor LED

Today I want to present you an ultrasonic sensor that detects when something is nearby. If there is something which distance to the ultrasonic sensor is less than 5 cm, then the LED will switch on, otherwise the LED is off.


Sunday, 8 December 2013

Post 5: RFID-Library Software

Today I want to present you a Library (a real library.... something with real books out of paper and so on. ;) ) Software. This was a project I've done for the chair and the people I'm working in respectively working with.

I expanded the Database that was already there. The data are on a MS SQL Server 2008. I wrote the core features of this Software (lending, returning, searching, view account), installed the Hardware and also made the design of the Software. On top of that I had ideas about additional features like live-search, lean search. These features weren't implemented by me but a very good Computer Science Student of mine. Kudos to him! :)

With this software you can lend and return books. You can also search for books and view your own account of books you already lend. The Software is connected to an RFID-Reader, in order to detect lend or returned books. The Software is completely written in C#. The RFID-Reader is from the firm "Feig". We used an UHF-RFID-Reader for Europe (868 MHz).

It works pretty straightforward: Books are attached with an RFID-Tag. Each Tag has an ID. On a database the book's information and the Tag-ID are connected. The reader detects the tag and displays the book's information on the Touchscreen.

Here's a video that demonstrates how it works (sorry for the poor quality. After editing most of the awesme HD 3D effects have gone....):

Sunday, 1 December 2013

Post 4: (tiny) Embedded Systems Project


Ok, so in order to enhance my knowledge in Computer Science I soldered a Freeduino (as you can see here). In this week I managed to upload a Hello-World-program and write a program that can detect an RFID-Tag and activates a Servo if the Tag is successfully detected. The second project can be used to open a door with a RFID-Card.

1. Blink program:


2. RFID-Door opener:


Tweet