0

Estoy obteniendo por medio de LocationManager AdressLine,Latitude y Longitude y los seteo en su respectivo textview para almacenarlos cuando se ejecuta un metodo onclick en firebaseFirestore y luego muestro los datos en un ActivityMap, teniendo en cuenta que también utilizo sharedpreferences para guardar las ultimas coordenadas, las coordenadas se envian a firebase como 3 campos String pero para mostrarlos en un mapa debo recibirlos con ayuda de la clase LatLng que almacena los datos y para asi mostrarlos en un .addMaker(etc...) mi problema en sí, es que obtengo el siguiente error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.usuario.app.myroodent, PID: 14567 java.lang.NumberFormatException: For input string: "2h7pH3xo6sgOBetaDsei6.25306028" at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306) at java.lang.Double.parseDouble(Double.java:547) at com.example.usuario.app.myroodent.MapsActivity$3.onComplete(MapsActivity.java:145) at com.google.android.gms.tasks.zzj.run(Unknown Source) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6351) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:786)

Anexo mi codigo donde cargo mi mapActivity:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,GoogleMap.OnMapClickListener {

private static final String TAG = "Mensaje:";
private static  final int defaultZoom = 10;
public FirebaseAuth mFirebaseAuth;
private FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
private GoogleMap mMap;
private ChildEventListener mChildEventListener;
private LatLngBounds PuertoTriunfo = new LatLngBounds(
        new LatLng(6.003979, -75.021556), new LatLng(6.003979, -75.021556));
DatabaseReference mUsers;
Marker marker;
ReporteEspecie reporteEspecie;
@BindView(R.id.btn_Regresar_Home)
Button btn_Regresar_Home;
@BindView(R.id.btn_Regresar_Lista)
Button btn_Regresar_Lista;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_maps);
    ButterKnife.bind(this);

    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirestore = FirebaseFirestore.getInstance();
    //////////////////////////////////////////////
    FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
            .setPersistenceEnabled(true)
            .build();
    mFirestore.setFirestoreSettings(settings);
    //////////////////////////////////////////////
    //traerDireccion();

    Locale locale = new Locale("es_419");//Convertidor de idioma local
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    this.getApplicationContext().getResources().updateConfiguration(config, null);

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    ChildEventListener mChildEventListener;
    mUsers = FirebaseDatabase.getInstance().getReference("Users/Users/"+mFirebaseAuth.getCurrentUser().getDisplayName());
    mUsers.push().setValue(marker);

    btn_Regresar_Lista.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_Regresar_Lista.setBackgroundResource(R.mipmap.icon_list_white);
            Intent intent = new Intent(getApplicationContext(),EspeciesActivity.class);
            startActivity(intent);
        }
    });

    btn_Regresar_Home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_Regresar_Home.setBackgroundResource(R.mipmap.icon_home_white);
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
        }
    });

}
private void traerDireccion() {

}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setOnMapClickListener(this);
    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    mFirestore.collection("Data").document(mFirebaseAuth.getCurrentUser().getDisplayName())
            .collection("Reportes")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {

                            //Log.d(TAG, document.getId() + " => " + document.get("latitud"));
                            //Log.d(TAG, document.getId() + " => " + document.get("longitud"));
                            String especieLectura = document.getId() + document.get("especie");
                            //String latitudLectura = document.getId() + document.get("latitud").toString();
                            //String longitudLectura = document.getId() + document.get("longitud").toString();
                            double nueva_lat = Double.parseDouble(document.getId() + document.get("latitud"));
                            double nueva_lng = Double.parseDouble(document.getId() + document.get("longitud"));

                            //UserInfo info = document.getData(document.getId());
                            //String informacionMap = ""+document.getData().get("latitud");
                            //Log.d("Hola",""+informacionMap);
                            LatLng location = new LatLng(nueva_lng,nueva_lat);

                            mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_map_white)).anchor(0.0f,1.0f).position(location).title(especieLectura));
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PuertoTriunfo.getCenter(), defaultZoom));
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });                                   //---Fin lectura Firebase

}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onMapClick(LatLng latLng) {

}

public void btn_RegresaraReportesLista(View view) {

}

public void aumentar_zoom(View view) {

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PuertoTriunfo.getCenter(), defaultZoom+2));
}

public void disminuir_zoom(View view) {
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PuertoTriunfo.getCenter(), defaultZoom-2));
}

}

2 respuestas 2

0

El problema es que estas concatenando a tu Latitud el ID del docuemnto ( es un String)

 double nueva_lat = Double.parseDouble(document.getId() + document.get("latitud"));

Deberia ser:

 double nueva_lat = Double.parseDouble(document.get("latitud"));
0

pues hombre .. el log esta muy claro..

document.getId() + document.get("latitud")

esto te devuelve

2h7pH3xo6sgOBetaDsei6.25306028

si te das cuenta..

document.getId() = 2h7pH3xo6sgOBetaDsei
document.get("latitud") = 6.25306028

claro lo estas concatenando (te devuelve un String con texto y numeros) ... al intentar parsear a Double se caera y te mandara el error

solo tendrias que parsear tu valor que viene en latitud y en longitud

  double nueva_lat = Double.parseDouble(document.get("latitud"));
  double nueva_lng = Double.parseDouble(document.get("longitud"));

ademas te recomendaría poner un try ya que los valores de latitud y longitud no siempre estarán disponibles o quizás te traiga null

   double nueva_lat  ;
   try { 
       nueva_lat = Double.parseDouble(document.get("latitud"));
       if(nueva_lat  == null) nueva_lat  = 0;
    } 
    catch (Exception e) { 
        System.out.println("Exception: " + e); 
       nueva_lat  = 0;
    } 

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.