Wednesday, June 24, 2009

Google Android is pretty super easy

I've been messing around with my new toy: a HTC Magic cellphone running Google Android. I was lucky enough to get one for free from Google IO last month and have just finally gotten around to actually writing a little app for it. I haven't done anything terribly difficult yet, but from what I have already accomplished in an hour, I can say it has been a breeze.

One thing that wasn't quite as trivial as I was hoping was making an alert dialog box to do some simple runtime debugging. Understanding how it works now makes this much easier, but here is my one-liner:

(new AlertDialog.Builder(this)).setTitle("An Alert")
.setMessage("Some message")
.create().show();

the "this" in my case is my current Activity which is the default class you make when you start a project which extends the necessary Context class (not directly though). This was inside an event handler (which was implemented as an anonymous inner class) so I had to make a named reference to "this" inside the Activity scope so it was the Activities scoped "this" instead of the anonymous inner class's.

Here is the whole relevant code:


package com.gleenn.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class GlennsFirstApp extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.Button01);
final GlennsFirstApp gfa = this;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String twitterUsername = ((EditText)findViewById(R.id.EditText_twitter_username)).getText().toString();
String twitterPassword = ((EditText)findViewById(R.id.EditText_twitter_password)).getText().toString();
String statusMessage = ((EditText)findViewById(R.id.EditText_status_message)).getText().toString();
(new AlertDialog.Builder(gfa)).setTitle("Test")
.setMessage(twitterUsername + " " + twitterPassword + " " + statusMessage)
.create().show();
}
});
}
}

Labels: ,