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

标签 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)

最佳答案

移除MainActivity的构造函数并在onCreate中调用buildGoogleApiClient()

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

    buildGoogleApiClient();
}

关于java - 获取当前位置时尝试调用虚拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286894/

相关文章:

java - 将 1D 转换为 2D java.lang.ArrayIndexOutOfBoundsException

android - 在按钮/图像上单击切换抽屉导航 'open'

java - ImageView 区域小于它的实际大小

java - Android 电子邮件编辑文本验证

使用 GeolocationPermissions 的 Android WebView

java - InputStream.read 方法调用速度太快

java - 尝试通过运行 `mvn test` 来运行测试时 JVM 崩溃

java - JPA日期不显示小时/分钟/秒

javascript - 具有 10.000 多个标记的最佳移动商店定位器解决方案

python - 城市/省/州列表与坐标?