Sunday, July 19, 2009

Initialization blocks in a class

You can have many initialization blocks in a class. It is important to note that unlike methods or constructors, the order in which initialization blocks appear in a class matters. When it's time for initialization blocks to run, if a class has more than one, they will run in the order in which they appear in the class file... in other words, from the top down.

To figure this out, remember these fules:
- Init blocks execute in the order they appear
- Static init blocks run once, when the class is first loaded.
- Instance init blocks run every time a class instance is created.
- Instance init blocks run after the constructor's call to super()


class Init {
Init(int x) {
System.out.println("1-arg const");
}

Init() {
System.out.println("no-arg const");
}

static {
System.out.println("1st static init");
}
{
System.out.println("1st instance init");
}
{
System.out.println("2nd instance init");
}
static {
System.out.println("2nd static init");
}

public static void main(String[] args) {
new Init();
new Init(7);
}
}


1st static init
2nd static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const

Sunday, July 5, 2009

SimpleAdapter

The corresponding SimpleAdapter maps an element from list of objects to this view.

SimpleAdapter(
Context context,
List<? extends Map<String, ?>> data,
int resource,
String[] from,
int[] to)

SimpleAdapter notes = new SimpleAdapter(
this,
list,
R.layout.main_item_two_line_row,
new String[] { "line1","line2" },
new int[] { R.id.text1, R.id.text2 } );

Now this is not a trivial line of code. What it says is:

  • "list" is a reference to an object implementing the List interface. Each element in this list is an object implementing the Map interface. In our implementation example, the list is ArrayList and the elements in this list are HashMaps.
  • The layout describing one row in the main list is defined in layout/main_item_two_line_row.xml file.
  • In each individual HashMap, there are two key-value pairs. The keys are "line1" and "line2", the corresponding values are arbitrary objects whose toString() method yields the value displayed in the list row. In our case, the values are Strings.
  • Values stored with key "line1" will be displayed in the TextView whose id is "text1". Similarly, "line2" Map key is associated with "text2" TextView.


http://mylifewithandroid.blogspot.com/2008/03/my-first-meeting-with-simpleadapter.html