Creating a thread to asynchronously download xml f

2019-07-25 08:58发布

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.

1条回答
疯言疯语
2楼-- · 2019-07-25 09:16

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.

查看更多
登录 后发表回答