I have no clue why the following piece of code is giving null pointer exception.Please help! This is the MapActivity.class.
package com.dutt.rishabh.locator;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.net.http.AndroidHttpClient;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText start, finish;
Button bsearch, btype;
String source, destiny,url;
List<LatLng> lines=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
start = (EditText) findViewById(R.id.start);
finish = (EditText) findViewById(R.id.finish);
bsearch = (Button) findViewById(R.id.bsearch);
btype = (Button) findViewById(R.id.btype);
start.setText(R.string.source);
finish.setText(R.string.destiny);
source = start.getText().toString();
destiny = finish.getText().toString();
Geocoder geocoder=new Geocoder(this);
List<Address> x=null;
List<Address> y=null;
try {
x=geocoder.getFromLocationName(source,1);
y=geocoder.getFromLocationName(destiny,1);
} catch (IOException e) {
e.printStackTrace();
}
Address origin,destination;
origin=x.get(0);
destination=y.get(0);
url="http://maps.googleapis.com/maps/api/directions/json?origin="
+ origin.getLatitude() + "," + origin.getLongitude() +"&destination="
+ destination.getLatitude() + "," + destination.getLongitude() + "&sensor=false";
changeMapType();
JSONObject result = null;
try {
result = new JSONObject(fetchData());
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray routes = null;
try {
routes = result.getJSONArray("routes");
} catch (JSONException e) {
e.printStackTrace();
}
try {
long distanceForSegment = routes.getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getInt("value");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray steps = null;
try {
steps = routes.getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps");
} catch (JSONException e) {
e.printStackTrace();
}
lines = new ArrayList<LatLng>();
for(int i=0; i < steps.length(); i++) {
String polyline = null;
try {
polyline = steps.getJSONObject(i).getJSONObject("polyline").getString("points");
} catch (JSONException e) {
e.printStackTrace();
}
for(LatLng p : decodePolyline(polyline)) {
lines.add(p);
}
}
}
private List<LatLng> decodePolyline(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(p);
}
return poly;
}
public String fetchData(){
HttpResponse response = null;
HttpGet request;
AndroidHttpClient client = AndroidHttpClient.newInstance("somename");
request = new HttpGet(url);
try {
response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
InputStream source = null;
try {
source = response.getEntity().getContent();
} catch (IOException e) {
e.printStackTrace();
}
String returnValue = buildStringIOutils(source);
return returnValue;
}
private String buildStringIOutils(InputStream is) {
try {
return IOUtils.toString(is, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void changeMapType() {
btype.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mMap.getMapType() == mMap.MAP_TYPE_NORMAL) {
mMap.setMapType(mMap.MAP_TYPE_HYBRID);
} else {
mMap.setMapType(mMap.MAP_TYPE_NORMAL);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng bangalore = new LatLng(12.9716, 77.5946);
mMap.addMarker(new MarkerOptions().position(bangalore).title("Marker in Bangalore"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(bangalore));
mMap.setBuildingsEnabled(true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
Polyline polylineToAdd = mMap.addPolyline(new PolylineOptions().addAll(lines).width(3).color(Color.RED));
}
}
The following is the logcat error.
07-23 13:43:36.300 11999-11999/com.dutt.rishabh.locator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dutt.rishabh.locator, PID: 11999
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dutt.rishabh.locator/com.dutt.rishabh.locator.MapsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.dutt.rishabh.locator.MapsActivity.onCreate(MapsActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
I have no clue why it is giving a null pointer exception.Please help.Thank you!