我在代码的getLatitude和getLongitude区域出现Null指针异常错误。如何解决此问题。 那是我的主要挑战。因为我的应用程序每次都会崩溃,所以请帮忙,因为它会引起很大的不满
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Restaurant extends FragmentActivity implements LocationListener {
private final int MAX_PLACES = 20;
private GoogleMap theMap;
private LocationManager locMan;
private Marker userMarker;
private int defautltId, restaurantId;
private Marker[] placeMarkers;
private MarkerOptions[] places;
String apiKey;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_map);
defautltId = R.drawable.ic_default;
restaurantId = R.drawable.ic_restaurant;
apiKey = getResources().getString(R.string.google_maps_key);
if (theMap == null) {
//map not instantiated yet
theMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.the_map)).getMap();
if (theMap != null) {
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
placeMarkers = new Marker[MAX_PLACES];
//update places
updatePlaces();
}
}
}
private void updatePlaces() {
//update location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastloc != null) {
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
}
LatLng lastLatLng = new LatLng(lat, lng);
if (userMarker != null) {
userMarker.remove();
}
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(defautltId))
.snippet("Your last recorded location"));
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location=" + lat + "," + lng +
"&radius=3000" +
"&types=food|bar" + "&key=" + apiKey + "&sensor=true";
//Reference for searching through url
//https://maps.googleapis.com/maps/api/place/radarsearch/
// json?radius=200&key=AIzaSyDPVYhZDzHdxRGnqqHZSWccL-BEe-JSYXA
// &location=-33.86705220%2C151.19573620&keyword=attractions
//My Add
// https://maps.googleapis.com/maps/api/place/nearbysearch/
// json?location=51.503186,-0.126446&radius=1000&sensor=true&types=food|bar
// &key=AIzaSyCBQyZ8lxV5vmLDMQRAuVBHIeBGnURpfCo&keyword=restaurants
//Reference add
//https://maps.googleapis.com/maps/api/place/radarsearch/json?
// location=51.503186,-0.126446&radius=5000
// &keyword=health&key=AIzaSyCshx_mxH4pJlxZAEfdHK4o012zZfitwX0
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
@Override
protected void onResume() {
super.onResume();
if (theMap != null) {
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
}
@Override
protected void onPause() {
super.onPause();
if (theMap != null) {
locMan.removeUpdates(this);
}
}
@Override
public void onLocationChanged(Location location) {
Log.v("Restaurant", "location changed");
updatePlaces();
}
@Override
public void onProviderDisabled(String provider) {
Log.v("Restaurant", "provider disabled");
}
@Override
public void onProviderEnabled(String provider) {
Log.v("Restaurant", "provider enabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("Restaurant", "status changed");
}
private class GetPlaces extends AsyncTask<String, Void, String> {
//fetch and parse place data
//yak4woundei@yahoo.com
@Override
protected String doInBackground(String... placesURL) {
//fetch places
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return placesBuilder.toString();
}
protected void onPostExecute(String result) {
//parse place data returned from Google Places
if (placeMarkers != null) {
for (int pm = 0; pm < placeMarkers.length; pm++) {
if (placeMarkers[pm] != null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
JSONObject resultObject = new JSONObject(result);
JSONArray placesArray = resultObject.getJSONArray("results");
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p = 0; p < placesArray.length(); p++) {
//parse each place
boolean missingValue = false;
LatLng placeLL = null;
String placeName = "";
String vicinity = "";
int currIcon = restaurantId;
try {
//attempt to retrieve place data values
missingValue = false;
JSONObject placeObject = placesArray.getJSONObject(p);
JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
placeLL = new LatLng(
Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
JSONArray types = placeObject.getJSONArray("types");
for (int t = 0; t < types.length(); t++) {
//what type is it
String thisType = types.get(t).toString();
if (thisType.contains("food")) {
currIcon = restaurantId;
break;
}
}
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
} catch (JSONException jse) {
missingValue = true;
jse.printStackTrace();
}
if (missingValue) places[p] = null;
else
places[p] = new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
} catch (Exception e) {
e.printStackTrace();
}
if (places != null && placeMarkers != null) {
for (int p = 0; p < places.length && p < placeMarkers.length; p++) {
//will be null if a value was missing
if (places[p] != null)
placeMarkers[p] = theMap.addMarker(places[p]);
}
}
}
}
}
Log cat:
11-17 20:30:40.532 17851-17851/www.uneditedmap.com.locationandmap E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: www.uneditedmap.com.locationandmap, PID: 17851
java.lang.RuntimeException: Unable to start activity ComponentInfo{www.uneditedmap.com.locationandmap/www.uneditedmap.com.locationandmap.Restaurant}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at www.uneditedmap.com.locationandmap.Restaurant.updatePlaces(Restaurant.java:71)
at www.uneditedmap.com.locationandmap.Restaurant.onCreate(Restaurant.java:62)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)