2

how can I show a loading image when this code running ?

HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.google.com"); try { HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; StringBuilder str = new StringBuilder(); while((line = reader.readLine()) != null) { str.append(line); } objwebview.loadData(str.toString(), "text/html", "UTF-8"); } catch(Exception e) { e.printStackTrace(); objwebview.loadData(e.toString(), "text/html", "UTF-8"); } 
1
  • use ProgressDialog for loading dialog, Before you hit the server, start the dialog and after getting response, attach it to the main thread and dismiss the dialog Commented Dec 8, 2012 at 7:47

1 Answer 1

3

Change your code as for showing loading bar using AsyncTask

private class Getdataasynktask extends AsyncTask<String, Void, String> { ProgressDialog progressDialog = new ProgressDialog(context); @Override protected void onPostExecute(String result) { // show loaging bar here progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setProgress(0); // set percentage completed to 0% progressDialog.show(); } @Override protected String doInBackground(String... params) { String strdata= getdatafromserver(); return strdata; } @Override protected void onPreExecute(String result) { objwebview.loadData(result.toString(), "text/html", "UTF-8"); // dismiss progress bar here progressDialog.dismiss(); } public String getdatafromserver(){ String line; objwebview.loadData(str.toString(), "text/html", "UTF-8"); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.google.com"); try { HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder str = new StringBuilder(); while((line = reader.readLine()) != null) { str.append(line); } } catch(Exception e) { e.printStackTrace(); line=e.toString(); } return line; } } 

for executing this AsyncTask from UI Thread use

new Getdataasynktask().execute(""); 

and you can also use onProgressUpdate and publishProgress for showing loading bar using AsyncTask and publishing results to Ui thread . for more info see

http://developer.android.com/reference/android/os/AsyncTask.html

Sign up to request clarification or add additional context in comments.

1 Comment

It seems onPreExecute() and onPostExecute() are mixed up (i.e, progressDialog should be set up in onPreExecute() and dismissed in onPostExecute())

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.