Saturday, February 28, 2009

The most useful piece of code I have written for Android so far

The following code generates a new tab whenever there is an error and prints the error inside the tab. AWESOME. It is quick and easy, and provides you with immediate feedback when something goes wrong.

} catch (Exception e) {
tabHost.addTab(tabHost.newTabSpec("ERROR")
.setIndicator("ERROR")
.setContent(R.id.errorText)
);
TextView errorText = (TextView) findViewById(R.id.errorText);
StringBuilder error = new StringBuilder();
error.append("Error: " + e.getMessage() + "\n");
for(StackTraceElement te : e.getStackTrace()) {
error.append("f: " + te.getFileName() + ", m: " + te.getMethodName() + ", l: " + te.getLineNumber() + "\n");
}
errorText.setText(error.toString());
}


N.B. I am using a TabActivity, the tabHost variable is the result of this.getTabHost().
R.id.errorText refers to a TextView I have in my layout xml.

No comments: