0

Progressbar will not show when I try to access it from a thread nor update the progress. I would prefer to just have a progress spinner be displayed until the network activity is complete, and this network activity is just to post some text data to the server.This is the code I have so far, any help is appreciated thanks,

 Thread th = new Thread(){
        public void run() {

                     try {
                        sleep(5000);

                         while(cnt < 5000){
                             activty.this.runOnUiThread(new Runnable(){
                                 public void run()
                                 {
                                     ProgressBar pd = (ProgressBar)findViewById(R.id.progressBar1);
                                    pd.setVisibility(0);
                                    pd.setMax(100);

                                     pd.setProgress(cnt);
                                    cnt += 100;
                                 }
                             });
                         }
                     } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
        }

        int cnt = 100;
    };
    th.start();
    `
kabuto178
  • 3,129
  • 3
  • 40
  • 61

1 Answers1

2

This is exactly the case where you would want to use AsyncTask, which processes data in a separate thread and contains methods publishProgress and onProgressUpdate to update your UI on the UI thread.

The Processes and Threads Guide has an example of how to implement an AsyncTask as well.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Is there a way to make a generic asynctask class or will i have to make one for each network activity i have to carry out in my activity. – kabuto178 May 06 '13 at 03:47
  • 1
    @kabuto178 Try this http://stackoverflow.com/questions/14253421/how-one-interface-can-be-used-for-different-background-android-tasks/14376233#14376233, you can change the code in doInBackground based on your request, i.e get or post – Pragnani May 06 '13 at 03:48
  • @kabuto178 - `AsyncTask`'s doInBackground can take in parameters so for example if the only difference is the file you need to download, you could pass that into your AsyncTask and reuse it: `new NetworkAsyncTask().execute(urlToDownload)` for example – ianhanniballake May 06 '13 at 03:49
  • One task needs a bitmap returned and the other needs JSONObject in my case – kabuto178 May 06 '13 at 03:58
  • @kabuto178 - then it sounds like two AsyncTasks seem more appropriate. – ianhanniballake May 06 '13 at 04:01