2

I have an application in which when user is logged-in, will download some data from the server and store them in the local database.

The problem is that I would like to show a progress bar during the downloading because it takes long time and the application seems to be block even if something hapens and the user will not see it.

Also, how to make this progressbar, £I have read some exemples with a new thread (asynchronus tasks but the problem is that I don't know how to use them.

Thank you for your help.

deepak Sharma
  • 1,641
  • 10
  • 23
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

1 Answers1

1

This is a sample code set.

 public class HttpActivity extends Activity implements OnClickListener
{
   @Override  
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ...
}
public void onClick(View v) {
    if(v.getId() == R.id.signin_get_button){
        ...
        signInGet(givenUsername, givenPassword);
    }       
}   
private void signInGet(String username, String password){

    class HttpGetAsycTask extends AsyncTask<String, Void, String>{

        private ProgressDialog dialog = ProgressDialog(HttpActivity.this, "Sign In", "Communicating with the server", true);

        @Override
        protected String doInBackground(String... params) {
            //Do your downloading Here......
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dialog.dismiss();
            ...
        }
@Override
        protected void onPreExecute(String result) {
            super.onPreExecute(result);
            dialog.show();
            ...
        }
    }

    HttpGetAsycTask httpGetAsycTask = new HttpGetAsycTask();
    httpGetAsycTask.doInBackground(username, password);
}
}
deepak Sharma
  • 1,641
  • 10
  • 23
AnujAroshA
  • 4,623
  • 8
  • 56
  • 99
  • Thank you @Anuja, but where to put my downloadingData code and where the progressbar ? – Milos Cuculovic Feb 17 '12 at 14:19
  • @Ana You put your downloading data in the doInBackground method. As you can see in my example code ProgressDialog starts when we call this inner class. You can dismiss the ProgressDiolog after the downloads complete, which means in the onPostExecute method. An example code for using AsyncTask for connecting with a server is here (http://anujarosha.wordpress.com/2012/01/27/handling-http-post-method-in-android/) – AnujAroshA Feb 17 '12 at 14:56
  • I am trying something but I have a problem with the Can't create handler inside thread that has not called Looper.prepare() – Milos Cuculovic Feb 17 '12 at 15:02
  • And how can I know when the downloading is finished? – Milos Cuculovic Feb 17 '12 at 15:05
  • @Ana if you are using AsyncTask, you no need to use Handler class. – AnujAroshA Feb 17 '12 at 15:11
  • How to use Handler class? Thank you. – Milos Cuculovic Feb 17 '12 at 15:38