从互联网加载数据时,我想在我的应用程序中单击按钮时显示进度对话框。我无法让它工作,有人可以给我一些关于在哪里放置对话框功能的提示吗?
这是我的 AsyncTask 方法:
private class GetTweets extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... twitterURL) {
//start building result which will be json string
StringBuilder tweetFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet tweetGet = new HttpGet(searchURL);
//execute request
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity tweetEntity = tweetResponse.getEntity();
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
}
}
else
tweetDisplay.setText("Error!");
}
catch(Exception e){
tweetDisplay.setText("Error!");
e.printStackTrace();
}
}
//return result string
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
//start preparing result string for display
StringBuilder tweetResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray tweetArray = resultObject.getJSONArray("results");
//loop through each item in the tweet array
for (int t=0; t<tweetArray.length(); t++) {
//each item is a JSONObject
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
}
}
catch (Exception e) {
tweetDisplay.setText("Error!");
e.printStackTrace();
}
//check result exists
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("no results!");
}
}