我在doInBackground()中运行了两个任务。一个任务是从站点读取数据,另一个任务是从Url解析xml文件并在imageview中设置图像。但是我希望将两个任务分开意味着一旦从站点读取完成,它应该在textview中设置文本。然后应该开始xml解析。那我该怎么办?
这是我的代码:
private class DownloadWebPageTask extends AsyncTask<String, Void, ArrayList<String>>
{
ProgressBar progressBar;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = (ProgressBar)findViewById(R.id.showLoading);
progressBar.bringToFront();
}
@Override
protected ArrayList<String> doInBackground(String... arg0)
{
String xml = null;
ArrayList<String> lyricArtistArray = new ArrayList<String>();
//get lyrics - First task
lyricsArray = SearchHelper.findLyrics(arg0[0],arg0[1]);
lyricArtistArray.add(lyricsArray);
//get image - Second task
artistNameGlobal = arg0[1].toString();
try
{
XMLParser parser= new XMLParser();
String img;
String t = arg0[1].replace(" ","%20");
String url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+t+"&api_key=mykey";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName("artist");
for(int i=0;i<1;i++)
{
Element e = (Element)nl.item(i);
img = parser.getValue(e,"image");
System.out.print(img);
ImageView imageArtist = (ImageView) findViewById(R.id.artistImageView);
imageArtist.setImageBitmap(LoadImageFromURL(img));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return lyricArtistArray;
}
@Override
protected void onPostExecute(ArrayList<String> lyricArtistArray)
{
progressBar.setVisibility(View.GONE);
tvMain.setTextSize(fontSize);
tvMain.setTextColor(FontColor);
if(!FontStyle.equals("None"))
{
String s = FontStyle.concat(".ttf");
String s1 = "fonts/"+s;
Typeface tf=Typeface.createFromAsset(getAssets(),s1);
tvMain.setTypeface(tf);
}
tvMain.setText(Html.fromHtml(lyricArtistArray.get(0).toString()));
tvMain.setMovementMethod(new ScrollingMovementMethod());
tvMain.setSelected(true);
}
}
我该如何处理这两项任务?请建议我一些解决方案,以便花费最少的时间。请快速回复我。提前完成。
答案 0 :(得分:0)
我想到了几种方法。第一个是实现onProgressUpdate(Progress...)
传递String
并在此方法中设置TextView
的值。然后,在下载完成后,但在解析开始之前,您将调用updateProgress
。这将是您完成这项工作所需的最少工作量。
另一条路线是创建一个新的AsyncTask
,其中只包含解析代码。第一个AsyncTask
(现在只执行下载)将设置TextView
内容,并在其AsyncTask
中开始解析onPostExecute
。