0

Tengo algunos problemas con la biblioteca osmdroid. Mi aplicación contiene un bottom navigation view 4 fragmentos y en uno de ellos estoy tratando de agregar el mapa, pero siempre hay una excepción y no sé cómo solucionarlo. Traté de implementar la biblioteca como en su sitio github https://github.com/osmdroid/osmdroid . Funciona si estoy usando una actividad normal, pero sería genial, si también funciona en fragmentos.

public class MainActivity extends AppCompatActivity {

private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1;

private MapView map = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Context ctx = getApplicationContext();
    Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));

    setContentView(R.layout.activity_main);

    MapView mapa = (MapView) findViewById(R.id.map);
    map.setTileSource(TileSourceFactory.MAPNIK);


    BottomNavigationView navView = findViewById(R.id.nav_view);

    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_rutas, R.id.navigation_historial, R.id.navigation_perfil)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);


    requestPermissionsIfNecessary(new String[]{
            // if you need to show the current location, uncomment the line below
            Manifest.permission.ACCESS_FINE_LOCATION,
            // WRITE_EXTERNAL_STORAGE is required in order to show the map
            Manifest.permission.WRITE_EXTERNAL_STORAGE


    });


}

@Override
public void onResume() {
    super.onResume();
    //this will refresh the osmdroid configuration on resuming.
    //if you make changes to the configuration, use
    //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
    map.onResume(); //needed for compass, my location overlays, v6.0.0 and up

}

@Override
public void onPause() {
    super.onPause();
    //this will refresh the osmdroid configuration on resuming.
    //if you make changes to the configuration, use
    //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    //Configuration.getInstance().save(this, prefs);
    map.onPause();  //needed for compass, my location overlays, v6.0.0 and up
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    ArrayList<String> permissionsToRequest = new ArrayList<>();
    for (int i = 0; i < grantResults.length; i++) {
        permissionsToRequest.add(permissions[i]);
    }
    if (permissionsToRequest.size() > 0) {
        ActivityCompat.requestPermissions(
                this,
                permissionsToRequest.toArray(new String[0]),
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

private void requestPermissionsIfNecessary(String[] permissions) {
    ArrayList<String> permissionsToRequest = new ArrayList<>();
    for (String permission : permissions) {
        if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            permissionsToRequest.add(permission);
        }
    }
    if (permissionsToRequest.size() > 0) {
        ActivityCompat.requestPermissions(
                this,
                permissionsToRequest.toArray(new String[0]),
                REQUEST_PERMISSIONS_REQUEST_CODE);

    }


    map.setMultiTouchControls(true);

    GeoPoint startPoint = new GeoPoint(7.9007, -72.4790);
    IMapController mapController = map.getController();
    mapController.setZoom(9);
    mapController.setCenter(startPoint);

    Marker startMarker = new Marker(map);
    startMarker.setPosition(startPoint);
    startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
    map.getOverlays().add(startMarker);

    startMarker.setIcon(getResources().getDrawable(R.drawable.logo));
    startMarker.setTitle("Start point");
}

error en el logcat

Process: com.example.busetapp, PID: 6778 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.busetapp/com.example.busetapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setTileSource(org.osmdroid.tileprovider.tilesource.ITileSource)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setTileSource(org.osmdroid.tileprovider.tilesource.ITileSource)' on a null object reference at com.example.busetapp.MainActivity.onCreate(MainActivity.java:47) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  05-24 00:19:04.770 6778-6822/com.example.busetapp E/FirebaseCrash: Unable to parse Json response string to get message: No value for crashes

1 respuesta 1

0

Revisando tu còdigo este problema se debe seguramente a que dentro del layout activity_main.xml no se encuentra el mapa con id map, por esa razòn cuando deseas usar el mapa obtienes el error.

setContentView(R.layout.activity_main);

MapView mapa = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);

Debes asegura que dentro del del layout activity_main.xml se encuentra el mapa con id map.

1
  • muchas gracias pude solucionarlo ya no muestra el error , pero al pasar el id map de mi fragmen_home.xml a activity_main.xml el mapa no se visualiza y perdi la funcion de bottom navigation view de moverme entre mis fragments, solo se visualiza el fragmen_home.xml, como puedo solucionarlo? gracias por su atencion el 25 may. 2020 a las 1:02

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.