我正在尝试开发基于位置的应用。我尝试绘制路线,但程序返回NullPointerException
。
我在第361行遇到了这个问题。
package com.example.tcarcelik.glympse;
/**
* Created by TCARCELIK on 09.07.2015.
*/
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.ads.formats.NativeContentAd;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MapsActivity extends FragmentActivity implements Parcelable,LocationListener {
LatLng destination;
Polyline line;
Button mBtnDest;
Button btnDraw;
Button btnOk;
Button btnNextStep;
int counter;
GoogleMap mMap;
EditText editPlace_Dest;
ArrayList<LatLng> markerPoints;
ArrayList<LatLng> list;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
double mLatitude = 0;
double mLongitude = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
markerPoints = new ArrayList<LatLng>();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
Criteria criteria = new Criteria();
btnDraw = (Button) findViewById(R.id.btn_draw);
btnOk = (Button) findViewById(R.id.btn_ok);
mMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
destination = point;
mMap.clear();
drawMarker(point);
markerPoints.add(point);
FrameLayout mapLayout = (FrameLayout)findViewById(R.id.map);
btnDraw.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
double lat1 = mMap.getMyLocation().getLatitude();
double long1 = mMap.getMyLocation().getLongitude();
LatLng latlng = new LatLng(lat1, long1);
String url = getDirectionsUrl(latlng, destination);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
});
// Button of OK
btnOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("listToPass", list);
// CameraPosition myCam = mMap.getCameraPosition();
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mainbound,100));
CameraPosition myCam = mMap.getCameraPosition();
i.putExtra("cameraPosition", myCam);
startActivity(i);
}
});
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, (LocationListener) this);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
// setUpMap();
}
}
}
public GoogleMap get_MapsMap(){
return mMap;
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
ProgressDialog progressDialog;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
// Draw path'in onPostExecute ' u
@Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
drawPath(result); // Ben ekledim
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
}
@Override
protected void onPreExecute() {
if(progressDialog == null){
progressDialog = new ProgressDialog(MapsActivity.this);
progressDialog.setMessage("Drawing route");
progressDialog.show();
}
}
}
/** A class to parse the Geocoding Places in non-ui thread */
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
}
}
//YENI EKLENENLER
private void drawMarker(LatLng point){
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
mMap.addMarker(options);
}
public void drawPath(String result){
try {
final JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = (ArrayList<LatLng>) decodePoly(encodedString);
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = mMap.addPolyline(options);
// Animate camera after drawing route
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mainbound, 100));
// Animate camera after drawing route
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.moveCamera(cameraUpdate);
locationManager.removeUpdates((LocationListener) this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//YENI EKLENENLER
private List<LatLng> decodePoly(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 void onMyLocationChange(Location location) {
// TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
@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;
}
}
答案 0 :(得分:0)
请调试并确保您正确下载文件,检查downloadUrl(String strUrl)方法并确保它到达第256行。我相信问题在于下载方法。