0

I am trying to build an app that uses a map on which i am pinning some markers to the scope of saving their coordinates. When i click on a marker i am saving some details about those coordinates and then go back to the map to add other coordinates. The issue is that when i return, the map recreates deleting the saved marker. I have tried many solutions already found related to this subject but when i press the return button the app crashes. Can you please help me with a solution on saving the markers and the fragment state?

Edit: app crashes even with other solution for saving the state that i have tried and definitely tea line 32 it id not the issue.

MapsActivity:

 @Override
public void onMapReady(GoogleMap googleMap) {
    // Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "onMapReady: map is ready");
    mMap = googleMap;
    mMap.setOnMarkerDragListener(this);
    mMap.setOnMapLongClickListener(this);


    if (mLocationPermissionsGranted) {
        getDeviceLocation();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);



    }
}

    @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    getLocationPermission();
    initMap();
    if(savedInstanceState != null) {
        CameraPosition savedCameraPosition = savedInstanceState.getParcelable("camera");
        if (savedCameraPosition != null) {
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(savedCameraPosition));
        }
    }
}

private void getDeviceLocation() {
    Log.d(TAG, "getDeviceLocation: getting the devices current location");

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    try {
        if (mLocationPermissionsGranted) {

            final Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "onComplete: found location!");
                        Location currentLocation = (Location) task.getResult();
                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                DEFAULT_ZOOM);


                    } else {
                        Log.d(TAG, "onComplete: current location is null");
                        Toast.makeText(MapsActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    } catch (SecurityException e) {
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
    }
}

private void moveCamera(LatLng latLng, float zoom) {
    Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));



}

public void onMapLongClick(LatLng latLng) {

    mMap.clear();
    MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(latLng.toString());
    markerOptions.draggable(true);
    mMap.addMarker(markerOptions);
    mMap.setOnMarkerClickListener(this);

    latlngNew = latLng;

    LatLng latlngNew;


}


private void initMap() {
    Log.d(TAG, "initMap: initializing map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(MapsActivity.this);



}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (mMap != null) {
        outState.putParcelable("camera", mMap.getCameraPosition());
    }
}
private void getLocationPermission() {
    Log.d(TAG, "getLocationPermission: getting location permissions");
    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionsGranted = true;
            initMap();
        } else {
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    } else {
        ActivityCompat.requestPermissions(this,
                permissions,
                LOCATION_PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.d(TAG, "onRequestPermissionsResult: called.");
    mLocationPermissionsGranted = false;

    switch (requestCode) {
        case LOCATION_PERMISSION_REQUEST_CODE: {
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        mLocationPermissionsGranted = false;
                        Log.d(TAG, "onRequestPermissionsResult: permission failed");
                        return;
                    }
                }
                Log.d(TAG, "onRequestPermissionsResult: permission granted");
                mLocationPermissionsGranted = true;
                //initialize our map
                initMap();
            }
        }
    }
}

public void changetype(View view) {
    if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
        mMap.setMapType(MAP_TYPE_SATELLITE);
    } else
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);


}

@Override
public void onMarkerDragStart(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(0.5f);
}

@Override
public void onMarkerDrag(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(0.5f);
}

@Override
public void onMarkerDragEnd(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(1.0f);

}

@Override
public boolean onMarkerClick(Marker marker) {

    openDialog();
    return false;
}

public void openDialog() {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle(R.string.default_info_title);
    dialog.show();
    Button bt_da = (Button)dialog.findViewById(R.id.dialog_ok);
    Button bt_nu = (Button)dialog.findViewById(R.id.dialog_cancel);

    bt_da.setOnClickListener(this);
    bt_nu.setOnClickListener(this);
    bt_nu.setOnClickListener(new View.OnClickListener()
                             {
                                 @Override
                                 public void onClick(View v) {
                                     dialog.dismiss();

                                 }
                             }

    );
    bt_da.setOnClickListener(new View.OnClickListener()

                             {
                                 @Override
                                 public void onClick(View v) {
                                     Intent intent=new Intent(MapsActivity.this,MainActivity.class);
                                     intent.putExtra("markerLat", latlngNew.latitude);
                                     intent.putExtra("markerLong", latlngNew.longitude);
                                     startActivity(intent);
                                 }
                             }
    );

}

@Override
public void onClick(View v) {

}

@Override
public void onMapClick(LatLng latLng) {



}

@Override
public void onCameraMove() {

}

And the error when pressing Return :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.c.b(com.google.android.gms.maps.a)' on a null object reference
    at com.example.raluca.geoloc.feature.MapsActivity.onCreate(Unknown Source:32)
    at android.app.Activity.performCreate(Activity.java:6975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2775)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2897) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1598) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:251) 
    at android.app.ActivityThread.main(ActivityThread.java:6572) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

On line 32 having this:

import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
  • where's your onmapready? you should only use map instance given in `onMapReady` – Pavneet_Singh Aug 01 '18 at 18:29
  • I have add it now. i had it in the code, just did not see it. Sorry – Raluca Vasiloiu Aug 01 '18 at 18:33
  • Miss, it's coming from `MapsActivity.onCreate line 32` mean something is not initialised and you are using it, you can debug your app and see? – Pavneet_Singh Aug 01 '18 at 18:39
  • I have added 2 Toasts for every if from onCreate to see where the Null gets generated and now the error have moved to line 33 which is an empty line. As i am a beginner i do not know exactly where the issue is and i am just trying to put together what i found here with my minimum knowledge. If you have any idea what can generate that please help me. – Raluca Vasiloiu Aug 01 '18 at 19:12
  • `error move to empty loc` did you rebuild the app and installed it again ? seems like you are running old app? – Pavneet_Singh Aug 01 '18 at 19:27
  • I did now and it does not open the map anymore. I removed the code where i try to save the state, still some library issues. – Raluca Vasiloiu Aug 01 '18 at 20:00
  • is there any information available in logcat, usually you much see some logs if there's is any issue with map loading, pay attention to logcat and set the break point and run your app in debug mode to see the flow of control – Pavneet_Singh Aug 01 '18 at 20:46
  • Thank you i will try again, but probably i am not saving the state correctly and i am meesing something. I will try to solve the issue and then come back on researching how to save at least the markers on the map. Thank you once again. – Raluca Vasiloiu Aug 01 '18 at 20:57
  • No need plus problem is still there, is there any possibility that your activity is recreated somewhere after leaving the map screen(like due to orientation change etc), seems like your map is null and you are trying to add marker or something in oncreate (only happens when activity is recreated) , `oncreate` method is only executed when activity is destroyed (orientation change, back button or [thanos](https://en.wikipedia.org/wiki/Thanos) did it ). – Pavneet_Singh Aug 01 '18 at 21:14
  • you can post a question with exact details (logcat + plus lifecycle details ,activity recreation etc) and link to this post if issue is not resolved and use `Log.d("tags","msg");` instead of toasts to see your info in logcat panel, Good Luck! – Pavneet_Singh Aug 01 '18 at 21:17

0 Answers0