我在Eclipse上有一个Navigation项目,想在Android Studio上运行它,它在API 10设备上运行。当我尝试在API 15设备上运行时,MapActivity
会自动关闭我的应用。
返回空指针异常。我开始知道它必须改为Map Fragment,我不知道如何改变它?
我的MapActivity
Java代码如下: -
public class NaviMap extends MapActivity {
MockLocProvider mockProvider;
ArrayList<Step> steps = new ArrayList<Step>();
Step curStep;
TextToSpeech tts;
FixedMyLocationOverlay myLoc;
MapView mv;
MapController mapcontrol;
ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();
static List<Overlay> mapitems;
LocationManager lm;
Drawable dr;
Location from, to;
Context cntx;
ProgressDialog pd;
boolean lastStep = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.navi_map);
from = this.getIntent().getExtras().getParcelable("from");
to = this.getIntent().getExtras().getParcelable("to");
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
tts = new TextToSpeech(this, onInit);
cntx = this;
dr = cntx.getResources().getDrawable(R.drawable.marker);
mv = (MapView) findViewById(R.id.interMap);
mv.setBuiltInZoomControls(true);
mapcontrol = mv.getController();
mapcontrol.setZoom(20);
mapitems = mv.getOverlays();
myLoc = new FixedMyLocationOverlay(this, mv);
GetJson getDir = new GetJson();
getDir.execute();
myLoc.enableMyLocation();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
tts.stop();
tts.shutdown();
mockProvider.shutdown();
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
myLoc.disableMyLocation();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
myLoc.enableMyLocation();
}
TextToSpeech.OnInitListener onInit = new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS)
{
int res = tts.setLanguage(Locale.US);
if(res == TextToSpeech.LANG_MISSING_DATA ||
res == TextToSpeech.LANG_NOT_SUPPORTED)
Toast.makeText(cntx, "Unable to Initialize Text-to-Speech engine", Toast.LENGTH_LONG).show();
else
speak("Getting data, please wait", TextToSpeech.QUEUE_FLUSH);
}
else
Toast.makeText(cntx, "Unable to Initialize Text-to-Speech engine", Toast.LENGTH_LONG).show();
}
};
LocationListener locListen = new LocationListener(){
@Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
GeoPoint point = new GeoPoint((int) ((loc.getLatitude()) * 1E6),
(int) ((loc.getLongitude()) * 1E6));
mapcontrol.animateTo(point);
float distance = loc.distanceTo(curStep.getEnd());
if(distance <= 2) // reached next step
{
if(lastStep) // reached destination
speak("Reached your destination", TextToSpeech.QUEUE_FLUSH);
else // move to next step
{
curStep = steps.get(0);
steps.remove(0);
if(steps.size() == 0)
lastStep = true;
speak(curStep.getInstruction(), TextToSpeech.QUEUE_FLUSH);
float dist = curStep.getDistance();
String mval;
if(curStep.getDistance() < 1000 )
mval = "Meters";
else
{
dist /= 1000;
mval = "Kilo meteres";
}
speak("Next step in " + dist + mval, TextToSpeech.QUEUE_ADD);
}
}
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class InterMapOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapview, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapview, false);
drawPath(mapview, canvas);
}
public void drawPath(MapView mv, Canvas cv) {
int xp=-1, yp=-1, xn=-1, yn=-1;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(5);
paint.setAlpha(100);
if(points != null)
{
for(int i = 0; i < points.size(); i++)
{
GeoPoint curPoint = points.get(i);
Point point = new Point();
mv.getProjection().toPixels(curPoint, point);
xn = point.x;
yn = point.y;
if( xp != -1 )
cv.drawLine(xp, yp, xn, yn, paint);
xp = xn;
yp = yn;
}
}
}
}
public ArrayList<GeoPoint> decodePoly(String encoded) {
ArrayList<GeoPoint> poly = new ArrayList<GeoPoint>();
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;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
public class GetJson extends AsyncTask<Void, Address, Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
points.clear();
mapitems.clear();
pd = new ProgressDialog(cntx);
pd.setCancelable(false);
pd.setMessage("Getting routes...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + from.getLatitude() + "," + from.getLongitude() +
"&destination=" + to.getLatitude() + "," + to.getLongitude() + "&sensor=true&units=metric&mode=walking";
try {
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse res = cli.execute(post);
InputStream in = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
reader.close();
// decoding JSON data..
JSONObject obj = new JSONObject(sb.toString());
JSONArray array = obj.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONObject route_polyline = routes.getJSONObject("overview_polyline");
String encoded = route_polyline.getString("points");
points = decodePoly(encoded);
// getting STEPS details...
JSONArray legs = routes.getJSONArray("legs");
JSONObject leg1 = legs.getJSONObject(0);
JSONArray jsteps = leg1.getJSONArray("steps");
for(int i = 0; i < jsteps.length(); i++)
{
JSONObject jstep = jsteps.getJSONObject(i);
Step step = new Step();
// getting distance
JSONObject jdis = jstep.getJSONObject("distance");
step.setDistance(jdis.getInt("value"));
// getting duration
JSONObject jdur = jstep.getJSONObject("duration");
step.setDuration(jdur.getInt("value") / 60);
// getting instruction
step.setInstruction(Html.fromHtml(jstep.getString("html_instructions")).toString());
// getting starting point
JSONObject jstart = jstep.getJSONObject("start_location");
Location start = new Location(LocationManager.NETWORK_PROVIDER);
start.setLatitude(jstart.getDouble("lat"));
start.setLongitude(jstart.getDouble("lng"));
step.setStart(start);
// getting end point
JSONObject jend = jstep.getJSONObject("end_location");
Location end = new Location(LocationManager.NETWORK_PROVIDER);
end.setLatitude(jend.getDouble("lat"));
end.setLongitude(jend.getDouble("lng"));
step.setEnd(end);
steps.add(step);
}
}
catch(Exception e) {
e.printStackTrace();
speak("Unable to get Route data", TextToSpeech.QUEUE_ADD);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub]
mapcontrol.animateTo(points.get(0));
StageOverlay stageOverlay = new StageOverlay(dr, cntx);
stageOverlay.addOverlay(new OverlayItem(points.get(0), "Source", "Source"));
stageOverlay.addOverlay(new OverlayItem(points.get(points.size() - 1), "Destination", "Destination"));
mapitems.add(stageOverlay);
mapitems.add(new InterMapOverlay());
mapitems.add(myLoc);
mv.postInvalidate();
mv.invalidate();
pd.dismiss();
curStep = steps.get(0);
steps.remove(0);
if(steps.size() == 0)
lastStep = true;
speak("Start walking by Instruction, " + curStep.getInstruction(), TextToSpeech.QUEUE_ADD);
speak("Next step in " + curStep.getDistance() + " meters", TextToSpeech.QUEUE_ADD);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListen);
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListen);
mockProvider = new MockLocProvider(LocationManager.NETWORK_PROVIDER, cntx, points);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListen);
mockProvider.start();
}
}
private void speak(String text, int Mode)
{
tts.speak(text, Mode, null);
}
}
XML代码如下: -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.maps.MapView
android:id="@+id/interMap"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0QhmZ8LxWHMvKv6YNSv0kAD87EE7xXRzW4EamFg" />
</RelativeLayout>
清单文件如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mani.droid.blindnavigation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name="mani.droid.blindnavigation.HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NaviMap" />
</application>
</manifest>
答案 0 :(得分:0)
在清单中添加此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />