Android Loading listview items from service results in hang

Posted by Isaac Waller on Stack Overflow See other posts from Stack Overflow or by Isaac Waller
Published on 2009-05-20T00:10:40Z Indexed on 2010/06/09 20:32 UTC
Read the original article Hit count: 400

Hello,
In my Android application, I have a ListActivity. This ListActivity uses a SimpleAdapter that I fill with items from my service. So, in my code, I do:

MySuperCoolService.Binder serviceBinder = null;
private ServiceConnection serviceConnection = new ServiceConnection()
    {
    	public void onServiceConnected(ComponentName className, IBinder service) {
    		Log.d(TAG, "Service connection: connected!");
    		serviceBinder = (MySuperCoolService.Binder)service;
    	}
    	public void onServiceDisconnected(ComponentName className) {
    		Log.d(TAG, "Service connection: disconnected");
    		serviceBinder = null;
    	}
    };
bindService(new Intent(this, MySuperCoolService.class), serviceConnection, BIND_AUTO_CREATE);
while(serviceBinder==null) {
    Thread.Sleep(1000);
}
// now retrieve from service using binder and set list adapter

This whole operation takes hardly any time (less than a second), so I want it to run in the UI thread. See my onCreate:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fillDataUsingCodeAbove();
}

The reason I want this to run in the UI thread is that if you have a list item selected, or you have scrolled to a certain position in the ListView, and you rotate the device or take out the keyboard or something (to trigger a configuration change) when my activity is restarted, Android will try to restore the state right after onCreate. But, if I run it in a separate thread, it will not. Also there is a cool fadein animation too :)
The problem I am having with running it in the UI thread is that when I try to bind to the service, that service bind request gets put onto the message queue. But then when I go into my loop, I stop the message queue from looping. So my program hangs, because it's waiting for the service to get bound, and the service won't get bound until the loop ends. I have thought of putting Looper.loop() inside my loop, but that just hangs it at Looper.loop() (I don't know why.)
Sorry for such a long question,
Isaac Waller

© Stack Overflow or respective owner

Related posts about android

Related posts about listview