Display Dialog when loading internet - android

I am trying to create a dialog when loading Httprequest. But it load during the i click to intent from last Activity, but not the start of this Activity.
And the dialog just shown in 0.00001sec then dismiss.
Am i implement it wrongly?
Here is my codes
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpPostHandler2 handler = new HttpPostHandler2();
String URL ="http://xxxxxx";
handler.execute(URL);
}
public class HttpPostHandler2 extends AsyncTask<String, Void, String> {
private String resultJSONString = null;
private ProgressDialog pDialog;
public String getResultJSONString() {
return resultJSONString;
}
public void setResultJSONString(String resultJSONString) {
this.resultJSONString = resultJSONString;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
AuthScope.ANY_PORT), new UsernamePasswordCredentials("core",
"core1234"));
String responseContent = "";
HttpClient httpClient = new DefaultHttpClient();
((AbstractHttpClient) httpClient).setCredentialsProvider(credProvider);
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse response = null;
try {
// Execute HTTP Post Request
response = httpClient.execute(httpPost);
responseContent = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
setResultJSONString(responseContent);
// return new JSONObject(responseContent);
return responseContent;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
resultJSONString = result;
}
}

Make sure that the work of HttpPostHandler2 is long enough to display the pDialog. If it not, it will disappear really soon.
However, you cannot display GUI in onCreate. To display the dialog, you should move them to onStart:
#Override
public void onCreate(Bundle savedInstanceState) {//GUI not ready: nothing is shown
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpPostHandler2 handler = new HttpPostHandler2();
}
#Override
protected void onStart () {//GUI is ready
String URL ="http://xxxxxx";
handler.execute(URL);
}
See comment for more information.

Related

Progress Dialog is not shown during execution of AsyncTask

I googled for hours and tried all answers of Stack Overflow but didn't solved my problem.
I made android program to download data in bytes which wroks perfectly. And for download working on background thread. I want to show a Progress Dialog(jus Spinning one). But I'm having really annoying problem. My download takes about 5 sec but my progress dialog is either not shown or just shown for last 1 sec.
Here's my code for AsyncTask.
public class ImageJSON extends AsyncTask<String, String, byte[]> {
private JSONObject jsonObject = new JSONObject();
private byte[] response;
private ProgressDialog pg;
private Context context;
public ImageJSON(Activity activity) {
pg = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg.setMessage("Downloading, please wait.");
pg.show();
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
if (pg != null) {
pg.setProgress(Integer.parseInt(progress[0]));
}
}
protected void onPostExecute(byte[] result) {
if (pg.isShowing()) {
pg.dismiss();
}
}
#Override
protected byte[] doInBackground(String... params) {
HttpPost httpPost = new HttpPost("my file url....");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("imageId", params[0]);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/octet_stream");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
if (entity!=null) {
response = EntityUtils.toByteArray(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException e) {
e.printStackTrace();
}
return response;
}
And I called it from my activity using this code.
final ImageJSON imageTask = new ImageJSON(ReaderActivity.this);
byte[] response = imageTask.execute(imageId).get();
If anybody can help me, Thanks in advance.
You don't want to be using get() as it still freezes your UI thread thus denying the sense of using AsyncTask. You might want to implement onPostExecute in order to return your result properly.
try this -
public ImageJSON(Activity activity) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(ReaderActivity.this);
pg.setMessage("Downloading, please wait.");
pg.show();
}
you forgot to initilise your progressDialogue in onPreExecute method
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(pass_context_here);
pg.setMessage("Downloading, please wait.");
pg.show();
}
Change this
public ImageJSON(Context ctx) {
this.context = ctx;
}
Now in your onPreExecute() method use this
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(context);
pg.setMessage("Downloading, please wait.");
pg.show();
}
You'r initializing your ProgressDialog in ImageJSON class which block your UI thread means freezes it. So need to initialize it in onPreExecute() method with reference of context.

Showing percentage progress dialog while parsing JSON response android

I am getting a JSON response from a URL and convert it into a string. I want to parse this string to get some values from the response. But when the parsing takes place the application shows a blank screen(black screen) until the response is parsed. I wanted to show a ProgressDialog which shows how much data is to be downloaded so that the app does not show that blank screen. I tried showing a ProgressDialog but it is shown before the parsing and after it is done. The in between time still shows the blank screen.
Here is my code:-
String registerContet = "myUrl";
String items;
try
{
items = new FetchItems().execute(registerContet).get();
pDialog = new ProgressDialog(this).show(Home.this, "Fetching news items", "Please wait..");
JSONArray jObject = new JSONArray(items);
for (int i = 0; i < jObject.length(); i++)
{
JSONObject menuObject = jObject.getJSONObject(i);
String title= menuObject.getString("Title");
String description= menuObject.getString("BodyText");
String thumbnail= menuObject.getString("ThumbnailPath");
String newsUrl = menuObject.getString("Url");
String body = menuObject.getString("Body");
String newsBigImage = menuObject.getString("ImageBlobUrls");
map = new HashMap<String,String>();
map.put(SOURCETITLE, title);
map.put(TITLE, description);
map.put(THUMBNAILPATH, thumbnail);
map.put(BODY, body);
map.put(URL, newsUrl);
map.put(IMAGEBLOBURLS,newsBImage);
myNList.add(map);
}
itemsAdapter = new LazyAdapter(Home.this, myNList);
if(pDialog!=null && pDialog.isShowing())
{
pDialog.dismiss();
}
nList.setAdapter(itemsAdapter);
nList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(Home.this).show(Home.this, "Fetching news..", "Just a moment");
HashMap<String, String> myMap = myNList.get(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("NItems", myMap);
startActivity(nIntent);
}
});
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FetchItems.java is
private class FetchItems extends AsyncTask<String, String, String> {
// TODO Auto-generated method stub
ProgressDialog myDialog;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpResponse response = null;
String resultString = "";
String myResponseBody = "";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpGet request = new HttpGet(params[0]);
try {
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
myResponseBody = convertToString(inputStream);
}
}
} catch (Exception e) {
}
return myResponseBody;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*
* if(myDialog.isShowing()) { myDialog.dismiss(); }
*/
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*
* myDialog = new ProgressDialog(Home.this);
* myDialog.setMessage("Loading"); myDialog.show();
*/
}
}
Can anyone tell me how can I resolve this.
Thanks
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
Creating dialog in activity:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Converting..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Show dialog in onPreExecute()
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Dismiss dialog in onPostExecute()
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Use this code with in onPreExecute method,
private ProgressDialog dialog;
dialog = new ProgressDialog(this);
dialog.setMessage("Please Wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
easy and simple code for percentage in dialog of progress dialog
> protected void onPreExecute() {
dialog = new ProgressDialog(UploadActivity.this);
dialog.setMessage("Loading, please wait.. ");
dialog.show();
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setMessage("Loading, please wait.. "+String.valueOf(progress[0])+"%");
}

ProgressBar in asynctask is not showing on upload

Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading.
Here is my code:
public class PreviewPostActivity extends Activity {
ImageView imageView;
TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_post);
Intent intent = this.getIntent();
imageView = (ImageView)findViewById(R.id.imgPerview);
tvComment = (TextView)findViewById(R.id.txtPreviewComment);
submit = (Button)findViewById(R.id.btnPreviewSubmit);
Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
String comment = intent.getStringExtra("comment");
locationListener = (MyLocationListener)intent.getSerializableExtra("location");
String imagePath = intent.getStringExtra("imagePath");
String date = intent.getStringExtra("date");
imageView.setImageBitmap(image);
tvComment.setText(comment);
//tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);
list.add(new BasicNameValuePair("image", imagePath));
list.add(new BasicNameValuePair("comment", comment));
list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
list.add(new BasicNameValuePair("date", date));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new uploadPost().execute();
}
});
}
public void post(List<NameValuePair> nameValuePairs) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
String responseMessage = EntityUtils.toString(httpEntity);
tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
class uploadPost extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PreviewPostActivity.this);
pDialog.setMessage("Uploading post. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//post(list);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < list.size(); index++) {
if(list.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
responseMessage = EntityUtils.toString(httpEntity);
//tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
tvComment.setText(responseMessage);
pDialog.dismiss();
}
}
So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.
EDIT:
I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program.
Here is code from him:
class GetSlike extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(KlubSlikeActivity.this);
pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String id = Integer.toString(k.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klub",id));
slikeUrl = JSONAdapter.getSlike(params);
gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Only thing changed is doInBackground body...
Edited:
Dialog is display after runOnUiThread() is executed.
I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:
https://github.com/nadam/android-async-http
It could be used like the following... Set onClickHandler for the upload Button:
#Override
public void onClick(View arg0) {
try {
String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
.buildUpon()
.appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
.appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
.build().toString();
AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
RequestParams params = new RequestParams();
// this path could be retrieved from library or camera
String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
params.put("data", new File(imageFilePath));
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, httpResponseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
then add this method to your activity code:
public AsyncHttpResponseHandler createHTTPResponseHandler() {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onProgress(int position, int length) {
super.onProgress(position, length);
progressBar.setProgress(position);
progressBar.setMax(length);
}
#Override
public void onSuccess(String content) {
super.onSuccess(content);
}
#Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
#Override
public void onFinish() {
super.onFinish();
}
};
return handler;
}
Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().
doInBackGround() runs in background so you cannot access or update ui here.
To update ui you can use onPostExecute().
Your AsyncTask should be something like below. You are doing it the wrong way.
http://developer.android.com/reference/android/os/AsyncTask.html. See the topic under The 4 steps
pd= new ProgressDialog(this);
pd.setTitle("Posting data");
new PostTask().execute();
private class PostTask extends AsyncTask<VOid, Void, Void> {
protected void onPreExecute()
{//display dialog.
pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
//post request. do not update ui here. runs in background
return null;
}
protected void onPostExecute(Void param)
{
pd.dismiss();
//update ui here
}

when process dialog is being displayed, doInBackground() is not being executed

I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}

ProgressDialog is not displayed

I have an Async Task getting me some data from the web. Async Task works fine and I want a Progress Dialog Spinner to be displayed while the data is being procured from the web.The Progress Dialog Spinner never shows up. Here is my code:
public class JsonHttpParsingActivity extends ListActivity{
private String jsonResult;
private ArrayList nameArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpConnection task = new HttpConnection(this);
AsyncTask<String,Void,String> taskResult = task.execute("Some URL...");
try {
jsonResult = taskResult.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
.
More Code.....
}
}
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
m_activity = activity;
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Thanks!
Instead of write a separate method setActivity(activity) (Non UI Thread scope)
for starting ProgressDialog put the code in onPreExecute() (UI Thread) of AsyncTask, Because you are trying to show it in non UI thread.
Try this,
protected HttpConnection(Activity activity) {
m_activity = activity;
}
Override
protected void onPreExecute(String result){
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
Call progress bar from onPreExecute() function
The following code is working fine and tested:
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Try calling the AsyncTask from another method in the activity. My guess is that right now, you call it in the onCreate method of the activity. Since the activity is still building, this can give you exceptions. A thing I once tried when I had this issue, is starting the asynchronous task from the onPostCreate method of the activity.

Categories

Resources