Monday, June 29, 2009

Using notifyAll()


package com.thread;

public class Reader extends Thread {
Calculator c;

public Reader(Calculator calc) {
c = calc;
}

public void run() {
synchronized(c) {
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {

}
System.out.println("Total is: " + c.total);
}
}

public static void main(String[] args) {
Calculator calculator = new Calculator();

// starts three threads that are all waiting to receive
// the finished calculation
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();

// start the calculator with its calculation
calculator.start();
}
}

class Calculator extends Thread {
int total;

public void run() {
synchronized(this) {
for(int i = 0; i < 100; i ++) {
total += i;
}
notifyAll();
}
}
}

Thursday, June 25, 2009

How far will my salary go in another city?

Money magazine posts a cost of living web calculator that covers a whole lot of U.S. cities with fairly up-to-date data, giving you the lowdown on how far your salary would go in your dream city.

More likely, though, is that you'd want a comparison of the cities you're looking at moving to for a new job or opportunity. Money's calculator pulls data on the cost of health care, groceries, utilities, and other necessities from the last four quarters available from The Council for Community and Economic Research, whereas some Google-located city cost comparison sites are working with years-old data.

http://cgi.money.cnn.com/tools/costofliving/costofliving.html

Thursday, June 18, 2009

Using threads and ProgressDialog

This is a simple tutorial to show how to create a thread to do some work while displaying an indeterminate ProgressDialog. Click here to download the full source.

We'll calculate Pi to 800 digits while displaying the ProgressDialog. For the sake of this example I copied the "Pi" class from this site.

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.

Because this Activity is so small I'll show you the whole thing and then discuss it at the end:


package com.helloandroid.android.progressdialogexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

public class ProgressDialogExample extends Activity implements Runnable {

private static String TAG = "ProgressDialogExample";
private String pi_string;
private TextView tv;
private ProgressDialog pd;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

tv = (TextView) this.findViewById(R.id.main);
tv.setText("Press any key to start calculation");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true, false);

Log.i(TAG, "Thread.currentThread().getName(): " + Thread.currentThread().getName());

// create a new thread using the current class as the runnable object
// new ProgressDialogExample() passed to Thread constructor
Thread thread = new Thread(this);
thread.start();

Log.i(TAG, "thread.getName(): " + thread.getName());

return super.onKeyDown(keyCode, event);
}

public void run() {
Log.i(TAG, "Thread.currentThread().getName(): " + Thread.currentThread().getName());

pi_string = Pi.computePi(800).toString();

Log.i(TAG, "run()");

handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);
}
};

}


So we see that this Activity implements Runnable. This will allow us to create a run() function to create a thread.

In the onCreate() function on line 18 we find and initialize our TextView and set the text telling the user to press any key to start the computation.

When the user presses a key it will bring us to the onKeyDown() function on line 27. Here we create the ProgressDialog using the static ProgressDialog.show() function, and as a result the pd variable is initialized. We also create a new Thread using the current class as the Runnable object. When we run thread.start() a new thread will spawn and start executing the run() function.

In the run() function we calculate pi and save it to the String pi_string. Then we send an empty message to our Handler object on line 40.

Why use a Handler?
We must use a Handler object because we cannot update most UI objects while in a separate thread. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.

When our Handler receives the message we can dismiss our ProgressDialog and update the TextView with the value of pi we calculated. It's that easy!

http://www.helloandroid.com/node/243

Callback

Java does not have procedure variables to implement function pointer callbacks the way C/C++ does. A callback would be used in C for example to pass a sin or cos function to generic plotting program. Callbacks are a way of passing functions as parameters. The callee can call the function passed to it as a parameter as often as it wants, with whatever parameters it wants.

Why would you want a callback? The normal parameter passing mechanism lets caller provide the callee with information, but provides only meager flow of information in the reverse direction, the single returned result primitive or Object. Further the callee cannot provide further information back to the caller once it has returned. The callback mechanism allows a two-way flow of information and exchange of computing resources between caller and callee.

Consider a component consisting of a panel of buttons. The caller wants to control the labellings on the buttons, how they are rendered etc. The callee wants to notify the caller whenever one of the buttons was pressed, and which one. The callback mechanism, sometimes called a Listener mechanism, allows the callee to notify the caller, the listener, of interesting events, or to use some of the methods the caller has access to.

There are four basic techniques to fake a callback function in Java.
  1. Subclassing. Subclass the calling class with an overridden callback method. Pass "this " as a parameter.

  2. Delegation via subclassing. Pass a subclassed Callback delegate object that knows how to invoke the callback method(s).

  3. Pass a Callback delegate object that implements an interface for the callback method(s).
    HeapSort: source code for an example of the delegate technique

    This is how it is most commonly done. It offers most flexibility,

  4. Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it
    as a parameter all in one line. This technique with EventListeners tends to muddle GUI and
    program logic making your GUI code non-reusable. Unless the anonymous inner classes are simple, it is generally wiser to
    make them ordinary free-standing named classes.

If you don’t already understand delegates, that probably sounds like Greek. Just look at the HeapSort example. Once you understand that code, you will easily understand the other three variants. It is much simpler than it first sounds.

Callback has a totaly different meaning in the context of security. For secure login you call the server. It then calls you back. This makes it harder for you to spoof being someone else. This may be done over phone lines or over the Internet. It is the same scheme a jealous husband might use to ensure his wife is really home as she claims.

http://mindprod.com/jgloss/callback.html

Friday, June 12, 2009

Convert from epoch to human readable date

String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

ex) 1220738315 -> 06/09/2008 17:58:35

http://www.epochconverter.com/

Thursday, June 11, 2009

Unescape HTML special characters from a String

http://www.rgagnon.com/javadetails/java-0307.html

Java: RegEx to Remove HTML Tags

String noHTMLString = htmlString.replaceAll("\\<.*?\\>", "");

http://snippets.dzone.com/posts/show/4018

Wednesday, June 10, 2009

Google Chart API

The Google Chart API lets you dynamically generate charts. To see the Chart API in action, open up a browser window and copy the following URL into the address bar:

http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World

Thursday, June 4, 2009

5 great freelance sites for developers

The following are five great websites that I have found for freelance work. This is for mostly programming/development, which includes PHP and many other languages.

1) http://www.rentacoder.com

Rentacoder is good place to find small to mid-sized projects for earning extra money. It also offers a rating system which can hurt or help you depending on your work.

2) http://odesk.com/

Odesk is a little bit different than the rest of the sites listed here. Instead of bidding on projects, you bid on hours. Employers can list the amount of hours/week and # of weeks they need out of a potential freelancer.

3) http://www.craigslist.com

Craigslist is great because there is no barrier to entry for either the employer or the potential freelancer/employee (it is also among the top sites on the Internet). This can also be a detriment because anyone with a computer can post a job listing.

4) http://programmermeetdesigner.com/

A unique website that provides an opportunity for programmers to meet and work with designers.

5) http://www.guru.com

Guru.com is a clean and professional website that has lots of large-scale projects. It also has a fairly high barrier to entry for the employers, which usually means better paying jobs.

http://www.rawseo.com/news/2009/06/04/5-great-freelance-sites-for-developers/

Wednesday, June 3, 2009

Top 10 Concepts That Every Software Engineer Should Know

1. Interfaces
2. Conventions and Templates
3. Layering
4. Algorithmic Complexity
5. Hashing
6. Caching
7. Concurrency
8. Cloud Computing
9. Security
10. Relational Databases

http://infoxon.blogspot.com/2008/07/top-10-concepts-that-every-software.html

Usage share of web browsers

The usage share of web browsers is the percentage of visitors to a group of websites that use a particular web browser. For example, when it is said that Internet Explorer has 66% usage share, it means that some version of Internet Explorer is used by 66% of visitors that visit a given set of sites. Typically, the user agent string is used to identify which browser a visitor is using. The concept of browser percentages for the Web audience in general is sometimes called browser penetration.[citation needed] More detailed information about a given browser can be found on the page for the browser in question. Notably, by-version browser share information for Internet Explorer can be found on the Wikipedia page for Internet Explorer.

http://en.wikipedia.org/wiki/Usage_share_of_web_browsers