使用AsyncTask检索多个字符串

时间:2015-01-07 03:14:41

标签: java android android-asynctask

我正在使用AsyncTask与StreamScraper一起为我正在开发的应用程序获取shoucast元数据。现在,我只获得歌曲标题,但我也希望获得流标题(使用stream.getTitle();实现。)以下是我的AsyncTask。

公共类HarvesterAsync扩展了AsyncTask {

@Override
protected String doInBackground(String... params) {
    String songTitle = null;
    Scraper scraper = new ShoutCastScraper();
    List<Stream> streams = null;
    try {
        streams = scraper.scrape(new URI(params[0]));
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ScrapeException e) {
        e.printStackTrace();
    }
    for (Stream stream: streams) {
        songTitle = stream.getCurrentSong();
    }
    return songTitle;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    MainActivity.songTitle.setText(s);
}
}

我需要更改哪些内容才能获得多个字符串?

1 个答案:

答案 0 :(得分:1)

在这种情况下,从后台任务返回多个值的最简单方法是返回一个数组。

@Override
protected String[] doInBackground(String... params) {
    String songTitle = null;
    String streamTitle = null; // new
    Scraper scraper = new ShoutCastScraper();
    List<Stream> streams = null;
    try {
        streams = scraper.scrape(new URI(params[0]));
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ScrapeException e) {
        e.printStackTrace();
    }
    for (Stream stream: streams) {
        songTitle = stream.getCurrentSong();
        streamTitle = stream.getTitle(); // new. I don't know what method you call to get the stream title - this is an example.
    }
    return new String[] {songTitle, streamTitle}; // new
}

@Override
protected void onPostExecute(String[] s) {
    super.onPostExecute(s); // this like is unnecessary, BTW
    MainActivity.songTitle.setText(s[0]);
    MainActivity.streamTitle.setText(s[1]); // new. Or whatever you want to do with the stream title.
}