package com.marakana;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class TestDemo extends Activity {
	static final String TAG = "TestDemo";
	EditText editKilos, editPounds;
	public static final String ERROR = "ERROR";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Find views
		editKilos = (EditText) findViewById(R.id.editKilos);
		editPounds = (EditText) findViewById(R.id.editPounds);

		// Setup listener for Kilos to Pounds
		editKilos.setOnKeyListener(new OnKeyListener() { // <1>
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				if (event.getAction() != KeyEvent.ACTION_UP)
					return false;
				try {
					Log.d(TAG, String.format("Kilos: %s", editKilos.getText()
							.toString()));
					double kilos = Double.parseDouble(editKilos.getText()
							.toString());
					double pounds = kilos * 2.20462262;
					editPounds.setText(new Double(pounds).toString());
				} catch (NumberFormatException e) {
					editPounds.setText(ERROR);
					Log.e(TAG, "e:" + e);
				}
				return true;
			}
		});

		// Setup listener for Pounds to Kilos
		editPounds.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				if (event.getAction() != KeyEvent.ACTION_UP)
					return false;
				try {
					Log.d(TAG, String.format("Pounds: %s", editPounds.getText()
							.toString()));
					double pounds = Double.parseDouble(editPounds.getText()
							.toString());
					double kilos = pounds * 0.45359237;
					editKilos.setText(new Double(kilos).toString());
				} catch (NumberFormatException e) {
					editKilos.setText(ERROR);
					Log.e(TAG, "e:" + e);
				}
				return true;
			}
		});

	}
}