有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图调用虚拟方法“int安卓”。电话。gsm。GsmCellLocation。对空对象引用执行getCid()

我面临着这个错误:

E/AndroidRuntime: FATAL EXCEPTION: main                                                          
Process: com.kotak.pck.jaimaasaraswati, PID: 8321
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kotak.pck.jaimaasaraswati/com.kotak.pck.jaimaasaraswati.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int 安卓.telephony.gsm.GsmCellLocation.getCid()' on a null object reference

main活动:

import 安卓.content.Context;
import 安卓.app.Activity;
import 安卓.support.v7.app.ActionBarActivity;
import 安卓.os.Bundle;
import 安卓.telephony.TelephonyManager;
import 安卓.telephony.gsm.GsmCellLocation;
import 安卓.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textGsmCellLocation = (TextView) findViewById(R.id.gsmcelllocation);
        TextView textCID = (TextView) findViewById(R.id.cid);
        TextView textLAC = (TextView) findViewById(R.id.lac);

        //retrieve a reference to an instance of TelephonyManager
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation cellLocation = new GsmCellLocation();
        cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();

        int cid = cellLocation.getCid();
        int lac = cellLocation.getLac();
        textGsmCellLocation.setText("GSM Cell Location: " + cellLocation.toString());
        textCID.setText("GSM Cell id: " + String.valueOf(cid));
        textLAC.setText("GSM Location area code: " + String.valueOf(lac));
    }
}

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    根据documentationgetCellLocation()将返回

    Current location of the device or null if not available.

    它还需要以下权限

    Manifest.permission.ACCESS_FINE_LOCATION
    

    另外,可能是由于LTE造成了问题。根据文件

    If there is only one radio in the device and that radio has an LTE connection, this method will return null.

    此外,您需要使用getAllCellInfo(),因为另一个在API级别26中已被弃用