Sunday 26 January 2014

Post 12: Stacks and Queues

Alright, today I want to show you an implementation of a Stack and a Queue. First of all what is a Stack and a Queue? Well, both are Arrays. But contrary to "ordinary" Arrays you have only limited access to the Array's items. For example in an ordinary Array you can pretty much access all it's members in order to display, add or delete the items. In Stacks or Queues you just can't do it.

Stacks

In Stacks you can only add (or also called "push") and a new item in the very end of the Array. And you can only delete (or also called "pop") the last item of the Array. this is called Last-In-First-Out (LIFO).

Here's the push implementation:

public void push(String input){
        //check whether the stack is full
        if (topOfStack+1< stackSize){
            topOfStack++;
            theStack[topOfStack]=input;
            displayContent();
        }else{
            System.out.println("Stack is full!");
        }
    }

Here's the pop implementation:

public void pop(){
        //if there is something to delete (=pop)
        if (topOfStack>-1){
            theStack[topOfStack]="-1";
            displayContent();
        }else{
            System.out.println("Nothing to delete");
        }
    }

Queue

In Queues you can also only add (or also called "enqueue") a new item at the very end of the Array. But you can only delete (or also called "dequeue") the first item. This is called First-In-First-Out (FIFO).

Here's the enqueue implementation:

public void enqueue(String input){
        //if there's still place in the queue Array
        if (queueLength< queueSize){
            queueLength++;
            String[] inputQ=new String[queueSize];
            inputQ[0]=input;
            String[] tempQ=new String[queueSize];
            tempQ=theQueue;

            //theQueue=ArrayUtils.addAll(inputQ, tempQ);
            //merege
            for (int j=1; j< queueSize; j++){
                inputQ[j]=theQueue[j-1];
            }
            theQueue=inputQ;
            displayQueue();
        }else{
            System.out.println("Queue is full");
        }
    }


Here's the dequeue implementation:

public void dequeue(){
        //if there's still something in the queue
        if (queueLength>0){
            theQueue[queueLength]="-1";
            queueLength--;
            displayQueue();
        }else{
            System.out.println("Queue is empty");
        }
    }

You can see the complete JAVA program here on GitHub.

Sunday 19 January 2014

Post 11: Wizard-App-Tutorial

Alright, I've been busy throughout the week with writing a paper and implementing parts for my project. Phewww.... yesterday I worked till 3 a.m. Needless to say I don't have something new to offer. All I'm showing you today is an App that works like a Wizard and is able to exchange data with the PC. 
If this sounds similar to you, then you're right. Because I made a similar project here already. The only difference is the Wizard feature (I reckon there aren't that many Tutorials about how to make a Wizard in Android App) and I'll extend the functionality of the Server site Software a little bit by displaying the message that it sends to the client on its GUI (so the demonstration of the data exchange becomes more clearly.).

A Wizard

For those who may not familar with the word "Wizard": In Programming a "Wizard" is an application that guides you through consecutive steps. If you're using Windows, then you've probably installed a program already where you constantly had to press the "next" button. Well, this installation program was a Wizard.

Our Wizard will look like this. First you have the start screen. In there you can see two Buttons with the name "Option 1" and "Option 2":


If you click on "Option 1" the screen will switch to this screen (fancy right? ^^ ):
If you press on "Option 2", you'll get this screen (...not so fancy right... TT  ):

That should be a piece of cake for us. But what do we need?

Tools


Alright, now that we know what a Wizard is and our aim is, we want to build on ourselves. To do that, I'll use eclipse and the plugin for Android. If you haven't installed yet, you can go here

 Setup

 So, if you're ready you have to first create an Android project. In order to do that, go to "File-> New-> Android Application Project" as shown in this picture:


After that you'll see this Wizard. Now type in any name you want. I chosed "wizardApp_Table". You're allowed to be a tad more creative. 


Now that you've created your Android Application project, we dive into coding. As an outlook, we'll create these files (edged in red):


I'll show you step by step how to make these files and how to write code for them, so we'll get our desired Wizard.

Create Class

First we want to create a package for the two JAVA classes you see on the top. To do that, rightclick n the "src" folder you see on the very top and then choose the "package" and give it a name you want. I choosed the name "option":


Now create two new Activity classes in this package. Each of these Activity classes represents a screen that you'd see if you clicked on one of the buttons in th start screen. It's important not to create just any class, but an Activity class. Click on the package you just created and then click on "other" as depictured here:


After you've done that you should see this window pop up. Chose our Activity class and follow the instructions (= just click the "next" button until you can't any more):


Repeat these processes for the second class.

Modify Layout XML File

After you've done that Eclipse should create two new XML-files for you. You can find them in the "layout" folder:


With the XML files you can create the layout for your two respectively. Here's how to code for your "Option 1" screen looks like:

     

 
        
             
            
                     
        
 
        
             
            
             
            
             
        
 
        
             
            

            
        
 
        
             
            
                         
             
             
        
         
        
             
            
                         
             
             
                                
        
             
            
                         
             
             
                
    
     

     

         
    
             
            
                     
        
         
            
    
 
            
             
            
             
            
             
            
                     
        
         
     
 
            
             
            
             
            
             
            
                     
        
         
      
 
            
             
            
             
            
             
            
                     
        
        
    
     
 
  
  
          
        

  
          
    

 


So you've seen in the preview, the screen have Texts on their Labels, Buttons, Headers, etc. These Texts are saved in a separate XML file - in the "string" XML-file. You can find it in the "value" folder:


The code for this file looks like this:


    wizzard App
    Settings
    Hello world!
    Suche
    Aufgabe
    Click on the buttons to switch view
    another Option
    Option

    Option 1
    Option 2


Implementing Click-Action 

 Now, let's go to the interesting part. Go to the "MainActivity" class at the very top. This is the code you need to make the magic happen:

package com.example.wizardapp_table;

import com.example.wizzardapp_table.R;

import option.Option2;
import option.Option1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
    
  Button clickTask=(Button) findViewById(R.id.bTask);
  //set click Listener
  clickTask.setOnClickListener(new OnClickListener(){

   //implement what it should do
   @Override
   public void onClick(View v) {

    Intent intent=null;
    intent=new Intent(MainActivity.this, Option1.class);
    startActivity(intent);
   }
   
  });
  
  Button clickSearch=(Button)findViewById(R.id.bSearch);
  clickSearch.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {

    Intent intent=null;
    intent=new Intent(MainActivity.this, Option2.class);
    startActivity(intent);
    
   }
   
  });
  
  
  }
  
 

 @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;
 }
 

}


I'll put all the source code into my GitHub so you can download and play with it.

GitHub 

Hope you enjoyed. Till nex time!

Friday 10 January 2014

Post 10: Setting up idTronic RFID-Reader

In this post I'll show you how to set up the idTronic RFID Reader for your own personal needs. Below you can see how this Reader looks like. It's connected via a USB-to-Mini-USB-Cable with my Notebook.

  

In the picture below you can see UHF-RFID Tags that I'm using for this post. But any other UHF-Tags (~868 MHz) will do the job as fine. 

IdTronic ships the RFID-Reader with an SDK and a Console Software in C#. But in this software you won't need half of the features there. Below you can see a screen shot of the console Software and the methods you can use.


Most of the times you'll only need these methods: connection to the reader, reading tag and deconnect from the Reader. That's it. But as you can see in the picture above there's a "plethora" of methods to be found. And filtering what you actually need can be quite time consuming. So I made this effort for you and filtered out what you need in order to have an application that uses the Reader for what it is supposed to do: Reading RFID-Tags.

The Software package delivers a C# console program.You get a lot of classes but you only need these (keep in mind to have the exact structure as you see in the picture below):




Below is the code for our GUI. As you can see we only have a method that get the ports, reads the Tags, writes the Tags in a Hash-set, so every Tag-ID will only appear once. And a deconnect method. Since we want the Reader to constantly read, we implemented a timer that calls the get-Method every 1000ms.

Form code
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Timers;

namespace idTronic_GUI_Anwendung
{
    delegate void myTC_fertigCallback(List< String> l);

    public partial class Form1 : Form
    {
        CSrfeReaderInterface.device.IProtocolDeviceInterface dev = null;
        HashSet< String> hashRFID = new HashSet< string>();
        static System.Timers.Timer _timer;
        private BindingSource bindingSource1 = new BindingSource();
        BindingList< String> blist = new BindingList< string>();
        List< String> lRFID = new List< string>();
        string[] theSerialPortNames;
        Boolean connectionSuccessful = false;
        string port;
        public Form1()
        {   
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = lRFID;
        }

        private void bConnect_Click(object sender, EventArgs e)
        {
            _timer = new System.Timers.Timer(1000);
            _timer.Elapsed += new ElapsedEventHandler(jetzt);
            _timer.Enabled = true;
        }

        private void jetzt(object sender, ElapsedEventArgs e)
        {           
            get();
        }

        private void get()
        {
            if (!connectionSuccessful)
            {
                while (true)
                {
                    for (int portIndex = 0; portIndex < theSerialPortNames.Count(); portIndex++)
                    {

                        // You have to set the port correctly in order to use the RFID-Reader
                        // You can look up the Port of the RFID-Reader by consulting 'Geräte Manager'/ 'Device Manager'
                        port = "12"; // in my case it was port 12. Yours can be different
                        try
                        {
                            // try to open the serial port
                            dev = new CSrfeReaderInterface.SerialDevice(theSerialPortNames[Convert.ToInt32(port)]);
                            if (!dev.Open())
                            {
                                Console.WriteLine("Could not open the COM-Port.");
                            }
                            else
                            {
                                Console.WriteLine("The COM-Port was open successfully");
                                connectionSuccessful = true;
                                return;
                            }
                        }
                        catch
                        {
                            Console.WriteLine("No Reader was found.");
                        }
                    }
                }
            }
            
            // create trace and turn off 
            CSrfeReaderInterface.Global.m_tracer = new CSrfeReaderInterface.ConsoleTrace();
            CSrfeReaderInterface.Global.m_tracer.TraceLevel = 0;

            // create new instance of the protocol handler with the selected serial device
            CSrfeReaderInterface.protocol.CSrfeProtocolHandler ph = new CSrfeReaderInterface.protocol.CSrfeProtocolHandler(dev);

            // print out menu and process what is selected
                // do a single inventory and print out the tag list with an index to select one tag
                List< byte[]> epcList;
                ph.doSingleInventory(out epcList);
                for (int i = 0; i < epcList.Count(); i++)
                {
                    hashRFID.Add(BitConverter.ToString(epcList[i]));
                }

                lRFID.Clear();
                foreach(string s in hashRFID)
                {                    
                    lRFID.Add(s);
                }

                foreach (string item in lRFID)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine("----------------------------");

                myTC_fertig(lRFID);
        }

        void myTC_fertig(List< string> l)
        {

            if (lb_rfidID.InvokeRequired == true)
            {
                myTC_fertigCallback callback = new myTC_fertigCallback(myTC_fertig);
                this.Invoke(callback, new object[] { l });
            }
            else
            {
                lb_rfidID.Items.Clear();
                foreach (string item in l)
                {
                    
                    lb_rfidID.Items.Add(item);
                }
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = l.Select(x=>new {Value=x}).ToList();

                DataGridViewColumn column = dataGridView1.Columns[0];
                column.Width = 200;

                lPortIndex.Text = port;

            }
        }

        private void bDisconnect_Click(object sender, EventArgs e)
        {
            _timer.Enabled = false;
            dev.Close();
            Console.WriteLine("Connection closed successfully.");
        }

        private void bEmpty_Click(object sender, EventArgs e)
        {
            lb_rfidID.Items.Clear();
            hashRFID.Clear();
            lRFID.Clear();
        }

        private void bGetPort_Click(object sender, EventArgs e)
        {
            // get all available port names
            theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();

            foreach (string availablePorts in theSerialPortNames)
            {
                Console.WriteLine("savailablePorts: "+ availablePorts);
            }
            Console.WriteLine("--------------------------");

            List< string> l = new List< string>();
            for (int i=0; i< theSerialPortNames.Count(); i++)
            {
                l.Add(i.ToString());
            }

            myTC_fertig(l);
        }
    }
} 


Our GUI will look like this. Nothing fancy but it does exactly what we need: Reading the RFID-Tags.

Below I made a vid how to use this software: Firstly we have click on the "Get Port" in order to ....get the port. Secondly you click on the "Connect / Start" button. This will make our Software connect to the Reader and starts the timer, so it constantly reads the RFID-Tags in it's proximity. Thirdly, if you're done with ready, just deconnect by pressing the "Decconect / Stop" button. I also put an "Empty list" in the GUI, so you can delete the list. Because the IDs of the RFID-Tags won't delete themselves if you try to remove the Tags from the RFID-Reader. Consequently the IDs will remain in the list although the Tags aren't it the Reader's proximty. In order to refresh the list, just press the "Empty List".
 


A video of the GUI only can be found here: 



Sunday 5 January 2014

Post 9: Sorting Algorithm GUI

Alright, here I implemented a JAVA Software that helps you to better understand different sorting algorithm. With this software you can define your own list regarding the length of the list and the numbers to be filled into the list. Then you can select a sorting algorithm, e.g. Bubble Sort, Quick Sort, Radix Sort, etc. After that the software prints out every step that it does in order to sort the list, so you get a better understanding of each and every sorting algorithm.

I uploaded a video that explains how to use this software.


The explanation to each sorting algorithm are covered in this post. I will share the source code with all of you on in this link (GitHub), so you can tinker around yourself.

[Head up: I haven't implemented all of the search algorithm yet, because I was busy with my work. But I'll get back to you as soon as possible! I promise!]
 


Tweet