You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Android Studio中java.lang.NullPointerException定位异常问题

解决LocationManager空指针异常问题

问题根源

报错核心原因:你在按钮点击事件里创建了局部变量nManager获取系统位置服务,但从未给类成员变量locationManager赋值,后续调用locationManager.isProviderEnabled()时,成员变量仍为null,触发空指针异常。

修复步骤

  1. 在onCreate方法中初始化成员变量locationManager,而非在点击事件内创建局部变量
  2. 每次使用locationManager前,先判断是否为null(避免系统服务获取失败的极端情况)

修改后的完整代码

MainActivity.java

package com.example.map;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_LOCATION = 1;
    Button btnGetLocation;
    TextView showLocation;
    LocationManager locationManager;
    String latitude, longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        showLocation = findViewById(R.id.showLocation);
        btnGetLocation = findViewById(R.id.btnGetLocation);
        
        // 初始化成员变量locationManager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        btnGetLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 先判断locationManager是否为空
                if (locationManager == null) {
                    Toast.makeText(MainActivity.this, "无法获取位置服务", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    OnGPS();
                } else {
                    getLocation();
                }
            }
        });
    }

    private void OnGPS() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void getLocation() {
        if (locationManager == null) {
            Toast.makeText(this, "无法获取位置服务", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (ActivityCompat.checkSelfPermission(
                MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        } else {
            Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (locationGPS != null) {
                double lat = locationGPS.getLatitude();
                double longi = locationGPS.getLongitude();
                latitude = String.valueOf(lat);
                longitude = String.valueOf(longi);
                showLocation.setText(String.format("%s\n%s%s\n%s%s", getString(R.string.your_location), getString(R.string.latitude), latitude, getString(R.string.longitude), longitude));
            } else {
                Toast.makeText(this, "Unable to find location.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

额外优化建议

  • 补充权限申请回调:当前代码直接请求权限,但未重写onRequestPermissionsResult方法,建议添加该方法,在用户授权后重新尝试获取位置
  • 改用Google推荐的FusedLocationProviderClient:融合位置服务比原生LocationManager更稳定,适配性更强

内容的提问来源于stack exchange,提问作者Asok M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:26:19