onMapReady recibir nula LatLng

votos
0

Tengo un problema con onMapReady . Cuando paso una dirección como esta:

LatLng myAddressCoordinates = getLocationFromAddress(Piazza Ferretto Mestre);

Tanto fina mapa y marcador de trabajo, pero cuando paso la dirección de la lectura de un TextView:

LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());

Lanzo esta excepción:

java.lang.IllegalArgumentException: latlng cannot be null - a position is required.
        at com.google.android.gms.maps.model.MarkerOptions.position(Unknown Source:6)
        at com.example.alex.alfa0.schedaIntervento.onMapReady(schedaIntervento.java:199)
        at com.google.android.gms.maps.zzaj.zza(Unknown Source:7)
        at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source:38)
        at android.os.Binder.transact(Binder.java:627)
        at gl.b(:com.google.android.gms.DynamiteModulesB@11580470:20)
        at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB@11580470:5)
        at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB@11580470:5)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Línea 199:

mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));

Mi método getLocationFromAddress:

public LatLng getLocationFromAddress(String strAddress) {
        /**
         * A class for handling geocoding and reverse geocoding.
         * Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.
         * Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.
         * The amount of detail in a reverse geocoded location description may vary,
         * for example one might contain the full street address of the closest building,
         * while another might contain only a city name and postal code.
         *
         * See more at: https://developer.android.com/reference/android/location/Geocoder.html
         */
        Geocoder coder = new Geocoder(this);

        //A list because of getFromLocationName will return a list of address depending on how many result I want
        List<Address> address;
        LatLng p1 = null;

        try {
            /**
             * List<Address> getFromLocationName (String locationName, int maxResults)             *
             * | locationName | String: |           a user-supplied description of a location                      |
             * | maxResults   |   int:  |max number of results to return. Smaller numbers (1 to 5) are recommended |
             * See more at: https://developer.android.com/reference/android/location/Geocoder.html
             */
            address = coder.getFromLocationName(strAddress, 2);
            if (address == null) {
                return null;
            }            //I take just the first result even if I've got list of 5 different LAT;LNG results
            Address location = address.get(0);
            location.getLatitude();
            location.getLongitude();
            p1 = new LatLng(location.getLatitude(), location.getLongitude());
            return p1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return p1;
    }

código de clase completo:

public class schedaIntervento extends AppCompatActivity implements OnMapReadyCallback {
    TextView TVNome, TVID, TVNomeP, TVCognome, TVVia, TVNumero, TVCitta, TVCap, TVChiamata, TVOperatore, TVCodice, TVData, TVStringa;
    String Nomee, Indirizzo;
    GoogleMap mapView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheda_intervento);
        TVNome = findViewById(R.id.TVNome);
        TVID =  findViewById(R.id.TVID);
        TVNomeP = findViewById(R.id.TVNomeP);
        TVCognome = findViewById(R.id.TVCognome);
        TVVia=findViewById(R.id.TVVia);
        TVNumero = findViewById(R.id.TVNumero);
        TVCitta = findViewById(R.id.TVCitta);
        TVCap = findViewById(R.id.TVCap);
        TVChiamata = findViewById(R.id.TVChiamata);
        TVOperatore = findViewById(R.id.TVOperatore);
        TVCodice = findViewById(R.id.TVCodice);
        TVData = findViewById(R.id.TVData);
        TVStringa = findViewById(R.id.TVStringa);
        Nomee = getUsername();
        String url = myurlforapi;
        getJSON(url);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapView);
        mapFragment.getMapAsync( this);
    }

    private String getUsername() {
        Intent i = getIntent();
        String j = i.getStringExtra(Username);
        TVNome.setText(j);
        return j;
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    loadIntoTextView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod(POST);
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    Uri.Builder builder = new Uri.Builder()
                            .appendQueryParameter(Username, Nomee);
                    String query = builder.build().getEncodedQuery();
                    OutputStream os = con.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(os, UTF-8));
                    writer.write(query);
                    writer.flush();
                    writer.close();
                    os.close();
                    con.connect();

                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;

                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + \n);
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

    private void loadIntoTextView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            TVNomeP.setText(obj.getString(Nome));
            TVCognome.setText(obj.getString(Cognome));
            TVVia.setText(obj.getString(Via));
            TVNumero.setText(obj.getString(Numero));
            TVCitta.setText(obj.getString(Citta));
            TVCap.setText(obj.getString(CAP));
            TVChiamata.setText(obj.getString(Motivo_chiamata));
            TVOperatore.setText(obj.getString(Operatore));
            TVCodice.setText(obj.getString(codice));
            TVData.setText(obj.getString(Data_di_nascita));
            Indirizzo = Via  + TVVia.getText().toString() +   + TVNumero.getText().toString() +   + TVCitta.getText().toString();
            TVStringa.setText(Indirizzo);
        }
    }


    public LatLng getLocationFromAddress(String strAddress) {
        /**
         * A class for handling geocoding and reverse geocoding.
         * Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.
         * Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.
         * The amount of detail in a reverse geocoded location description may vary,
         * for example one might contain the full street address of the closest building,
         * while another might contain only a city name and postal code.
         *
         * See more at: https://developer.android.com/reference/android/location/Geocoder.html
         */
        Geocoder coder = new Geocoder(this);

        //A list because of getFromLocationName will return a list of address depending on how many result I want
        List<Address> address;
        LatLng p1 = null;

        try {
            /**
             * List<Address> getFromLocationName (String locationName, int maxResults)             *
             * | locationName | String: |           a user-supplied description of a location                      |
             * | maxResults   |   int:  |max number of results to return. Smaller numbers (1 to 5) are recommended |
             * See more at: https://developer.android.com/reference/android/location/Geocoder.html
             */
            address = coder.getFromLocationName(strAddress, 2);
            if (address == null) {
                return null;
            }            //I take just the first result even if I've got list of 5 different LAT;LNG results
            Address location = address.get(0);
            location.getLatitude();
            location.getLongitude();
            p1 = new LatLng(location.getLatitude(), location.getLongitude());
            return p1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return p1;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.mapView = googleMap;
        /*LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(Marker in Sydney));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/


        LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());
        //LatLng myAddressCoordinates = getLocationFromAddress(Piazza Ferretto Mestre);
        mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));
        mapView.moveCamera(CameraUpdateFactory.newLatLngZoom(myAddressCoordinates, 16));
    }
}
Publicado el 11/04/2018 a las 12:52
fuente por usuario
En otros idiomas...                            


1 respuestas

votos
0

Aparte de la gestión de errores en general, tendrá que coordinar la carga de mapa y la carga JSON de tal manera que cuando la carga está completa JSON el mapa está disponible para su uso.

Esto es sólo una manera de resolver esa condición carrera.

Retire (moverlo a onMapReady) la llamada a getJSON(url)partir de suonCreate

Modificar onMapReadypara iniciar la carga JSON (y eliminar las getLocationFromAddressoperaciones de llamada y del mapa):

public void onMapReady(GoogleMap googleMap) {
   this.mapView = googleMap;
   getJSON(url);
 }

Actualizar el postExecutede su AsyncTask:

protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
        loadIntoTextView(s);

        // MOVED FROM onMapReady
        LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());
          //LatLng myAddressCoordinates = getLocationFromAddress("Piazza Ferretto Mestre");
          mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));
          mapView.moveCamera(CameraUpdateFactory.newLatLngZoom(myAddressCoordinates, 16));

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Respondida el 11/04/2018 a las 13:25
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more