Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Destory MapView when tab selected

I've having trouble destroying a map before it's completely loaded. I have tabs and I need to destroy the map when the user clicks a new tab. I stop the thread the map is using but the onResume() is stilled called with null as a sources. Makes sense but I don't know how to stop the map from getting loaded.

3 Answers

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Would you mind posting code in here for us to take a look at? I guess it depends on how and where you are loading the map.

Fragment {
MapView m;
private GoogleMap googleMap;

public void stopThreads() {
        getBlogPostsTask.cancel(true);
        mTimer.cancel();
        m.clearAnimation();
        onStop();
    }

onCreateView() {
   m = (MapView) rootView.findViewById(R.id.mapView);
        m.onCreate(savedInstanceState);

        getBlogPostsTask = new TheTask();
        getBlogPostsTask.execute();

try {
            MapsInitializer.initialize(getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }

googleMap = m.getMap();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

        mTimer = new Timer();

        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                    new TheTask().execute();
                 }
            }, 0, REFRESH_TIME);

}


private class TheTask extends AsyncTask<String,Void,Bitmap> {
protected Bitmap doInBackground(String... arg0) {
    lat = Double.parseDouble(parts[1]);
                    lon = Double.parseDouble(parts[2]);
}
}

protected void onPostExecute(Bitmap result) {
    m.onResume();
    googleMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Surge Cam"));
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15));
}
Ben Jakuben
Ben Jakuben
Treehouse Teacher

Is the onResume() that you mentioned the one in onPostExecute()? If you cancel the async task, like in this StackOverflow question, then it should avoid calling onPostExecute() and instead call onCancelled() (which you can choose to override or just ignore).

Seems like I've tried everything under the sun lol.

public class SurgeActivity extends Fragment {

    MapView m;
    private GoogleMap googleMap;
    protected ImageView iv;
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    protected String location;
    public static final String TAG = SurgeActivity.class.getSimpleName();
    protected double lat;
    protected double lon;
    protected int REFRESH_TIME = 30000;
    protected TheTask getBlogPostsTask;
    protected Timer mTimer;

    public void stopThreads() {
        getBlogPostsTask.cancel(true);
        mTimer.cancel();
        m.clearAnimation();
        onStop();
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.mapdemo,
                container, false);
        iv = (ImageView) rootView.findViewById(R.id.imageView1);

        m = (MapView) rootView.findViewById(R.id.mapView);
        m.onCreate(savedInstanceState);

        getBlogPostsTask = new TheTask();
        getBlogPostsTask.execute();




        try {
            MapsInitializer.initialize(getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }

        googleMap = m.getMap();

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

        mTimer = new Timer();

        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                    new TheTask().execute();
                 }
            }, 0, REFRESH_TIME);

//      final Handler handler = new Handler();
//      final Runnable r = new Runnable()
//      {
//          public void run() 
//          {
//              new TheTask().execute();
//              //handler.postDelayed(this, 30000);
//          }
//      };
//
//      handler.postDelayed(r, 1000);



        return rootView;
    }

//  @Override
//      public void onResume() {
//          super.onResume();
//          m.onResume();
//      }

        @Override
        public void onPause() {
            super.onPause();
            m.onPause();
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            m.onDestroy();
        }
        @Override
        public void onLowMemory() {
            super.onLowMemory();
            m.onLowMemory();
        }

        @Override
        public void onStop()
        {
            super.onStop();

            if (m.getChildCount() > 0 && m.getChildAt(0) instanceof MapView)
                m.removeViewAt(0);
        }


    private class TheTask extends AsyncTask<String,Void,Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected void onCancelled() {
            //if (m.getChildCount() > 0 && m.getChildAt(0) instanceof MapView)
                m.removeViewAt(0);
                mTimer.cancel();
                m.clearAnimation();
                //this.cancel(true);
        }

        @Override
        protected Bitmap doInBackground(String... arg0) {
            Bitmap mIcon11 = null;
            try {
                String urldisplay = image;
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);

             // Create a URL for the desired page
                URL url = new URL(textfile);

                // Read all the text returned by the server
                BufferedReader readin = new BufferedReader(new InputStreamReader(url.openStream()));
                String str;
                while ((str = readin.readLine()) != null) {
                    // str is one line of text; readLine() strips the newline character(s)
                    String[] parts = str.split("\\|");
                    lat = Double.parseDouble(parts[1]);
                    lon = Double.parseDouble(parts[2]);
                }
                in.close();
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        @Override
        protected void onPostExecute(Bitmap result) {           
            iv.setImageBitmap(result);

            m.onResume();

            googleMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Surge Cam"));

            // Move the camera instantly to hamburg with a zoom of 15.
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15));

            Log.i(TAG, "w");
        }

    }
}

I know that's a lot of pseudo code. I can send you the real files if you want.