Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8637653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T10:31:43+00:00 2026-06-12T10:31:43+00:00

following code , it crashes when I uncomment the ‘list etc and add overlay

  • 0

following code , it crashes when I uncomment the ‘list etc and add overlay when I add the overlay to list it crashes. I can add a single overlay icon in the ‘oncreate and it doesn’t crash, but adding it to the ‘onlocationchanged’ it crashes

 public class MainActivity extends MapActivity implements LocationListener {


MyLocationOverlay myLocationOverlay;

public MapView mapView;
MapController mc;

OverlayItem overlayitem;
List<Overlay> mapOverlays;
HelloItemizedOverlay itemizedoverlay;
GeoPoint myLocationGeoPoint;



private MockGpsProvider mMockGpsProviderTask = null;
//mMockGpsProviderTask = new MockGpsProvider();

/* This method is called when use position will get changed */
public void onLocationChanged(Location location) {
    GeoPoint myLocationGeoPoint = new GeoPoint((int)(location.getLatitude() * 1e6) , (int)(location.getLongitude() * 1e6));

//  Toast.makeText(this, "changinglocation", Toast.LENGTH_SHORT).show();
    String message = String.format(
            "New Location \n Longitude: %1$s \n Latitude: %2$s",
            (int)(location.getLongitude()), (int)(location.getLatitude())
    );
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
   // mc.setCenter(myLocationGeoPoint);
   mc.animateTo(myLocationGeoPoint);        
  // mc.setZoom(11);
    //}
 //     mapOverlays = mapView.getOverlays();
 // Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);

  overlayitem = new OverlayItem(myLocationGeoPoint, "Hola, Mundo!", "I'm in Mexico City!");
   itemizedoverlay.addOverlay(overlayitem);
   mapOverlays.add(itemizedoverlay);

}



public void onProviderDisabled(String provider) {
    Toast.makeText(this, "No mock data mofo", Toast.LENGTH_SHORT).show();

}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
int test()
{
    int i1=getIntent().getIntExtra("key", -1);
    return(i1);
}

@Override
protected boolean isRouteDisplayed() {
    return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mc = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mc.setZoom(19);

 List<Overlay> mapOverlays = mapView.getOverlays();
 Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
 HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);

 GeoPoint point = new GeoPoint(19240000,-99120000);
 //GeoPoint point = new GeoPoint(19240000,test());

 //GeoPoint point = new GeoPoint(19240000,message);
 OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
 itemizedoverlay.addOverlay(overlayitem);
 mapOverlays.add(itemizedoverlay);

//   LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//   Criteria criteria = new Criteria();
//  criteria.setAccuracy( Criteria.ACCURACY_COARSE );
//  String provider = lm.getBestProvider( criteria, true );

//  if ( provider == null ) {
//      Toast.makeText(this, "No mock data mofo", Toast.LENGTH_SHORT).show();

//  }

       /** Setup GPS. */
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
        /// use real GPS provider if enabled on the device
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    else if(!locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
        // otherwise enable the mock GPS provider
        locationManager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false, false,
                false, false, true, false, false, 0, 5);
        locationManager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER, true);
        Toast.makeText(this, "mock data enabled mofo", Toast.LENGTH_SHORT).show();
    }  
    if(locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
        locationManager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, this);

        /** Load mock GPS data from file and create mock GPS provider. */
        try {
            // create a list of Strings that can dynamically grow
            List<String> data = new ArrayList<String>();

            /** read a CSV file containing WGS84 coordinates from the 'assets' folder
             * (The website http://www.gpsies.com offers downloadable tracks. Select
             * a track and download it as a CSV file. Then add it to your assets folder.)
             */         
            InputStream is = getAssets().open("mock_gps_data.csv");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            // add each line in the file to the list
            String line = null;
            while ((line = reader.readLine()) != null) {
                data.add(line);
            }

            // convert to a simple array so we can pass it to the AsyncTask
            String[] coordinates = new String[data.size()];
            data.toArray(coordinates);

            // create new AsyncTask and pass the list of GPS coordinates
            mMockGpsProviderTask = new MockGpsProvider();
            mMockGpsProviderTask.execute(coordinates);
        } 
        catch (Exception e) {}
    }




        }
private class MockGpsProvider extends AsyncTask<String, Integer, Void> {
    public static final String LOG_TAG = "GpsMockProvider";
    public static final String GPS_MOCK_PROVIDER = "GpsMockProvider";

    /** Keeps track of the currently processed coordinate. */
    public Integer index = 0;

    @Override
    protected Void doInBackground(String... data) {         
        // process data
        for (String str : data) {
            // skip data if needed (see the Activity's savedInstanceState functionality)
            if(index < 5) {
                index++;
                continue;
            }               

            // let UI Thread know which coordinate we are processing
            publishProgress(index);

            // retrieve data from the current line of text
            Double latitude = null;
            Double longitude = null;
            Double altitude= null;
            try {
                String[] parts = str.split(",");
                latitude = Double.valueOf(parts[0]);
                longitude = Double.valueOf(parts[1]);
                altitude = Double.valueOf(parts[2]);
            }
            catch(NullPointerException e) { break; }        // no data available
            catch(Exception e) { continue; }                // empty or invalid line

            // translate to actual GPS location
            Location location = new Location(GPS_MOCK_PROVIDER);
            location.setLatitude(latitude);
            location.setLongitude(longitude);
            location.setAltitude(altitude);
            location.setTime(System.currentTimeMillis());

            // show debug message in log
            Log.d(LOG_TAG, location.toString());

            // provide the new location
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER, location);

            // sleep for a while before providing next location
            try {
                Thread.sleep(200);

                // gracefully handle Thread interruption (important!)
                if(Thread.currentThread().isInterrupted())
                    throw new InterruptedException("");
            } catch (InterruptedException e) {
                break;
            }

            // keep track of processed locations
            index++;
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        Log.d(LOG_TAG, "onProgressUpdate():"+values[0]);
        mMockGpsProviderIndex = values[0];
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T10:31:44+00:00Added an answer on June 12, 2026 at 10:31 am

    You would declare all the variables used inside onLocationChanged() as global variables to avoid reallocating of memory and errors, the reason it works in onCreate() method is that it executes one time only while onLocationChanged() executes several times whenever the location is changed.

    EDIT:

    You didn’t add any request for location updates in your onCreate() method. Please see this link to follow best strategies of getting location updates.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using following code to add tabs on a tabHost but crashes on
The following code crashes and burns and I don't understand why: DateTime dt =
I wanted to know why the following code crashes. int main( ) { int
When I run the following Code it crashes at the last line. I don't
I have discovered that the following PHP code crashes when it runs on a
The following code crashes on the second Pop() call. I'm a novice with C
I am using following code. When the query crashes, it is not displaying the
The following code crashes while sorting the vector. #include<cstdio> #include<vector> #include<algorithm> using namespace std;
The following code works on the simulator but crashes the device because img is
While running following code, my program crashes unexpectedly! #include<stdio.h> #include<string.h> int main(){ char *str

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.