获取当前位置时尝试调用虚方法

时间:2015-05-17 12:32:49

标签: java android geolocation google-play google-play-services

我正在尝试使用Google Play服务获取当前位置。以下是我的代码。

public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    public double latitude;

    public double longitude;

    public static final String TAG = MainActivity.class.getSimpleName();

    private GoogleApiClient mGoogleApiClient = null;

    protected Location mLastLocation;

    // Some butterknife code

    public MainActivity() {
        buildGoogleApiClient();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
    }

    /**
     * Build a GoogleApiClient. Used to request Goole Play Services.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            latitude = mLastLocation.getLatitude();
            longitude = mLastLocation.getLongitude();
        } else {
            Toast.makeText(this, getString(R.string.no_location_detected), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, 9000);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Connection failed, ERROR: " + connectionResult.getErrorCode());
        }
    }
}

以下是android studio向我显示的错误消息。

05-17 17:47:59.954  14680-14680/creativedreams.cloudyweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: creativedreams.cloudyweather, PID: 14680
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{creativedreams.cloudyweather/creativedreams.cloudyweather.ui.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
            at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:100)
            at com.google.android.gms.common.api.GoogleApiClient$Builder.<init>(Unknown Source)
            at creativedreams.cloudyweather.ui.MainActivity.buildGoogleApiClient(MainActivity.java:153)
            at creativedreams.cloudyweather.ui.MainActivity.<init>(MainActivity.java:127)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5312)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

2 个答案:

答案 0 :(得分:1)

您应该将此方法buildGoogleApiClient();放在Activity的onCreate()方法中,而不是在构造函数中,因为该活动未在构造函数中完全初始化。

答案 1 :(得分:1)

删除MainActivity的构造函数并在buildGoogleApiClient()

中调用onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.inject(this);

    buildGoogleApiClient();
}