Reputation: 569
I want to show a Progress Dialog on button click in my app while data is loaded from the internet. I can't get it to work, could someone give me some tips on where to put the Dialog function?
This is my AsyncTask method:
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!");
}
}
Upvotes: 2
Views: 1745
Reputation: 11191
In the AsyncTask class use onPrexecute method to display progress dialog and use onPostExecute to dismiss it:
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(YOUR_ACTIVITY_CLASS_NAME.this);
pDialog.setMessage("Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onPostExecute(String str)
{
// Dismiss the dialog once finished
pDialog.dismiss();
}
Don't forget to define pDialog before you call it:
ProgresDialog pDialog;
Upvotes: 6