2015-01-07 3 views
-1

Я использую AsyncTask в сочетании с StreamScraper, чтобы получить метаданные shoucast для приложения, которое я разрабатываю. Прямо сейчас, я получаю только название песни, но я также хотел бы получить название потока (что достигается с помощью stream.getTitle();.) Ниже мой AsyncTask.Восстановление более одной строки с помощью 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); 
} 
} 

Что мне нужно изменить, чтобы я мог получить больше, чем одну строку?

+0

не так ли? use '(Array) List ' вместо 'String' – Selvin

ответ

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. 
} 
Смежные вопросы