0

I have activity with a button.When button is clicked,a new activity starts and in this activity , various data fetch from web.But when I click the button , first activity holds on for a while and after 3-4 seconds second activity starts with ready datas.Apparently,before second activity is visible,app tries to fetch data.But firstly,I want second activity is visible to user, after that fetching data must start. I examined activity lifecycle and replaced fetching to onStart() but not working

 @Override
 protected void onStart() {
          super.onStart();
          //Fetch data
 }

How can I do that ?

Here is my all code (just second activity) :

public class GuzergahActivity extends android.support.v4.app.FragmentActivity{

      private GoogleMap map;
      private GuzergahOverlay overlay;
      private WebView webview;
      private ImageView imageview;
      private ProgressDialog dialog;
      private int flag;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        overridePendingTransition(0, 0);
        setContentView(R.layout.guzergah);
        flag=this.getIntent().getExtras().getInt("flag");
        setUpMapIfNeeded();
        setUpView();
      }

      @Override
      protected void onResume() {
          super.onResume();
          setUpMapIfNeeded();
      }

      @Override 
      protected void onDestroy() {
        if (dialog!=null) {
            dialog.dismiss();
        }
        super.onDestroy();
      }

      private void setUpMapIfNeeded() {
            // Do a null check to confirm that we have not already instantiated the map.
            if (map == null) {
                map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.guzergah_fragment)).getMap();
                if(map!=null){
                    setUpMap();
                }
            }
      }

    private void setUpMap(){

         try {
            String result=new MyNewTask().execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         overlay.setOverlay(map);
         map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.910526,32.804435),15));
         map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
    }


    private void setUpView() {
           //Binding imageview,webview...and setting up their features
    }

    private class MyNewTask extends AsyncTask<String,Integer,String> 
    {
        @Override
        protected void onPreExecute()
        {

            dialog= new ProgressDialog(GuzergahActivity.this);
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.setMessage("Downloading! Please wait...!");
            dialog.show();

        }


        @Override
        protected String doInBackground(String... params)
        {
            /* Fetching data is in this class - GuzergahOverlay*/ 
            overlay =  new GuzergahOverlay(flag);

            return "Done";

      }

        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            Log.i("result","" +result);
            if(result!=null){
                dialog.dismiss();
            }
        }

    } //end MyNewTask
}



public class GuzergahOverlay {

private MarkerOptions beytepe_kampusu;
private MarkerOptions sihhiye_kampusu;
private ArrayList<PolylineOptions> lines;
private ArrayList<MarkerOptions> stops;

public GuzergahOverlay(int mode) {
    beytepe_kampusu=new MarkerOptions().position(new LatLng(39.87159,32.735435)).title("Hacettepe Üniversitesi Beytepe Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_beytepe));
    sihhiye_kampusu=new MarkerOptions().position(new LatLng(39.931599,32.862365)).title("Hacettepe Üniversitesi Sıhhıye Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_sihhiye));
    getLinesAndStops(mode); //Here is fetching geopoint and preparing lines and stops arraylists
}

private void getLinesAndStops(int mode) {

    // Fetching data from Parse.com
            // Fillinp up lines and stops arraylists
}




public void setOverlay(GoogleMap map){
    map.addMarker(beytepe_kampusu);
    map.addMarker(sihhiye_kampusu);
    for(PolylineOptions polyline : lines){
        map.addPolyline(polyline);
    }
    for(MarkerOptions marker : stops){
        map.addMarker(marker);
    }
}
}

With above code , when I click button , first activity holds on for a while and second activity is visible when fetching data finished.Progress dialog is visible for just a few milisecond

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sedat KURT
  • 478
  • 4
  • 9
  • 20

2 Answers2

1

You should move the data fetching method into an AsyncTask. You should never fetch data from a remote source on the UI thread. If you move that operation into a background thread in this way, the UI will have a higher priority, and should load quickly, while still allowing your asynchronous task to complete. You can even start the task in onCreate or onStart, and you should see better performance.

mattgmg1990
  • 5,576
  • 4
  • 21
  • 26
  • Thanks for reply , I editted my question with codes.Can you look again ? – Sedat KURT Sep 23 '13 at 17:48
  • @SedatKURT Your edit looks like you're heading in the right direction. What is the problem now? – mattgmg1990 Sep 23 '13 at 18:23
  • I said at the end of question "With above code , when I click button , first activity holds on for a while and second activity is visible when fetching data finished.Progress dialog is visible for just a few milisecond".This is my problem :( – Sedat KURT Sep 23 '13 at 18:27
1

Sounds as if you are running all your code in the UI thread. Would be nice with more code to be able to give a better example.

In your second activity:

    private class BackgroundTask extends AsyncTask<Void, Void, Void> {

    // Before running code in separate thread
    @Override
    protected void onPreExecute() {
        // setup loading dialog
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // do long running code
        return null;
    }

    // after executing the code in the thread
    @Override
    protected void onPostExecute(Void arg) {
        // dismiss your dialog

    }

}

And inside onCreate:

new BackgroundTask().execute();

Edit:

Now that I have seen your code I would suggest you try something like this:

    private void setUpMap(){
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new      LatLng(39.910526,32.804435),15));
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                try {
                    String result = new MyNewTask().execute();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                /*
                 * you should move this call to onPostExecute
                 * then you will not need to call execute().get() 
                 * which takes away the advantage of AsyncTask
                 * as it then is run on UI thread
                 */

                overlay.setOverlay(map);
            }
        }, 2000);

    }

Setting up the map is an UI heavy task, so in my experience it looks nicer to wait a bit before loading markers etc. Furthermore this should enable the dialog to properly show before it is dismissed.

cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • True. All calls to add markers to map and the like must be on UI thread, could be in onPostExcecute though. Think you should move super.onPostExecute(result); to the bottom of the method. – cYrixmorten Sep 23 '13 at 18:43
  • I have updated my answer so that you hopefully get the behaviour that you are looking for – cYrixmorten Sep 23 '13 at 19:10
  • It gives me compile error "The left-hand side of an assignment must be a variable" for new Handler.....code.I typed Handler hnd= new Handler....... but nothing change – Sedat KURT Sep 23 '13 at 23:10
  • Sorry, something must have slipped when I entered the code, try now. – cYrixmorten Sep 23 '13 at 23:17
  • Now , Acitivity opens instantly,this is good but ProgressDialog do not appear.it becomes visible for a very very short time just before adding lines and markers.No matter what I appreciate your work.Thanks – Sedat KURT Sep 23 '13 at 23:39
  • Im happy I could help. Guess the process is just fast, leaving the dialog dismissed quickly? – cYrixmorten Sep 24 '13 at 00:12