【问题标题】:android app stops with last location checkandroid 应用程序停止最后一次位置检查
【发布时间】:2016-06-11 17:29:20
【问题描述】:

我正在尝试将设备的位置信息输入到我的 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: 致命异常: main 进程:com.worcestercomputing.ryanlambert.toiletstall,PID:4048 java.lang.RuntimeException:无法启动活动 组件信息{com.worcestercomputing.ryanlambert.toiletstall/com.worcestercomputing.ryanlambert.toiletstall.MainActivity}: java.lang.NullPointerException:尝试调用虚拟方法 空对象上的“双 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(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 引起:java.lang.NullPointerException:尝试调用虚拟 方法 'double android.location.Location.getLatitude()' 在 null 对象引用 在 com.worcestercomputing.ryanlambert.toiletstall.MainActivity.onCreate(MainActivity.java:63) 在 android.app.Activity.performCreate(Activity.java:6251) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 在 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(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

【问题讨论】:

  • 能否请您也发布 logcat..
  • 你是在模拟器上运行它吗?您必须分别传递纬度和经度才能在模拟器上运行位置。此外,在现实生活中,getLastLocation 有时会返回 null(用户可能从购买手机之日起就禁用了定位),因此您应该执行 null 检查。
  • 我在物理设备上运行。我怎么能对此进行空检查? (对不起,只是学习绳索)
  • 使用简单的 if/else 语句就可以了。检查 mLastLocation 是否为空,仅当它不为空时才使用 getLatitude。另外,Parse 将在今年年底失效,您应该尽快更换它的功能。
  • 实现一个位置监听器会让事情变得非常容易。

标签: java android geolocation location


【解决方案1】:

显然,问题是你打电话

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

Activity.onCreate()。 但是当时mLastLocation还是null

请注意,onCreate(Bundle) 是 Activity 生命周期回调,您可以在其中初始化 Activity - 它是创建 Activity 的新实例时首先调用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    相关资源
    最近更新 更多