How to delay code execution (draw the path) for few seconds?

Yeny picture Yeny · Apr 7, 2012 · Viewed 7.9k times · Source

This is the problem about loading. My application should wait for 3 seconds and then draw path. Now, the loading message box appears within 3 seconds but the application does not wait for 3 seconds and draw immediately . Is there any problem in my coding ?

Many Thanks!!

 public void drawpath(){
       // first to do some checking
    if (sourceLat.equals("22.3366467")  && destinationLat.equals("35.68449"))
        ShowMsgDialog("Please enter the starting point and destination");
    else if (sourceLat.equals("22.3366467") )
        ShowMsgDialog("Please enter the starting point by touch");
    else if (destinationLat.equals("35.68449") )
        ShowMsgDialog("Please enter the destination by touch");

    else if (pairs != null ){
        //  go to loading function
        loading();
        // Start to draw the path
        String[] lngLat = pairs[0].split(",");

        GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

         mc = mapView.getController();
         geoPoint = startGP;
         mc.setCenter(geoPoint);
         mc.setZoom(15);
         mapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));

                ...... 
        }

in the loading() function:

private void loading() {
    progressDialog = ProgressDialog.show(this, "Showing Data..", "please wait", true, false);
    new Thread()
    { 
      public void run()
      { 
        try{ 
          sleep(3000);
        }
        catch (Exception e){
          e.printStackTrace();
        }
        finally{
            progressDialog.dismiss();    
        }
      }
    }.start(); 
}

Answer

Jeroen picture Jeroen · Nov 29, 2012

You can also do it in the following way:

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            drawPath();
        }
    }, 5000);

This won't display any lint warnings.