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

Posted

技术标签:

【中文标题】获取当前位置时尝试调用虚方法【英文标题】:Attempt to invoke virtual method when getting current location 【发布时间】:2015-05-17 12:32:48 【问题描述】:

我正在尝试使用 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 ComponentInfocreativedreams.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)

【问题讨论】:

【参考方案1】:

去掉MainActivity的构造函数,在onCreate中调用buildGoogleApiClient()

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

    buildGoogleApiClient();

【讨论】:

【参考方案2】:

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

【讨论】:

以上是关于获取当前位置时尝试调用虚方法的主要内容,如果未能解决你的问题,请参考以下文章

尝试调用虚方法

尝试在空对象引用上调用虚方法'double android.location.Location.getLatitude()'[duplicate]

如何解决“调用纯虚方法”

片段通信问题(尝试调用虚方法)

关于C++设计模式的问题,纯虚方法调用

SearchView 尝试在空引用上调用虚方法