i'm currently working on a Android application which draw a navigation Path from current location to a specific place selected on a spinner. This is my first Android application it works great so far but when i click the button to draw the navigation line the application crashes with an NullPointerException and i have absolutely no idea why? Maybe someone here can figure this out. I know what a NullPointerException is, but i cant understand where my issue in the code is. Searching 3 days now. Please can someone help me.
For testing purposes i decide to set preset LatLng's in getMapsApiDirectionsUrl().
This is the class which contains the error:
package com.example.dl.myapplication;
/**
* Created by dl on 30.11.15.
*/
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapShow extends AppCompatActivity implements OnMapReadyCallback {
private static final LatLng Sontheim = new LatLng(49.12194, 9.21092);
private static final LatLng Eurpaplatz = new LatLng(49.148396, 9.2164799);
private static final LatLng Kuenzelsau = new LatLng(49.2755224, 9.71216623);
private static final LatLng Schwaebisch_Hall = new LatLng(49.1125398, 9.7436008);
private GoogleMap mMap;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings2) {
return true;
}
if (id == R.id.action_settings3) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapshow);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
// 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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setMapType(googleMap.MAP_TYPE_NORMAL);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(49.12194, 9.21092), 15.0f));
// mMap.addMarker(new MarkerOptions().position(new LatLng(49.12194, 9.21092)).title("Hochschule Heilbronn - Campus Sontheim"));
//Calculate Direction
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.dl.myapplication/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.dl.myapplication/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private String getMapsApiDirectionsUrl() {
/*location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng destination;
String spinner_value = spinner.getSelectedItem().toString();
// Get Destination
if (spinner_value.equals(getResources().getString(R.string.eu_name))){
destination = EUROPAPLATZ;
} else if (spinner_value.equals(getResources().getString(R.string.ku_name))){
destination = KUENZELSAU;
} else if (spinner_value.equals(getResources().getString(R.string.sh_name))){
destination = SCHWAEBISCH_HALL;
} else {
destination = SONTHEIM;
}*/
// Check if location is available nicht vergessen!!!
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
//urlString.append(Double.toString(location.getLatitude()));
urlString.append(Sontheim.latitude);
urlString.append(",");
urlString.append(Sontheim.longitude);
urlString.append("&destination=");// to
urlString.append(Kuenzelsau.latitude);
urlString.append(",");
urlString.append(Kuenzelsau.latitude);
urlString.append("&sensor=false&mode=driving&alternatives=true");
/*double midpoint_lat = (location.getLatitude() + destination.latitude) / 2;
double midpoint_lng = (location.getLongitude() + destination.longitude) / 2;
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())));
mMap.addMarker(new MarkerOptions().position(destination));
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(midpoint_lat, midpoint_lng)));*/
// dynamisches zoom level hinzufügen falls möglich
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
return urlString.toString();
}
private class ReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
//Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
@Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points;
points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(5);
polyLineOptions.color(Color.BLUE);
}
mMap.addPolyline(polyLineOptions);
}
}
}
and this is the error log:
FATAL EXCEPTION: main Process: com.example.dl.myapplication, PID: 2251 java.lang.NullPointerException: Attempt to read from field 'float com.google.android.gms.maps.model.PolylineOptions.c' on a null object reference at com.google.maps.api.android.lib6.d.aw.(Unknown Source) at com.google.maps.api.android.lib6.d.eu.a(Unknown Source) at com.google.android.gms.maps.internal.j.onTransact(SourceFile:137) at android.os.Binder.transact(Binder.java:380) at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addPolyline(Unknown Source) at com.google.android.gms.maps.GoogleMap.addPolyline(Unknown Source) at com.example.dl.myapplication.MapShow$ParserTask.onPostExecute(MapShow.java:272) at com.example.dl.myapplication.MapShow$ParserTask.onPostExecute(MapShow.java:225) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) 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:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)