Wednesday, April 20, 2011

Observer that would not observe....

This is what I wasted half the night trying to solve and I failed:

http://stackoverflow.com/questions/5726468/contentobserver-getting-notifications-about-Linkdeletes-but-not-inserts-or-updates

Basically, I have a ListActivity that I wanted to sort. To enable sorting, I added a spinner control at the top of the screen, with sort options. When a sort option is selected, it requeries the underlying DataProvider, and the list is sorted according to user's preferences.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content">

<Spinner android:layout_width="fill_parent"
android:layout_height="40sp" android:id="@+id/spinner_sort_activities">
</Spinner>

</LinearLayout>

<FrameLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@android:id/list" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:drawSelectorOnTop="true" />

<!-- Here is the view to show if the list is empty -->
<TextView android:text="@string/empty_list_default_value"
android:id="@+id/txt_empty_list" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textSize="16sp"
android:textStyle="bold" android:gravity="center">
</TextView>
</FrameLayout>
</LinearLayout>

However, it does not make much sense for the Spinner to still be there when the list is empty, and the empty view is presented to the user. So I did this:

// Get a cursor to access the note
Cursor mCursor = managedQuery(ActivityColumns.CONTENT_URI, PROJECTION, null, null,
getSortOrderStringFromSpinner());

mCursor.registerContentObserver(new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfChange)
{
// hide the list sort drop down if no items in the list
if (activityListAdapter.isEmpty())
sortOptionsSpinner.setVisibility(View.GONE);
else
sortOptionsSpinner.setVisibility(View.VISIBLE);
}

@Override
public boolean deliverSelfNotifications()
{
return true;
}
});


For some reason it just does not work. I know there is a problem somewhere in my code. But I just don't know where. The observer is observing - it receives all deletes, but not inserts or updates. Frustrating.

I tried debugging, reading, googling, stack-overflowing, cursing and, finally, throwing some random code at the problem, but it still did not work. I hope to find an answer quickly, because I have some updates I wanted to publish ASAP, but I wanted to get the sorting done first.

Well, I'll spend some more time on it tonight.

No comments: