0

I want to show progress dialog in the page layout. I implemented in the following code. Progress Dialog is not closed and it keeps running.When I click an image in the previous page it will navigate to the next layout and I want this layout to show progress dialog before all the data is downloaded from server and show it in the list of the current layout. Progress dialog is displayed and list is displayed in the background but progress dialog keeps on running and it does not get closed. I don't know where i am going wrong. Help please.

ProgressDialog pg;
String[] ar;
public void onCreate(Bundle savedInstanceState) 
{

         super.onCreate(savedInstanceState);
         setContentView(R.layout.filename);
         pg=ProgressDialog.show(this, "ABC", "Downloading .....",true);  

         Thread dt= new Thread(new Runnable() 
        {
            public void run() 
            {
                try
                {
                     String addr=Util.url;
                     URL url = new URL(urlname);
                     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                     urlConnection.setConnectTimeout(5000);             
                     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     String x = "";
                     String total = "";
                     int i=0;
                     ArrayList<String> content = new ArrayList();
                     while((x = r.readLine()) != null)
                    {
                        content.add(x);
                    }
                    in.close();
                    r.close();
                    ar= content.toArray(new String[content.size()]);

                }
                catch(Exception e1){
                     handler.sendEmptyMessage(0);
                }

            }

        });

        dt.start();
        try{
            dt.join();

        }catch(Exception e){
            handler.sendEmptyMessage(0);
        }

    try{   
        if(ar[0].toString().trim()!="")
        {
             android.view.Display display1 = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
             TableLayout tbl1 = (TableLayout)findViewById(R.id.tableLayout2);

             TableRow newRow1 = (TableRow) new TableRow(this);
             TextView txt=(TextView) new TextView(this);
             txt.setText("No");
             txt.setGravity(Gravity.LEFT);
             txt.setTextColor(Color.RED);
             txt.setTextSize(18);

             TextView txt1=(TextView) new TextView(this);
             txt1.setText("NAME");
             txt1.setTextColor(Color.RED);
             txt1.setTextSize(18);
             txt1.setGravity(3);

             TextView txt2=(TextView) new TextView(this);
             txt2.setText("DATE");

             txt2.setTextColor(Color.RED);
             txt2.setTextSize(18);
             txt.setGravity(3);

             TextView txt3=(TextView) new TextView(this);
             txt3.setText("VALUE");
             txt3.setTextColor(Color.RED);
             txt3.setTextSize(18);
             txt3.setGravity(Gravity.RIGHT);


             txt.setWidth((int)(display1.getWidth()/4));
             txt1.setWidth((int)(display1.getWidth()/4));
             txt3.setWidth((int)(display1.getWidth()/4)); 
             txt2.setWidth((int)(display1.getWidth()/4));


             newRow1.addView(txt2);
             newRow1.addView(txt);
             newRow1.addView(txt1);
             newRow1.addView(txt3);
             tbl1.addView(newRow1);

            for(int t=0;t<(ar.length);t++)
            {
            android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            TableLayout tbl = (TableLayout)findViewById(R.id.tableLayout1);
            TableRow newRow = (TableRow) new TableRow(this);
            newRow.setClickable(true);
            TextView tx=(TextView) new TextView(this);
            String temp=ar[t].toString();
            tx.setText(temp);
            tx.setTextColor(Color.WHITE);
            tx.setGravity(Gravity.LEFT);
            tx.setTextSize(15);

            t=t+1;

            TextView tx1=new TextView(this);
            tx1.setText(ar[t].toString());
            tx1.setGravity(Gravity.LEFT);
            tx1.setTextColor(Color.WHITE);
            tx1.setTextSize(15);


            t=t+1;

            TextView tx2=new TextView(this);
            tx2.setText(ar[t].toString());
            tx2.setGravity(Gravity.LEFT);
            tx2.setTextColor(Color.WHITE);
            tx2.setTextSize(15);

            t=t+1;

            TextView tx3=new TextView(this);
            tx3.setText(ar[t].toString());
            tx3.setGravity(Gravity.RIGHT);
            tx3.setTextColor(Color.WHITE);
            tx3.setTextSize(15);

            tx3.setWidth((int)(display.getWidth()/4));
            tx.setWidth((int)(display.getWidth()/4));
            tx1.setWidth((int)(display.getWidth()/4));
            tx2.setWidth((int)(display.getWidth()/4));

            newRow.addView(tx);
            newRow.addView(tx2);
            newRow.addView(tx1);
            newRow.addView(tx3);

             newRow.setId(t);

            tbl.addView(newRow);
            }

        }
    }
    catch(Exception e){
        pg.dismiss();
        handler.sendEmptyMessage(0); 
    }

}
private Handler handler = new Handler() {
    @Override 
          public void handleMessage(Message msg) {

        Toast.makeText(this,"Network not available!.... ", Toast.LENGTH_LONG).show();
}
};
ləːnə
  • 323
  • 2
  • 8
  • 22
  • write this in your catch block `runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub pg.dismiss(); handler.sendEmptyMessage(0); } });` – Nitin Misra Nov 18 '13 at 09:07
  • I think you are not closing it after completing your background process. I are only closing your answer in catch clause. – Himanshu Dudhat Nov 18 '13 at 09:07
  • Dont try in catch add the line after catch block – Kalai.G Nov 18 '13 at 09:11
  • @Nitin Misra , As you suggested, I tried. Progress Dialog keeps running – ləːnə Nov 18 '13 at 09:20
  • @Kalai.G if there is no exception occuring in your code then why are you closing it in there try this code out of catch block. `runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(pg.isShowing())pg.dismiss(); handler.sendEmptyMessage(0); } });` – Nitin Misra Nov 18 '13 at 09:22
  • @NitinMisra Thats what i have mentioned and i didnt ask question dude – Kalai.G Nov 18 '13 at 09:30
  • @NitinMisra I changed as u suggested but Progress Dialog is not displayed. – ləːnə Nov 18 '13 at 09:30

7 Answers7

1

Add this line to where ever you want to dismiss your dialog.

if(pg.isShowing())pg.dismiss();
Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
1

You are closing the ProgressDialog on Exception of Try clause

catch(Exception e){
        pg.dismiss();
        handler.sendEmptyMessage(0); 
    }

That's why without Exception this won't close

Nitesh Tiwari
  • 4,742
  • 3
  • 28
  • 46
1

I have go through your code, your progress dialog will exit if and only if your program throws an exception. put it out side of the catch block(after the catch block) following code

catch(Exception e){
    pg.dismiss();
    handler.sendEmptyMessage(0); 
}

should be changed to

catch(Exception e){
    handler.sendEmptyMessage(0); 
}finally{
    pg.dismiss();
}

if above is not working try to shift the finally block to inside the thread's run method as shown in following..

Thread dt= new Thread(new Runnable() 
    {
        public void run() 
        {
            try
            {
                 String addr=Util.url;
                 URL url = new URL(urlname);
                 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                 urlConnection.setConnectTimeout(5000);             
                 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                 BufferedReader r = new BufferedReader(new InputStreamReader(in));
                 String x = "";
                 String total = "";
                 int i=0;
                 ArrayList<String> content = new ArrayList();
                 while((x = r.readLine()) != null)
                {
                    content.add(x);
                }
                in.close();
                r.close();
                ar= content.toArray(new String[content.size()]);

            }
            catch(Exception e1){
                 handler.sendEmptyMessage(0);
            }finally{
                pg.dismiss();
            }

        }

    });
Dehan Wjiesekara
  • 3,152
  • 3
  • 32
  • 46
1

replace this :

catch(Exception e){
    pg.dismiss();
    handler.sendEmptyMessage(0); 
}

to this :

catch(Exception e){
    handler.sendEmptyMessage(0); 
}
pg.dismiss();
Erwhyn_khn
  • 27
  • 5
1

try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

Sample code:

AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

    @Override
    protected void onPreExecute() {
         //Show UI
         //Start your progress bar

         showProgress();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
         // do your bg process 
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
                      //Show UI
         //dismiss your progress bar
        hideProgress();
    }

};
task.execute((Void[])null);

Show and hide progress dialog code

public void showProgress() {
        progressDialog = ProgressDialog.show(this, "",
                "Loading. Please wait...");
        progressDialog.setCancelable(false);
    }

public void hideProgress() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
Kalai.G
  • 1,610
  • 13
  • 22
1

Use an AsyncTask and move all the network related code in doInBackground(). Show the ProgressDialog in onPreExecute() of AsyncTask and hide it in onPostExecute().

public class DownloadTask extends AsyncTask<String, Void, Response> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showProgressDialog(R.string.please_wait);
    }

    @Override
    protected Response doInBackground(String... params) {
            try {
                // Do the network stuff here
            } catch (Exception ex) { 
                // Handle exception
            }
        return result;
    }

    @Override
    protected void onPostExecute(Response result) {
        super.onPostExecute(result);
        hideProgressDialog();
        // Do the response handling here
    }
}    

private void showProgressDialog(int resId) {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.setMessage(getString(resId));
    } else {
        progressDialog = ProgressDialog.show(this, "", getString(resId), false);
    }
}

private void hideProgressDialog() {
    try {
        if (progressDialog != null && progressDialog.isShowing()) {
             progressDialog.dismiss();
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.getMessage(), ex);
    }
}

Hope it helps.

jagmohan
  • 2,052
  • 2
  • 26
  • 41
0

I finally found the solution. I preferred to go for threads since the data to fetch from the server is huge and need to be dynamically assigned to fields.

Thread thread = new Thread() {

            public void run () {
                 try
                { 
                     pg.show();
                     //long running task
                 }
                catch(){
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        //code for Update UI  after the long running  task


                        // dismiss the progress dialog on UI thread
                        pg.dismiss();

                    }
                });

            }
        };

        thread.start();
ləːnə
  • 323
  • 2
  • 8
  • 22