在地图上显示点时出错

时间:2015-08-01 05:14:39

标签: android eclipse google-maps

我的Android应用程序有点问题 我是android编程的新手,请帮帮我 这是我的FirstActivity.java代码

package com.example.nav;
import android.os.Bundle;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.res.TypedArray;

import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import android.content.Intent;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.widget.EditText;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class FirstActivity extends BaseActivity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;

Button btnGPSShowLocation;
Button btnNWShowLocation;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
    set(navMenuTitles, navMenuIcons);

    appLocationService = new AppLocationService(FirstActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (GPS): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("GPS");
            }
        }
    });

    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation(LocationManager.NETWORK_PROVIDER);

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("NETWORK");
            }
        }
    });

    Button btnShow = (Button) findViewById(R.id.btn_show);
    btnShow.setOnClickListener(new OnClickListener() {          
        @Override
        public void onClick(View arg0) {
            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            double latitude = gpsLocation.getLatitude();
            double longitude = gpsLocation.getLongitude();

            Intent intent = new Intent(getBaseContext(), MapActivity.class);

            // Passing latitude and longitude to the MapActiv
            intent.putExtra("lat", latitude);
            intent.putExtra("lng", longitude);

            startActivity(intent);          
            finish();
        }
    });
}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            FirstActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog
            .setMessage(provider + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    FirstActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

这是我的MapActivity.java代码

  package com.example.nav;

  import android.os.Bundle;
  import android.support.v4.app.FragmentActivity;
  import android.view.Menu;

  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.LatLng;
  import com.google.android.gms.maps.model.MarkerOptions;

  public class MapActivity extends FragmentActivity{

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    // Receiving latitude from MainActivity screen
    double latitude = getIntent().getDoubleExtra("lat", 0);

    // Receiving longitude from MainActivity screen
    double longitude = getIntent().getDoubleExtra("lng", 0);

    LatLng position = new LatLng(latitude, longitude);

    // Instantiating MarkerOptions class
    MarkerOptions options = new MarkerOptions();

    // Setting position for the MarkerOptions
    options.position(position);

    // Setting title for the MarkerOptions
    options.title("Position");

    // Setting snippet for the MarkerOptions
    options.snippet("Latitude:"+latitude+",Longitude:"+longitude);

    // Getting Reference to SupportMapFragment of activity_map.xml
    SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting reference to google map
    GoogleMap googleMap = fm.getMap();

    // Adding Marker on the Google Map
    googleMap.addMarker(options);

    // Creating CameraUpdate object for position
    CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);

    // Creating CameraUpdate object for zoom
    CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);

    // Updating the camera position to the user input latitude and longitude
    googleMap.moveCamera(updatePosition);

    // Applying zoom to the marker position
    googleMap.animateCamera(updateZoom);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

这是我的appLocationService.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

这里我试图从FirstActivity.java向MapActivity.java发送纬度和经度,因此它可以根据纬度和经度显示谷歌地图中的一个点。 但相反,我得到了一个错误

这里是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nav"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="17" />

<permission
    android:name="com.example.nav.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.example.nav.permission.MAPS_RECEIVE"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".FirstActivity"
        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=".SecondActivity" />
    <activity android:name=".MapActivity" />

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="MY_KEY" />
</application>

这是我的logcat

08-01 11:45:52.211: E/AndroidRuntime(2021): java.lang.NullPointerException
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.example.nav.FirstActivity$3.onClick(FirstActivity.java:97)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.view.View.performClick(View.java:4204)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.view.View$PerformClick.run(View.java:17355)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Handler.handleCallback(Handler.java:725)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Looper.loop(Looper.java:137)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 11:45:52.211: E/AndroidRuntime(2021): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 11:45:52.211: E/AndroidRuntime(2021): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 11:45:52.211: E/AndroidRuntime(2021): at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

如果变量 gpsLocation 为空,则会出现此异常。它应该从 appLocationService 中获取它的价值。 我可以看到你在

中创建了一个新的appLocationService
appLocationService = new AppLocationService(FirstActivity.this);

确保您已启动该服务(启动service()方法)。

同样改变这个:

Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {          
    @Override
    public void onClick(View arg0) {
        Location gpsLocation = appLocationService
                .getLocation(LocationManager.GPS_PROVIDER);

                double latitude = gpsLocation.getLatitude();
        double longitude = gpsLocation.getLongitude();

        Intent intent = new Intent(getBaseContext(), MapActivity.class);

        // Passing latitude and longitude to the MapActiv
        intent.putExtra("lat", latitude);
        intent.putExtra("lng", longitude);

        startActivity(intent);          
        finish();
    }
});

对此:

 Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {          
    @Override
    public void onClick(View arg0) {
        Location gpsLocation = appLocationService
                .getLocation(LocationManager.GPS_PROVIDER);

        if(gpsLocation==null){
            //if no location found create one
            gpsLocation =new Location("");  
            gpsLocation.setLatitude(20.75d);
            gpsLocation.setLongitude(44.9d);
        }
        double latitude = gpsLocation.getLatitude();
        double longitude = gpsLocation.getLongitude();

        Intent intent = new Intent(getBaseContext(), MapActivity.class);

        // Passing latitude and longitude to the MapActiv
        intent.putExtra("lat", latitude);
        intent.putExtra("lng", longitude);

        startActivity(intent);          
        finish();
    }
});