簡體   English   中英

android應用程序停止並進行最后的位置檢查

[英]android app stops with last location check

我正在嘗試將設備的位置放到我的android應用中。 我試圖使用android開發者網站上概述的指南,但是,每當我在手機上運行代碼時,該應用就會立即停止。 我的代碼是:

public class MainActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener{

    protected static final String TAG = "MainActivity";

    protected GoogleApiClient mGoogleApiClient;

    protected Location mLastLocation;
    protected Double lonValue;
    protected Double latValue;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;

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

        TextView lonView = (TextView) findViewById(R.id.lon);

        buildGoogleApiClient();

        //connect to parse backend
        Parse.initialize(this, "xxxx", "xxxx");
        ParseInstallation.getCurrentInstallation().saveInBackground();
        Log.d("myInstallation Id", ParseInstallation.getCurrentInstallation().getInstallationId());

        //get location
        lonValue = mLastLocation.getLatitude();
        latValue = mLastLocation.getLongitude();

        //text update

    }

    public void openLocation(View v){
        startActivity(new Intent(MainActivity.this, LocationActivity.class));
    }

    @Override
    public void onConnected(Bundle bundle) {

        //check build version on phone
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //check that app has permission to access data
            if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //get information from location service
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                Log.d(TAG,mLatitudeLabel);
            }
        }

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);


        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.

        buildGoogleApiClient();

        Toast.makeText(MainActivity.this, "Should have network", Toast.LENGTH_SHORT).show();
    }

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

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

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

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

}

日志貓

02-28 18:45:08.848 4048-4048 / com.worcestercomputing.ryanlambert.toiletstall E / AndroidRuntime:FATAL EXCEPTION:main Process:com.worcestercomputing.ryanlambert.toiletstall,PID:4048 java.lang.RuntimeException:無法啟動活動ComponentInfo {com.worcestercomputing.ryanlambert.toiletstall / com.worcestercomputing.ryanlambert.toiletstall.MainActivity}:java.lang.NullPointerException:嘗試在null對象引用處調用虛擬方法“ double android.location.Location.getLatitude()” android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)在android.app.ActivityThread.-wrap11(ActivityThread.java)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)(位於android.os.Handler.dispatchMessage(Handler.java:102)(位於android.os.Looper.loop(Looper.java:148)),位於android.app.ActivityThread.main(ActivityThread) .java:5417),位於java.lang.reflect.Method.invoke(本機方法),位於c om.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)原因:java.lang.NullPointerException:嘗試執行在android.app.Activity.performCreate(Activity.com.worcestercomputing.ryanlambert.toiletstall.MainActivity.onCreate(MainActivity.java:63)上的空對象引用上調用虛擬方法“ double android.location.Location.getLatitude()”。於android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)處的java:6251)於android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)處的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)處android.os.Handler.dispatchMessage(Handler.java:102)上的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)上的android.app.ActivityThread.-wrap11(ActivityThread.java)。 java.lang.reflect.M的android.app.ActivityThread.main(ActivityThread.java:5417)的Looper.loop(Looper.java:148) com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)上的ethod.invoke(本機方法)com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)上的ethod.invoke(MethodAndArgsCaller.run(ZygoteInit.java:726)

顯然,問題在於您致電

//get location
lonValue = mLastLocation.getLatitude();
latValue = mLastLocation.getLongitude();

Activity.onCreate() 但是, mLastLocation仍為null

請注意, onCreate(Bundle)是您在其中初始化活動的活動生命周期回調-創建活動的新實例時,這是要調用的第一件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM