views:

63

answers:

1

I'm making an application that grabs an RSSFeed from one location, parses it, and displays the items in a rich ListView. I've got it working synchronously, but it hangs on the initial download. I used ImageDownloader from the Google blog to asynchronously grab images to populate the ListView, but how do I go about threading the download process, making the display update wait until it's done before passing the RSS to the adapter, and display a dialog during the initial download? I'm totally new to threads and message handling!

Here's the code in my onCreate so far:

    feedWait = new Handler() {

        public void handleMessage(Message msg) {
            Log.d(TAG, "made it to handler");
            UpdateDisplay();
        }
    };

    netThread.start();

And here's the thread:

private Thread netThread = new Thread() {  
    public void run() {  

            getFeed();
            feedWait.handleMessage(new Message());
    }
};

This throws an error, saying I have to invoke Looper.prepare() before creating a handler, but if I do Looper.prepare() in onCreate, it just fails.

+5  A: 

You should use an AsyncTask for this. For example,

private class GetFeedTask extends AsyncTask<Void,Void,Boolean> {

    @Override
    public Boolean doInBackground(Void... params) {
       return getFeed();
    }

    private boolean getFeed() {
        //return true if successful, false if not
    }

    @Override
    public void onPostExecute(Boolean result) {
        if(result) //got feed successfully
            updateDisplay();
    }
}

Then in your onCreate(), just call new GetFeedTask().execute();.

See http://developer.android.com/reference/android/os/AsyncTask.html for documentation.

cfei
Oh, thanks for the response. I think I'm going to build an asynchronous class to queue up and handle these http requests for my project. In the meantime, however, I did manage to get it working via a simple Thread and Handler class. I'm reading up on it all now! Thanks for the reply!
Brian