Tuesday, June 19, 2012

NDK Docs

Google has not placed its NDK documentation online. Consequently any NDK-related Google searches that might by answered by the NDK documentation will come up empty. I'm tired of this, so I've decided to put up some of these docs, at least the ones that are not mirrored elsewhere already.

Friday, June 15, 2012

Android ListView: Make Selection Stay

The behavior of Android's ListView is surprising: when the user clicks an item, it doesn't stay selected! It looks selected for a brief instant and then fades away.

Apparently the "disappearing selection" is by design; it's something called "touch mode". I read through that document and still I have no idea why they thought it was a good idea. My guess is that, since Android was originally designed for small-screen devices, they expected that you would fill the screen with a list and then, when the user clicks an item, move to a new list on a different screen. Thus, the user wouldn't be aware that Android lost track of the selected item.

But this behavior is quite annoying if, for example, you want the user to select an item and then show information about that item on the same screen. If the selection disappears, how is the user supposed to know what they clicked (assuming of course that users have the attention span of a goldfish)?

One possible solution is to change all the list items into radio buttons. I don't really like that solution because it wastes screen real estate. I'd rather just use the background color to show which item is selected. I have seen one solution so far but it is not quite complete or general. So here's my solution:

1. In your XML layout file,

Go to your ListView element and the following attribute: android:choiceMode="singleChoice". I'm not entirely sure what this does (by itself, it doesn't allow the user to select anything) but without this attribute, the code below doesn't work.

2. Define the following class.

It is used to keep track of the selected item, and also allows you to simulate pass-by-reference in Java:

public class IntHolder {
public int value;
public IntHolder() {}
public IntHolder(int v) { value = v; }
}

3. Put the following code somewhere

I'll assume you put it in your Activity, but it could go in any class really:
static void setListItems(Context context, AdapterView listView, List listItems, final IntHolder selectedPosition)
{
    setListItems(context, listView, listItems, selectedPosition, 
                 android.R.layout.simple_list_item_1, 
                 android.R.layout.simple_spinner_dropdown_item);
}
static void setListItems(Context context, AdapterView listView, List listItems, final IntHolder selectedPosition, 
                         int list_item_id, int dropdown_id)
{
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> list, View lv, int position, long id) {
            selectedPosition.value = position;
        }
    });
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, list_item_id, listItems) { 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = super.getView(position, convertView, parent);
            if (selectedPosition.value == position)
                itemView.setBackgroundColor(0xA0FF8000); // orange
            else
                itemView.setBackgroundColor(Color.TRANSPARENT);
            return itemView;
        }
    };
    adapter.setDropDownViewResource(dropdown_id);
    listView.setAdapter(adapter);
}

That's all! The above assumes you want single selection. With some small modifications to getView(), you could support multi-selection too, I guess, but you should probably use checkboxes instead.

Warning: this solution needs further development. If the user uses arrow keys or buttons to select an item, that item will not be selected from the IntHolder's perspective. If the user presses the unlabeled button or the Enter key then the item will become "officially" selected, but then you have another problem because if the user uses the arrow keys again, it will sort of look like two items are selected. Leave a comment if you figure out how to keep the "internal selection" in the IntHolder synchronized with the "keyboard selection" or whatever it's called. What is it called, anyway?

Friday, June 8, 2012

The Delightful D Programming Language

D versus C# and C++

I became a D enthusiast yesterday, when I learned how much better it is than C++, and I have been studying D for two days straight out of sheer love. Oh, it's not perfect, but compared to C++? No contest. Ditto for Java. C# was my language of choice as of 3 days ago, but today I think it has moved down a rank.

Not having used D for any serious work yet, I could be mistaken. But D has an answer to every major criticism commonly raised against C++, from compilation time, to poor type safety, to the headache of maintaining header files, to slow compilation. D isn't just an evolutionary improvement, it has innovations that don't exist in any of the world's popular languages*:
  • It is said to have one of the world's fastest compilers
  • You can use try/catch/finally and RAII, but scope(exit) makes exception-safe code easier to read and write
  • You can define closures that the compiler can inline (do any C++11 compilers do that? I'm not sure, I'm stuck on Visual C++ 2008 due to a need to support Windows CE)
  • Garbage Collection is standard but optional, so you can write programs with low-latency guarantees by avoiding GC allocations (but how to manage memory instead? I suspect one could use alias this to make smart pointers a la C++?)
  • Slices and ranges, a collection access mechanism that is far safer than C++ iterators and also far more convenient, no need to repeat yourself as in lower_bound(blobCollection.begin(), blobCollection.end(), blob)
  • Generics are more flexible than in C++ and don't produce pages of error messages
  • Compile-time metaprogramming that vastly outclasses C++ (and obviously C# too)
  • Compile-time reflection which (I hope, but can't confirm) one could use to build a run-time reflection system if one wanted
  • A well-designed, multi-paradigm approach to concurrency with interesting features for both shared-memory and message-passing architectures
  • Built-in support for unit tests
  • Array-wise expressions, e.g. a[] = (b[] + c[]) / 2  (MATLAB does this more tersely, but among general-purpose languages this kind of feature is rare)
  • Superior floating-point features (e.g. nextUp()/nextDown()/ulp(), hex floats, control of hardware exceptions)
* (Other less-popular languages have some of these features, but certainly not all of them)

And since D is so similar to C++ and C#, you wouldn't have to spend a lot of time learning it, so why not? Plus, it shouldn't be that hard to port small programs and libraries from C++.

Admittedly, I'm not happy with everything. They are still catering to the C crowd, so you still have to fill your "switch" statements with "breaks", the "static" keyword is confusingly overused, lambdas require braces and a "return" statement (c.f. C#'s quick x -> x+1 syntax), all functions and try/catches requires braces, pass-by-reference is implicit at the call site, the operator precedence of (&, |, ^) is foolish, there's no pattern matching or algebraic data types (but at least there are tuples), if statements are not expressions... still, what D offers is too good to pass up.

But of course, while the D language is clearly terrific, and the standard library has apparently matured, the surrounding tools might not be so good: IDEs, support for smartphone platforms, etc. The only IDE I tried, Visual D (IDE plugin for Visual Studio) works pretty well, including debugging which seems to work as well as the Visual C++ debugger, and which can step into the standard library (fun!). However, Code Completion doesn't work very well yet.

Compared to C#, D is better in most areas but seems weak when it comes to dynamic linking and reflection. For example, an IDE written in .NET or Java could easily have a plug-in system, but I'm not so sure about D. .NET also offers runtime code generation while D does not. However, a research compiler exists to compile D to .NET code. Given that C++/CLI already compiles to .NET (C++/CLI), perhaps someday one will be able use D equally well for managed and native code (with a small performance hit in managed land, of course.)

Interoperability with C/C++ and .NET are pretty decent. D is supposed to interoperate with C++ functions and singly-inherited classes via extern (C++) and C++ name mangling (but which compiler's name mangling?), while you can easily create COM interfaces callable from .NET and other languages.

Still don't know D? Go forth and learn it! Note: okay, to be honest the documentation isn't that great. It really helps to read The D Programming Language.

Thursday, June 7, 2012

Smart Tabs

Man, I sure wish programming text editors would support those smart tabs known as "elastic tabs".


Use Visual Studio? Vote for elastic tabs.